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


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fzm.mall.server.front.asset.model.vo.good.GoodSkuVO;
import com.fzm.mall.server.front.base.ResponseVO;
import com.fzm.mall.server.front.constant.MallResponseEnum;
import com.fzm.mall.server.front.goods.model.Category;
import com.fzm.mall.server.front.goods.model.GoodSku;
import com.fzm.mall.server.front.goods.model.GoodSpu;
import com.fzm.mall.server.front.goods.model.vo.PromotionVo;
import com.fzm.mall.server.front.goods.model.vo.SkuVo;
import com.fzm.mall.server.front.goods.service.*;
import com.fzm.mall.server.front.order.model.vo.DeliveryVO;
import com.fzm.mall.server.front.order.model.vo.PayVo;
import com.fzm.mall.server.front.user.model.Header;
import com.fzm.mall.server.front.util.OrderUtil;
import com.fzm.mall.server.front.util.Sha256Util;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jdk.nashorn.internal.ir.annotations.Ignore;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

import static com.fzm.mall.server.front.goods.controller.GoodsController.PLATFORM_MERCHANT_ID;

/**
 * <p>
 * 商品促销 前端控制器
 * </p>
 *
 * @author tdz
 * @since 2021-05-27
 */
@Api(tags = "促销活动接口", description = "促销活动等")
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RequestMapping("/mall/marketingPromotion")
public class MarketingPromotionController {
    private final IMarketingPromotionService marketingPromotionService;
    private final ISpuService spuService;
    private final IGoodSkuService goodSkuService;
    private final ICategoryService categoryService;
    private final IGoodSpuService goodSpuService;

    @ApiOperation(value = "根据skuId查促销活动")
    @PostMapping("/getProBySkuId")
    public ResponseVO<List<PromotionVo>> getProBySkuId(@Ignore @RequestAttribute Header header, @RequestBody JSONObject obj) {
        JSONArray skuArr = obj.getJSONArray("skuIds");
        String s = skuArr.toJSONString();
        List<String> skuIds = JSON.parseObject(s, List.class);
        //第一步查平台的活动
        List<PromotionVo> proList = new ArrayList<>();
        // 查商家的活动
        Iterator<String> iterator = skuIds.iterator();
        while (iterator.hasNext()) {
            String skuIdmer = iterator.next();
            SkuVo skuVo = goodSkuService.getSkuVoBySkuId(skuIdmer);
            if (skuVo != null) {
                //String goodsId = skuVo.getGoodsId();
                String merchantId = skuVo.getMerchantId();
                PromotionVo merchantProV = marketingPromotionService.getByMerchantId(merchantId);
                if (merchantProV != null) {
                    merchantProV.setSkuId(skuIdmer);
                    iterator.remove();
                    proList.add(merchantProV);
                }
            }
            if (CollectionUtils.isEmpty(skuIds)) {
                break;
            }
        }

        //如果平台查不到活动查类目
        //根据skuId查类目，再查promotion
        Iterator<String> skuIdList = skuIds.iterator();
        while (skuIdList.hasNext()) {
            String skuId = skuIdList.next();
            GoodSku sku = goodSkuService.getBySkuId(skuId);
            if (sku != null) {
                String goodsId = sku.getGoodsId();
                List<String> categoryIds = spuService.getCategoryId(goodsId);
                List<Category> categorys = categoryService.getCategorys(categoryIds);
                if (categorys != null) {
                    List<Category> categorySort = categorys.stream().sorted(Comparator.comparing(Category::getLevel)).collect(Collectors.toList());
                    Map<Integer, String> categoryMap = categorySort.stream().collect(Collectors.toMap(Category::getLevel, Category::getCategoryId));
                    Iterator<Map.Entry<Integer, String>> it = categoryMap.entrySet().iterator();
                    while (it.hasNext()) {
                        //一个goodsId查询下面不同等级category的活动
                        Map.Entry<Integer, String> entry = it.next();
                        String categoryId = entry.getValue();
                        PromotionVo promotion = marketingPromotionService.getByCategoryId(categoryId);
                        if (promotion != null) {
                            promotion.setSkuId(skuId);
                            proList.add(promotion);
                            skuIdList.remove();
                            break;
                        } else {
                            continue;
                        }
                    }
                }
            }
            if (CollectionUtils.isEmpty(skuIds)) {
                break;
            }
        }

        if (!CollectionUtils.isEmpty(skuIds)) {
            //根据skuId查活动
            for (String skuId : skuIds) {
                PromotionVo promotion = marketingPromotionService.getBySkuId(skuId);
                if (promotion != null) {
                    promotion.setSkuId(skuId);
                    proList.add(promotion);
                }
            }
        }

        //设置skuIds去重
        if (CollectionUtils.isEmpty(proList)) {
            return new ResponseVO(MallResponseEnum.SUCCESS, proList);
        }
        final Map<String, List<String>> skuMap = proList.stream().collect(Collectors.groupingBy(PromotionVo::getPromotionId, Collectors.mapping(PromotionVo::getSkuId, Collectors.toList())));
        TreeSet<PromotionVo> distinctList = proList.stream().collect(Collectors.toCollection(
                () -> new TreeSet<>(
                        Comparator.comparing(tc -> tc.getPromotionId())
                )
        ));
        for (PromotionVo pro : distinctList) {
            String promotionId = pro.getPromotionId();
            Iterator<Map.Entry<String, List<String>>> it = skuMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, List<String>> entry = it.next();
                if (promotionId.equals(entry.getKey())) {
                    pro.setSkuIds(entry.getValue());
                }
            }
        }
        return new ResponseVO(MallResponseEnum.SUCCESS, distinctList);
    }


}

