package com.liquidnet.service.goblin.service.impl;

import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.commons.lang.util.CurrentUtil;
import com.liquidnet.service.base.PagedResult;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.goblin.dto.manage.vo.AnticipateValueVo;
import com.liquidnet.service.goblin.dto.vo.*;
import com.liquidnet.service.goblin.service.GoblinCouponService;
import com.liquidnet.service.goblin.service.IGoblinNftGoodsAppService;
import com.liquidnet.service.goblin.service.manage.IGoblinGoodsAnticipateMgService;
import com.liquidnet.service.goblin.util.GoblinMongoUtils;
import com.liquidnet.service.goblin.util.GoblinRedisUtils;
import com.liquidnet.service.goblin.util.ObjectUtil;
import com.liquidnet.service.goblin.util.QueueUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class GoblinNftGoodsAppServiceImpl implements IGoblinNftGoodsAppService {

    @Autowired
    private GoblinRedisUtils goblinRedisUtils;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    QueueUtils queueUtils;
    @Autowired
    GoblinMongoUtils mongoUtils;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    GoblinCouponService goblinCouponService;
    @Autowired
    IGoblinGoodsAnticipateMgService goblinGoodsAnticipateMgService;

    @Override
    public ResponseDto<PagedResult<GoblinNftGoodsSkuListVo>> goodsList(int page) {

        int size = 40;
        //条件
        List<String> skuIdList = goblinRedisUtils.getGoblinNftGoodsInfoListVo();
        List<GoblinNftGoodsSkuListVo> skuList = new ArrayList<>();
        if (null == skuIdList || page > 1) {
            skuIdList = new ArrayList<>();
            // 分页 排序:按照开售时间
            Query query = Query.query(
                    Criteria.where("skuType").is(1)
                            .and("delFlg").is("0")
                            .and("status").is("3")
                            .and("shelvesStatus").is("3")
                            .and("skuAppear").is("0")
            );
            Pageable pageable = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.ASC, "saleStartTime"));
            query.with(pageable);

            List<GoblinGoodsSkuInfoVo> skuInfoVos = mongoTemplate.find(query, GoblinGoodsSkuInfoVo.class, GoblinGoodsSkuInfoVo.class.getSimpleName());
            for (GoblinGoodsSkuInfoVo info : skuInfoVos) {
                //获取预约相关
                AnticipateValueVo anticipateValueVo = goblinGoodsAnticipateMgService.getAnticipateValueBySkuId(info.getSkuId(), 0);
                // sku信息
                GoblinNftGoodsSkuListVo nftGoodsSkuInfoVo = GoblinNftGoodsSkuListVo.getNew().copy(info, anticipateValueVo);
                // spu信息
                GoblinGoodsInfoVo goodsInfoVo = goblinRedisUtils.getGoodsInfoVo(info.getSpuId());
                GoblinNftGoodsSpuInfoVo nftGoodsSpuInfoVo = GoblinNftGoodsSpuInfoVo.getNew().copy(goodsInfoVo);
                nftGoodsSkuInfoVo.setGoblinNftGoodsSpuInfoVo(nftGoodsSpuInfoVo);
                // 写入列表
                skuList.add(nftGoodsSkuInfoVo);
                skuIdList.add(nftGoodsSkuInfoVo.getSkuId());
            }
            if (page <= 1) {
                goblinRedisUtils.setGoblinNftGoodsInfoListVo(skuIdList);
            }
        } else {
            for (String skuId : skuIdList) {
                GoblinGoodsSkuInfoVo goodsSkuInfoVo = goblinRedisUtils.getGoodsSkuInfoVo(skuId);
                GoblinNftGoodsSkuListVo goblinNftGoodsSkuListVo = GoblinNftGoodsSkuListVo.getNew().copy(goodsSkuInfoVo, null);
                skuList.add(goblinNftGoodsSkuListVo);
            }
        }
        for (GoblinNftGoodsSkuListVo skuInfoVo : skuList) {
            int stock = 0;
            if (skuInfoVo.getUnbox().equals("0")) {
                if (null == skuInfoVo.getSoldoutStatus() || skuInfoVo.getSoldoutStatus().equals("0")) {
                    stock = goblinRedisUtils.getSkuStock(null, skuInfoVo.getSkuId());
                }
            } else {
                String spuId = skuInfoVo.getSpuId();
                List<String> skuArray = goblinRedisUtils.getGoodsInfoVo(spuId).getSkuIdList();
                for (String skuIdItem : skuArray) {
                    GoblinGoodsSkuInfoVo itemVo = goblinRedisUtils.getGoodsSkuInfoVo(skuIdItem);
                    stock += goblinRedisUtils.getSkuAllStatusStock(itemVo);
                }
            }
            if (stock <= 0 || (null != skuInfoVo.getSoldoutStatus() && skuInfoVo.getSoldoutStatus().equals("1"))) {
                skuInfoVo.setIsStock(0);
            } else {
                skuInfoVo.setIsStock(1);
            }
        }
        List<GoblinNftGoodsSkuListVo> listSort = skuList.stream().sorted(Comparator.comparing(GoblinNftGoodsSkuListVo::getIsStock).reversed()).collect(Collectors.toList());

        PagedResult<GoblinNftGoodsSkuListVo> listVoPagedResult = ObjectUtil.getGoblinNftGoodsSkuListVoPagedResult();
        listVoPagedResult.setList(listSort).setPageSize(size).setCurrentPage(page);
        return ResponseDto.success(listVoPagedResult);
    }

    @Override
    public GoblinNftGoodsSkuInfoVo goodsDetail(String skuId) {
        GoblinGoodsSkuInfoVo goodsSkuInfoVo = goblinRedisUtils.getGoodsSkuInfoVo(skuId);
        if (goblinRedisUtils.getSkuAllStatusShow(goodsSkuInfoVo)) {
            //获取预约相关
            AnticipateValueVo anticipateValueVo = goblinGoodsAnticipateMgService.getAnticipateValueBySkuId(skuId, 1);

            GoblinNftGoodsSkuInfoVo nftGoodsSkuInfoVo = GoblinNftGoodsSkuInfoVo.getNew().copy(goodsSkuInfoVo, anticipateValueVo);
            // 限购数量
            Integer buyCount = 0;
            String userId = CurrentUtil.getCurrentUid();
            if (StringUtils.isNotBlank(userId)) {
                buyCount = goblinRedisUtils.getSkuCountByUid(userId, skuId);
            }
            if (null != goodsSkuInfoVo.getBuyLimit() && 0 != goodsSkuInfoVo.getBuyLimit()) {
                nftGoodsSkuInfoVo.setCanBuyNum(goodsSkuInfoVo.getBuyLimit() - buyCount);
            }
            // 库存 盲盒计算所有sku库存总数
            int stock = 0;
            if (goodsSkuInfoVo.getUnbox().equals("0")) {
                if (null == goodsSkuInfoVo.getSoldoutStatus() || goodsSkuInfoVo.getSoldoutStatus().equals("0")) {
                    stock = goblinRedisUtils.getSkuStock(null, skuId);
                }
            } else {
                String spuId = goodsSkuInfoVo.getSpuId();
                List<String> skuArray = goblinRedisUtils.getGoodsInfoVo(spuId).getSkuIdList();
                for (String skuIdItem : skuArray) {
                    GoblinGoodsSkuInfoVo itemVo = goblinRedisUtils.getGoodsSkuInfoVo(skuIdItem);
                    stock += goblinRedisUtils.getSkuAllStatusStock(itemVo);
                }
            }
            log.info("skuId:{}, 库存数量:{}", skuId, stock);
            if (stock <= 0) {
                nftGoodsSkuInfoVo.setIsStock(0);
            } else {
                nftGoodsSkuInfoVo.setIsStock(1);
            }
            // spu信息
            GoblinGoodsInfoVo goodsInfoVo = goblinRedisUtils.getGoodsInfoVo(goodsSkuInfoVo.getSpuId());
            GoblinNftGoodsDetailSpuInfoVo nftGoodsDetailSpuInfoVo = GoblinNftGoodsDetailSpuInfoVo.getNew().copy(goodsInfoVo);
            nftGoodsSkuInfoVo.setGoblinNftGoodsDetailSpuInfoVo(nftGoodsDetailSpuInfoVo);
            nftGoodsSkuInfoVo.setSystime(LocalDateTime.now());
            return nftGoodsSkuInfoVo;
        } else {
            return null;
        }
    }

    @Override
    public Boolean exchange(String code) {
        try {
            // 验证
            // 使用
            // 下单
            return true;
        } catch (Exception e) {
            log.error("cityVote5Error", e);
            return false;
        }
    }

}
