package com.fzm.mall.server.front.goods.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fzm.mall.server.front.base.ResponseVO;
import com.fzm.mall.server.front.constant.MallResponseEnum;
import com.fzm.mall.server.front.enums.GoodsRedisEnum;
import com.fzm.mall.server.front.goods.model.*;
import com.fzm.mall.server.front.goods.model.vo.*;
import com.fzm.mall.server.front.goods.model.vo.Comment;
import com.fzm.mall.server.front.goods.service.*;
import com.fzm.mall.server.front.goods.service.impl.SkuServiceImpl;
import com.fzm.mall.server.front.user.model.Coupon;
import com.fzm.mall.server.front.user.model.Header;
import com.fzm.mall.server.front.user.service.ICouponService;
import com.fzm.mall.server.front.user.service.IFootService;
import com.fzm.mall.server.front.user.service.IRedisService;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.ApiOperation;

import jdk.nashorn.internal.ir.annotations.Ignore;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@RestController
@RequestMapping("/mall/goods")
public class GoodsController {

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private ISpuService iSpuService;

    @Autowired
    private IMarketingCouponService marketingCouponService;

    @Autowired
    private IMarketingPromotionService marketingPromotionService;

    @Autowired
    private ISkuService iSkuService;

    @Autowired
    private ISkuPropService iSkuPropService;

    @Autowired
    private IOprationKeywordService oprationKeywordService;

    @Autowired
    private IRedisService redisService;

    @Autowired
    private IDistributionTemplateItemService distributionTemplateItemService;

    @Autowired
    private IDistributionTemplateService distributionTemplateService;

    @Autowired
    private IGoodCommentService goodCommentService;

    @Autowired
    private ICouponService couponService;

    //平台-商户号
    public static final String PLATFORM_MERCHANT_ID = "e3ac4b4a4e65460dbd9f1ec6cbd7a900";

    @Autowired
    private INftService nftService;

    @Autowired
    private IFootService footService;

    @Autowired
    private ICountService countService;


    @ApiOperation(value = "热搜词")
    @PostMapping("/without/getHotSearchKey")
    public ResponseVO<List<String>> getHotSearchKey() {
        List<String> keys = oprationKeywordService.getKeyWord();
        return new ResponseVO<>(MallResponseEnum.SUCCESS, keys);
    }


    @ApiOperation(value = "获取搜索历史")
    @PostMapping("/getSearchKey")
    public ResponseVO<List<String>> getSearchKey(@ApiIgnore @RequestAttribute Header header) {
        String uid = header.getUid();
        if (StringUtil.isNullOrEmpty(uid)) {
            return new ResponseVO<>(MallResponseEnum.SUCCESS);
        } else {
            String key = redisService.getKey(header.getUid() + GoodsRedisEnum.GOODS_REDIS_SEARCK_FIX);
            System.out.println("getSearchKey" + key);
            if (key == null) {
                return new ResponseVO<>(MallResponseEnum.SUCCESS);
            }
            List<String> searchKeys = JSONArray.parseArray(key, String.class);
            return new ResponseVO<>(MallResponseEnum.SUCCESS, searchKeys);
        }
    }

