package com.liquidnet.service.consumer.kylin.utils;

import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.service.goblin.constant.GoblinRedisConst;
import com.liquidnet.service.goblin.constant.GoblinStatusConst;
import com.liquidnet.service.goblin.dto.vo.GoblinGoodsSkuInfoVo;
import com.liquidnet.service.goblin.dto.vo.GoblinListCollectVo;
import com.liquidnet.service.goblin.dto.vo.GoblinNftOrderVo;
import com.mongodb.BasicDBObject;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Component
public class GoblinNftUtils {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private MongoConverter mongoConverter;

    private static final BasicDBObject basicDBObject = new BasicDBObject();

    // 库存
    public int decrSkuStock(String skuId, Integer stock) {
        String redisKey = GoblinRedisConst.REAL_STOCK_SKU.concat(skuId);
        return (int) redisUtil.decr(redisKey, stock);
    }

    public int incrSkuStock(String marketPre, String skuId, Integer stock) {
        String rk = GoblinRedisConst.REAL_STOCK_SKU;
        if (marketPre != null && !marketPre.equals("null")) {
            rk = rk.concat(marketPre + ":");
        }
        rk = rk.concat(skuId);
        return (int) redisUtil.incr(rk, stock);
    }

    // 减少 用户sku购买个数
    public int decrSkuCountByUid(String uid, String skuId, int number) {
        String redisKey = GoblinRedisConst.REDIS_GOBLIN_BUY_COUNT.concat(uid + ":skuId:" + skuId);
        return (int) redisUtil.decr(redisKey, number);
    }

    // 订单详情vo
    public void setNftOrder(GoblinNftOrderVo vo) {
        String redisKey = GoblinRedisConst.REDIS_GOBLIN_NFT_ORDER_INFO.concat(vo.getOrderId());
        redisUtil.set(redisKey, vo);
    }

    // 获取 订单详情vo
    public GoblinNftOrderVo getNftOrder(String orderId) {
        String redisKey = GoblinRedisConst.REDIS_GOBLIN_NFT_ORDER_INFO.concat(orderId);
        Object obj = redisUtil.get(redisKey);
        if (obj == null) {
            return null;
        } else {
            return (GoblinNftOrderVo) obj;
        }
    }

    // 订单详情vo
    public void setGoblinNftOrderVo(GoblinNftOrderVo vo) {
        mongoTemplate.insert(vo, GoblinNftOrderVo.class.getSimpleName());
    }

    public UpdateResult updateGoblinNftOrderVo(GoblinNftOrderVo data) {
        BasicDBObject object = cloneBasicDBObject().append("$set", mongoConverter.convertToMongoType(data));
        return mongoTemplate.getCollection(GoblinNftOrderVo.class.getSimpleName()).updateOne(
                Query.query(Criteria.where("orderId").is(data.getOrderId())).getQueryObject(),
                object);
    }

