package com.hzs.sale.index.controller.api;

import cn.hutool.core.collection.CollectionUtil;
import com.hzs.common.core.enums.EOrderType;
import com.hzs.common.core.enums.ERangeType;
import com.hzs.common.core.enums.ESpecialArea;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.common.domain.sale.ext.BdWaresExt;
import com.hzs.common.domain.sale.ext.BdWaresSpecsSkuExt;
import com.hzs.common.domain.sale.wares.BdWares;
import com.hzs.common.domain.sale.wares.BdWaresAuthority;
import com.hzs.common.domain.sale.wares.BdWaresRange;
import com.hzs.common.domain.sale.wares.ext.WaresGradeAwards;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.member.base.dto.ShowWaresDTO;
import com.hzs.sale.index.controller.param.IndexWaresParam;
import com.hzs.sale.wares.service.IBdWaresGradeService;
import com.hzs.sale.wares.service.IBdWaresRangeService;
import com.hzs.sale.wares.service.IBdWaresService;
import com.hzs.sale.wares.service.IBdWaresSpecsSkuService;
import com.hzs.sale.wares.vo.WaresVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * 会员首页
 */
@Slf4j
@RequestMapping("/api/order")
@RestController
public class ApiIndexController extends BaseController {

    @Autowired
    private IBdWaresService iBdWaresService;
    @Autowired
    private IBdWaresRangeService iBdWaresRangeService;
    @Autowired
    private IBdWaresGradeService iBdWaresGradeService;
    @Autowired
    private IBdWaresSpecsSkuService iBdWaresSpecsSkuService;

    @DubboReference
    IMemberServiceApi iMemberServiceApi;