    @ApiOperation(value = "搜索")
    @PostMapping("/without/search")
    public ResponseVO<SearchGoods> search(@ApiIgnore @RequestAttribute Header header, @RequestBody SearchVo searchVo) {
        System.out.println(searchVo.toString());
        List<GoodsVo> goodsVos = new ArrayList<>();
        String searchKey = searchVo.getSearchKey();
        System.out.println(header.toString());
        if (!StringUtil.isNullOrEmpty(header.getUid())) {
            System.out.println(1);
            String key = redisService.getKey(header.getUid() + GoodsRedisEnum.GOODS_REDIS_SEARCK_FIX);
            System.out.println(key);
            List<String> searchKeys = new ArrayList<>();
            if (!StringUtil.isNullOrEmpty(key)) {
                searchKeys = JSONArray.parseArray(key, String.class);
            }
            if (searchKeys == null || searchKeys.size() == 0) {
                searchKeys.add(searchKey);
            } else {
                boolean remove = searchKeys.remove(searchKey);
                System.out.println(remove);
                if (searchKeys.size() >= 10) {
                    searchKeys.remove(0);
                    searchKeys.add(searchKey);
                } else {
                    searchKeys.add(searchKey);
                }
            }
            redisService.setKey(header.getUid() + GoodsRedisEnum.GOODS_REDIS_SEARCK_FIX, JSON.toJSONString(searchKeys));
            System.out.println(redisService.getKey(header.getUid() + GoodsRedisEnum.GOODS_REDIS_SEARCK_FIX));
        }
        //Category category = categoryService.getByName(searchKey);
        if (StringUtil.isNullOrEmpty(searchVo.getSale())) {
            searchVo.setSale("desc");
        }
        if (StringUtil.isNullOrEmpty(searchVo.getPrice())) {
            searchVo.setPrice("desc");
        }
        Integer count = 0;
        if (StringUtil.isNullOrEmpty(searchVo.getCategoryId())) {
            goodsVos = iSpuService.getSearch(searchVo);
            count = iSpuService.getSearchCount(searchVo);
        } else {
            goodsVos = iSpuService.getByCategoryId(searchVo.getCategoryId(), searchVo);
            count = iSpuService.getByCategoryIdCount(searchVo.getCategoryId());
        }
        for (GoodsVo goodsVo : goodsVos) {
            String categoryId = "";
            List<String> categoryIds = iSpuService.getCategoryId(goodsVo.getGoodsId());
            List<UserCouponVo> userCouponVos = couponService.getCouponByGoodsId(header.getUid(), goodsVo.getGoodsId(), header.getType(), PLATFORM_MERCHANT_ID, goodsVo.getMerchantId());
            goodsVo.setMarketingCoupons(userCouponVos);
            PromotionVo promotionVo = marketingPromotionService.getByGoodsId(goodsVo.getGoodsId(), header.getType(), goodsVo.getMerchantId());
            goodsVo.setPromotionVo(promotionVo);
        }
        SearchGoods searchGoods = new SearchGoods();
        searchGoods.setList(goodsVos);
        searchGoods.setCount(count);
        return new ResponseVO<>(MallResponseEnum.SUCCESS, searchGoods);
    }

    @ApiOperation(value = "商品详情 参数：goodsId")
    @PostMapping("/without/getDetail")
    public ResponseVO<GoodsVo> getdetail(@ApiIgnore @RequestAttribute Header header, @RequestBody JSONObject data) {
        String uid = header.getUid();
        Integer type = header.getType();
        String goodsId = data.getString("goodsId");
        GoodsVo goodsVo = iSpuService.getByGoodId(goodsId);
        if (goodsVo == null) {
            return new ResponseVO<>(MallResponseEnum.GOOD_NOT_EXIST);
        }
        BigDecimal comment = goodCommentService.getScope(goodsVo.getMerchantId());
        goodsVo.setComment(comment == null ? BigDecimal.ZERO : comment.setScale(2, RoundingMode.HALF_UP));
        //生成浏览记录
        if (!StringUtil.isNullOrEmpty(uid)) {
            footService.addRecord(uid, goodsId);
        }
        goodsVo.setImgListJson(JSONArray.parseArray(goodsVo.getImgList(), String.class));
        //优惠券
        List<UserCouponVo> userCouponVos = couponService.getCouponByGoodsId(uid, goodsId, type, PLATFORM_MERCHANT_ID, goodsVo.getMerchantId());
        System.err.println(header.getUid());
        for (UserCouponVo u : userCouponVos) {
            if (StringUtil.isNullOrEmpty(header.getUid())) {

            } else {
                Boolean b = couponService.checkHave(header.getUid(), u.getCouponId());
                if (b) {
                    u.setUid(uid);
                }
            }
        }
        goodsVo.setMarketingCoupons(userCouponVos);
        //促销活动
        PromotionVo byGoodsId = marketingPromotionService.getByGoodsId(goodsId, type, goodsVo.getMerchantId());
        goodsVo.setPromotionVo(byGoodsId);
        List<SkuVo> skus = iSkuService.getByGoodsId(goodsId);
        System.out.println(skus.size());
        Long sum = 0L;
        Long sales = 0L;
        if (!CollectionUtils.isEmpty(skus)) {
            for (SkuVo skuVo : skus) {
                System.out.println(skuVo.getSkuId());
                List<SkuProp> skuProps = iSkuPropService.getBySkuId(skuVo.getSkuId());
                skuVo.setSkuProps(skuProps);
            }
            sum = skus.stream().mapToLong(SkuVo::getCirculation).sum();
            sales = skus.stream().mapToLong(SkuVo::getSales).sum();
        }
        goodsVo.setCirculation(sum);
        goodsVo.setSales(sales);
        goodsVo.setSkus(skus);
        return new ResponseVO<>(MallResponseEnum.SUCCESS, goodsVo);
    }