    /**
     * 获取 包含分段购的sku详情 HASHMAP
     *
     * @param now   当前时间
     * @param skuId skuId
     * @return
     */
    public HashMap<String, Object> getGoodsSkuInfoVo(LocalDateTime now, String skuId) {
        GoblinGoodsSkuInfoVo vo = getGoodsSkuInfoVo(skuId);
        List<GoblinListCollectVo> collectVos = getGoblinListCollect(skuId);
        GoblinListCollectVo collectVo = null;
        for (GoblinListCollectVo collectVoItem : collectVos) {
            if (now.isAfter(collectVoItem.getTimeStart()) && now.isBefore(collectVoItem.getTimeEnd())) {
                collectVo = collectVoItem;
                break;
            }
        }
        HashMap<String, Object> map = CollectionUtil.mapStringObject();
        Integer tagType = null;
        String listId = null;
        if (collectVo != null) {
            vo.setPrice(collectVo.getPrice());
            vo.setPriceV(collectVo.getPriceV());
            vo.setProductId(collectVo.getProductId());
            vo.setSaleStartTime(collectVo.getTimeStart());
            vo.setSaleStopTime(collectVo.getTimeEnd());
            tagType = collectVo.getTagType();
            listId = collectVo.getListId();
        }
        map.put("vo", vo);
        map.put("tagType", tagType);
        map.put("listId", listId);
        return map;
    }
    /**
     * 单品信息
     *
     * @param skuId 单品ID
     * @return GoblinGoodsSkuInfoVo
     */
    public GoblinGoodsSkuInfoVo getGoodsSkuInfoVo(String skuId) {
        String pre = GoblinStatusConst.MarketPreStatus.getPre(skuId);
        if (pre != null && pre.equals(GoblinStatusConst.MarketPreStatus.MARKET_PRE_ZHENGZAI.getValue())) {
            String rk = GoblinRedisConst.BASIC_GOODS_SKU.concat(skuId.split(GoblinStatusConst.MarketPreStatus.MARKET_PRE_ZHENGZAI.getValue())[0]);
            GoblinGoodsSkuInfoVo vo = (GoblinGoodsSkuInfoVo) redisUtil.get(rk);
            if (null == vo && null != (vo = getGoodsSkuInfoVoMdb(skuId))) {
                redisUtil.set(rk, vo);
            }
            if (vo == null) {
                return vo;
            }
            String marketrk = GoblinRedisConst.BASIC_GOODS_SKU.concat(skuId);
            GoblinGoodsSkuInfoVo marketVo = (GoblinGoodsSkuInfoVo) redisUtil.get(marketrk);
            if (null == marketVo && null != (marketVo = getGoodsSkuInfoVoMdb(skuId))) {
                redisUtil.set(marketrk, marketVo);
            }
            if (marketVo == null) {
                return marketVo;
            }

            vo.setSpuId(marketVo.getSpuId());
            vo.setSkuId(marketVo.getSkuId());
            vo.setPrice(marketVo.getPrice());
            vo.setPriceMember(marketVo.getPriceMember());
            vo.setSkuStock(marketVo.getSkuStock());
            vo.setBuyLimit(marketVo.getBuyLimit());
            vo.setBuyRoster(marketVo.getBuyRoster());
            vo.setBuyFactor(marketVo.getBuyFactor());
//            vo.setDelFlg("0");
            vo.setDelFlg(marketVo.getDelFlg().equals("1") ? marketVo.getDelFlg() : vo.getDelFlg());
            vo.setMarketId(marketVo.getMarketId());
            vo.setCreatedAt(LocalDateTime.now());
            return vo;
        } else {
            String rk = GoblinRedisConst.BASIC_GOODS_SKU.concat(skuId);
            GoblinGoodsSkuInfoVo vo = (GoblinGoodsSkuInfoVo) redisUtil.get(rk);
            if (null == vo && null != (vo = getGoodsSkuInfoVoMdb(skuId))) {
                redisUtil.set(rk, vo);
            }
            return vo;
        }
    }
    // SKU信息
    public GoblinGoodsSkuInfoVo getGoodsSkuInfoVoMdb(String skuId) {
        return mongoTemplate.findOne(Query.query(Criteria.where("skuId").is(skuId)),
                GoblinGoodsSkuInfoVo.class, GoblinGoodsSkuInfoVo.class.getSimpleName());
    }
    /**
     * 分段购获取
     * @param skuId
     * @return
     */
    public List<GoblinListCollectVo> getGoblinListCollect(String skuId) {
        Object obj = redisUtil.get(GoblinRedisConst.LIST_COLLECT.concat(skuId));
        if (obj == null) {
            return new ArrayList<>();
        } else {
            return (List<GoblinListCollectVo>) obj;
        }
    }

    public static BasicDBObject cloneBasicDBObject() {
        return (BasicDBObject) basicDBObject.clone();
    }

}