    /**
     * 首页商品列表
     *
     * @param param
     * @return
     */
    @GetMapping("/index-wares-list")
    public TableDataInfo indexWaresList(IndexWaresParam param) {
        Long pkMember = SecurityUtils.getUserId();
        // 返回数据列表
        List<WaresVo> waresVOList = new ArrayList<>();

        if (CollectionUtil.isEmpty(param.getSpecialAreaList())) {
            // 如果没有传入专区，则使用默认商品专区
            param.setSpecialAreaList(Arrays.asList(ESpecialArea.REPURCHASE_AREA.getValue(), ESpecialArea.SPECIAL_REPURCHASE_AREA.getValue(), ESpecialArea.RESCISSION_AREA.getValue()));
        }

        // 商品列表
        List<BdWaresExt> waresList = iBdWaresService.listWares(param);
        if (CollectionUtil.isNotEmpty(waresList)) {
            // 获取商品ID列表
            List<Integer> waresIdList = waresList.stream().map(BdWares::getPkId).collect(Collectors.toList());
            // 登录用户
            CuMemberExt loginMember = iMemberServiceApi.getMemberById(pkMember).getData();

            // 商品等级、奖衔、权限控制处理
            Set<Integer> authWaresIdSet = new HashSet<>();
            List<String> authWaresList = new ArrayList<>();
            if (waresIdList.size() > 0) {
                List<WaresGradeAwards> waresGradeAwardsList = iBdWaresGradeService.queryWaresGradeAwards(waresIdList);
                waresGradeAwardsList.forEach(waresGradeAwards -> {
                    authWaresIdSet.add(waresGradeAwards.getPkWares());
                    String key = waresGradeAwards.getPkWares() + "_" + waresGradeAwards.getRangeType() + "_" + waresGradeAwards.getPkRange().toString();
                    authWaresList.add(key);
                });
            }

            // 商品是否显示（用于团队显示控制使用）
            Map<Integer, Boolean> waresShowMap = new HashMap<>();
            Map<Integer, List<BdWaresAuthority>> waresAuthorityMap = iBdWaresService.getWaresAuthority(waresIdList);
            if (waresAuthorityMap.size() > 0) {
                List<ShowWaresDTO> showWaresList = waresList.stream().map(item -> {
                    ShowWaresDTO showWaresDTO = new ShowWaresDTO();
                    showWaresDTO.setPkWares(item.getPkId());
                    showWaresDTO.setLoginMember(pkMember);
                    showWaresDTO.setWaresAuthorityList(waresAuthorityMap.get(item.getPkId()));
                    return showWaresDTO;
                }).collect(Collectors.toList());
                // 商品显示权限map（key:商品ID，value:是否可见）
                waresShowMap = iMemberServiceApi.checkIsShowWares(showWaresList).getData();
            }

            // 查询商品sku 最小值 和数量
            Map<Integer, List<BdWaresSpecsSkuExt>> waresSpecsSkuMap = new HashMap<>();
            if (waresIdList.size() > 0) {
                List<BdWaresSpecsSkuExt> waresSpecsSkuArray = iBdWaresSpecsSkuService.selectByMinWaresSpecsSkuByPkWaresList(waresIdList);
                waresSpecsSkuMap = waresSpecsSkuArray.stream().collect(Collectors.groupingBy(BdWaresSpecsSkuExt::getPkWares));
            }
            // 复购类商品级差价格
            List<BdWaresRange> bdWaresRangeList = iBdWaresRangeService.queryWaresRangeByCondition(loginMember, waresIdList);

            for (BdWaresExt bdWares : waresList) {
                if (authWaresIdSet.contains(bdWares.getPkId())) {
                    String gradeKey = bdWares.getPkId() + "_" + ERangeType.GRADE.getValue() + "_" + loginMember.getPkSettleGrade();
                    String awardsKey = bdWares.getPkId() + "_" + ERangeType.AWARDS.getValue() + "_" + loginMember.getPkAwards();
                    String authorityKey = bdWares.getPkId() + "_" + ERangeType.AUTHORITY.getValue() + "_" + loginMember.getRegisterAuthority();
                    if (!authWaresList.contains(gradeKey) && !authWaresList.contains(awardsKey) && !authWaresList.contains(authorityKey)) {
                        continue;
                    }
                }

                Boolean isShow = waresShowMap.get(bdWares.getPkId());
                if (null == isShow || isShow) {
                    List<BdWaresSpecsSkuExt> waresSpecsSku = waresSpecsSkuMap.get(bdWares.getPkId());
                    waresSpecsSku = waresSpecsSku.stream().peek(a -> a.setProductGift(a.getPkProduct() + "" + a.getIsGift())).collect(Collectors.toList());
                    Map<String, List<BdWaresSpecsSkuExt>> col = waresSpecsSku.stream().collect(Collectors.groupingBy(BdWaresSpecsSkuExt::getProductGift));
                    BigDecimal waresPrice = BigDecimal.ZERO;
                    BigDecimal waresAchieve = BigDecimal.ZERO;
                    BigDecimal assAchieve = BigDecimal.ZERO;
                    // 会员价
                    BigDecimal vipAchieve = BigDecimal.ZERO;
                    // 零售价
                    BigDecimal retailPrice = BigDecimal.ZERO;
                    for (Map.Entry<String, List<BdWaresSpecsSkuExt>> integerListEntry : col.entrySet()) {
                        // 取得每一个商品价格最小值
                        Optional<BdWaresSpecsSkuExt> minBdWaresSpecsSkuExt = integerListEntry.getValue().stream().filter(Objects::nonNull).min(Comparator.comparing(BdWaresSpecsSkuExt::getPrice));
                        BdWaresSpecsSkuExt bdWaresSpecsSkuExt = minBdWaresSpecsSkuExt.get();
                        waresPrice = waresPrice.add(bdWaresSpecsSkuExt.getPrice().multiply(new BigDecimal(bdWaresSpecsSkuExt.getQuantity())));
                        waresAchieve = waresAchieve.add(bdWaresSpecsSkuExt.getAchieve().multiply(new BigDecimal(bdWaresSpecsSkuExt.getQuantity())));
                        assAchieve = assAchieve.add(bdWaresSpecsSkuExt.getAssAchieve().multiply(new BigDecimal(bdWaresSpecsSkuExt.getQuantity())));
                        // 会员价
                        vipAchieve = vipAchieve.add(bdWaresSpecsSkuExt.getVipPrice().multiply(BigDecimal.valueOf(bdWaresSpecsSkuExt.getQuantity())));
                        // 零售价
                        retailPrice = retailPrice.add(bdWaresSpecsSkuExt.getRetailPrice().multiply(BigDecimal.valueOf(bdWaresSpecsSkuExt.getQuantity())));
                    }

                    // 商品信息填充
                    WaresVo waresVo = new WaresVo();
                    waresVo.setCover(bdWares.getCover());
                    waresVo.setWaresName(bdWares.getWaresName());
                    BigDecimal price = waresPrice;
                    if (EOrderType.REPURCHASE_ORDER.getValue() == bdWares.getSpecialArea()) {
                        for (BdWaresRange bdWaresRange : bdWaresRangeList) {
                            if (bdWares.getPkId().intValue() == bdWaresRange.getPkWares().intValue()) {
                                price = price.add(bdWaresRange.getPrice());
                            }
                        }
                    }
                    waresVo.setWaresPrice(price);
                    waresVo.setVipPrice(vipAchieve);
                    waresVo.setRetailPrice(retailPrice);
                    waresVo.setWaresAchieve(waresAchieve);
                    waresVo.setPkWares(bdWares.getPkId());
                    waresVo.setWaresCode(bdWares.getWaresCode());
                    waresVo.setSpecialArea(bdWares.getSpecialArea());
                    waresVo.setIsSale(bdWares.getIsSale());
                    waresVo.setPreSaleStatus(bdWares.getPreSaleStatus());
                    waresVo.setSales(bdWares.getSales());
                    waresVOList.add(waresVo);
                }
            }
        }
        TableDataInfo tableDataInfo = getDataTable(waresList);
        tableDataInfo.setRows(waresVOList);
        return tableDataInfo;
    }


}