    @ApiOperation(value = "商品快递模板 参数：area;merchantId")
    @PostMapping("/without/getDistribution")
    public ResponseVO<TemplateVo> getDistribution(@RequestBody JSONObject data) {
        String areaName = data.getString("area");
        String merchantId = data.getString("merchantId");
        DistributionTemplate distributionTemplate = distributionTemplateService.getByMerchantId(merchantId);
        DistributionTemplateItem distributionTemplateItem = distributionTemplateItemService.getByAreaAndTemplateId(areaName, distributionTemplate.getTemplateId());
        TemplateVo templateVo = new TemplateVo();
        templateVo.setDistributionTemplateItem(distributionTemplateItem);
        templateVo.setDistributionTemplate(distributionTemplate);
        return new ResponseVO<>(MallResponseEnum.SUCCESS, templateVo);

    }

    /* @ApiOperation(value = "商品评论 参数：goodsId")
     @PostMapping("/without/getComment")
     public ResponseVO<Comment> getComment(@RequestBody JSONObject data,@RequestBody PageVo pageVo){
         String goodsId = data.getString("goodsId");
         List<CommentVo> commentVos = goodCommentService.getByGoodsId(goodsId,pageVo);
         Integer count = goodCommentService.getCount(goodsId);
         Comment comment = new Comment();
         comment.setList(commentVos);
         comment.setCount(count);
         return new ResponseVO<>(MallResponseEnum.SUCCESS,comment);
     }*/
    @ApiOperation(value = "商品skuId详情 参数：skuId")
    @PostMapping("/without/getSkuDetail")
    public ResponseVO<SkuVo> getSkuDetail(@RequestBody JSONObject data) {
        String skuId = data.getString("skuId");
        SkuVo skuVo = iSkuService.getBySkuId(skuId);
        if (skuVo == null) {
            return new ResponseVO<>(MallResponseEnum.PARAMETER_ERR);
        }

        List<SkuProp> skuProps = iSkuPropService.getBySkuId(skuId);
        skuVo.setSkuProps(skuProps);
        return new ResponseVO<>(MallResponseEnum.SUCCESS, skuVo);
    }

    @ApiOperation(value = "获取优惠券 参数：skuIds")
    @PostMapping("/getCoupon")
    public ResponseVO<List<CouponVo>> getCoupon(@ApiIgnore @RequestAttribute Header header, @RequestBody JSONObject data) {
        String uid = header.getUid();
        Integer type = header.getType();
        List<String> skuIds = data.getObject("skuIds", List.class);
        System.err.println(skuIds);
        if (skuIds.size() == 0) {
            return new ResponseVO<>(MallResponseEnum.SUCCESS);
        }
        Map<MarketingCoupon, List<String>> map = new HashMap<>();
        Set<String> merchantId = new HashSet<>();
        Set<String> categoryId = new HashSet<>();
        Map<String, List<String>> merchantSku = new HashMap<>();
        Map<String, List<String>> categorySku = new HashMap<>();
        String couponId = "";
        //CouponVo couponVos = couponService.getAll(couponId,type);
        for (String skuId : skuIds) {
            SkuVo skuVo = iSkuService.getBySkuId(skuId);
            merchantId.add(skuVo.getMerchantId());
            List<String> merchantSkuList = merchantSku.get(skuVo.getMerchantId());
            if (merchantSkuList == null) {
                merchantSkuList = new ArrayList<>();
            }
            merchantSkuList.add(skuId);
            merchantSku.put(skuVo.getMerchantId(), merchantSkuList);
            List<String> category = iSpuService.getCategoryId(skuVo.getGoodsId());
            for (String c : category) {
                categoryId.add(c);
                List<String> categorySkuList = categorySku.get(c);
                if (categorySkuList == null) {
                    categorySkuList = new ArrayList<>();
                }
                categorySkuList.add(skuId);
                categorySku.put(c, categorySkuList);
            }
        }
        List<CouponVo> couponVoList = new ArrayList<>();
        List<String> userCouponIds = couponService.getCouponIdByUid(uid, type);
        for (String userCouponId : userCouponIds) {
            System.err.println(userCouponId);
            CouponVo couponVos = couponService.getAll(userCouponId, type);
            if (couponVos.getRangeType() == 1) {
                if (couponVos.getMerchantId().equals(PLATFORM_MERCHANT_ID) || merchantId.contains(couponVos.getMerchantId())) {
                    couponVos.setSkuIds(skuIds);
                    couponVoList.add(couponVos);
                }
            } else if (couponVos.getRangeType() == 2) {
                List<MarketingCouponCategory> marketingCouponCategories = couponVos.getMarketingCouponCategories();
                Set<String> skuId = new HashSet<>();
                for (MarketingCouponCategory marketingCouponCategorie : marketingCouponCategories) {
                    if (categoryId.contains(marketingCouponCategorie.getCategoryId())) {
                        if (couponVos.getMerchantId().equals(PLATFORM_MERCHANT_ID) || merchantId.contains(couponVos.getMerchantId())) {
                            skuId.addAll(categorySku.get(marketingCouponCategorie.getCategoryId()));
                        }

                    }
                }
                List<String> a = new ArrayList<>();
                a.addAll(skuId);
                if (a.size() != 0) {
                    couponVos.setSkuIds(a);
                    couponVoList.add(couponVos);
                }
            } else if (couponVos.getRangeType() == 3) {
                List<String> temp = new ArrayList<>();
                List<MarketingCouponSku> marketingCouponSkus = couponVos.getMarketingCouponSkus();
                for (MarketingCouponSku skuid : marketingCouponSkus) {
                    if (skuIds.contains(skuid.getSkuId())) {
                        temp.add(skuid.getSkuId());
                    }
                }
                if (temp.size() != 0) {
                    couponVos.setSkuIds(temp);
                    couponVoList.add(couponVos);
                }

            }

        }

        return new ResponseVO<>(MallResponseEnum.SUCCESS, couponVoList);
    }


    @ApiOperation(value = "获取优惠券 参数：couponId")
    @PostMapping("/addCoupon")
    public ResponseVO<String> addCoupon(@ApiIgnore @RequestAttribute Header header, @RequestBody JSONObject data) {
        String couponId = data.getString("couponId");
        String uid = header.getUid();
        Integer type = header.getType();
        if (!redisService.setNx("addCoupon:" + uid + couponId)) {
            return new ResponseVO<>(MallResponseEnum.SUCCESS);
        }
        try {
            int i = couponService.addCoupon(uid, type, couponId);
        } catch (Exception e) {
            return new ResponseVO<>(MallResponseEnum.COUPON_ERR);
        } finally {
            redisService.del("addCoupon:" + uid + couponId);
        }
        return new ResponseVO<>(MallResponseEnum.SUCCESS);
    }


    public String stringArray2Strin(List<String> strings) {
        StringBuffer sb = new StringBuffer();
        for (String s : strings) {
            sb.append("'").append(s).append("'").append(",");
        }
        return sb.toString();
    }


    @ApiOperation(value = "Nft商品详情 参数：goodsId")
    @PostMapping("/without/getNftDetail")
    public ResponseVO<GoodsVo> getNftDetail(@ApiIgnore @RequestAttribute Header header, @RequestBody JSONObject data) {
        String goodsId = data.getString("goodsId");
        GoodsVo goodsVo = iSpuService.getByGoodId(goodsId);
        Nft nft = nftService.getByGoodsId(goodsId);
        goodsVo.setNft(nft);
        return new ResponseVO<GoodsVo>(MallResponseEnum.SUCCESS, goodsVo);
    }
}



