package com.hzs.sale.wares.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.activity.base.service.IActivityService;
import com.hzs.common.core.enums.EShippingChannel;
import com.hzs.common.core.utils.ComputeUtil;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.sale.ext.BdWaresDetailExt;
import com.hzs.common.domain.sale.wares.BdWaresDetail;
import com.hzs.common.domain.scm.ic.IcAvailableNum;
import com.hzs.common.domain.scm.pub.ScmItemSpecs;
import com.hzs.common.domain.system.base.ext.BdProductStorehouseExt;
import com.hzs.sale.order.param.OrderItemsParam;
import com.hzs.sale.order.param.WaresItemsParam;
import com.hzs.sale.product.vo.WaresDetailVo;
import com.hzs.sale.wares.mapper.BdWaresDetailMapper;
import com.hzs.sale.wares.param.CuProductParams;
import com.hzs.sale.wares.service.IBdWaresDetailService;
import com.hzs.sale.wares.vo.WaresProductDetailVo;
import com.hzs.system.base.IAreaServiceApi;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品发布明细表 服务实现类
 */
@Service
public class BdWaresDetailServiceImpl extends ServiceImpl<BdWaresDetailMapper, BdWaresDetail> implements IBdWaresDetailService {

    @DubboReference
    IAreaServiceApi iAreaServiceApi;

    @Autowired
    private IActivityService iActivityService;

    /**
     * 根据条件查询商品信息
     *
     * @param specialArea 专区
     * @param transType   运输方式
     */
    @Override
    public List<BdWaresDetailExt> queryWaresDetailByCondition(Integer specialArea, Integer transType, List<OrderItemsParam> orderItemsParams, Integer systemType) {
        List<BdWaresDetailExt> bdWaresDetailExtList = new ArrayList<>();
        for (OrderItemsParam orderItemsParam : orderItemsParams) {
            for (WaresItemsParam waresItemsParam : orderItemsParam.getWaresItemsParamList()) {
                BdWaresDetailExt bdWaresDetailExt = BdWaresDetailExt.builder()
                        .waresCode(orderItemsParam.getWaresCode())
                        .pkWaresSpecsSku(waresItemsParam.getPkWaresSpecsSku())
                        .waresQuantity(orderItemsParam.getQuantity())
                        .pkMakerSpace(orderItemsParam.getPkMakerSpace())
                        .price(BigDecimal.ZERO)
                        .achieve(BigDecimal.ZERO)
                        .build();
                bdWaresDetailExt.setQuantity(waresItemsParam.getQuantity());
                bdWaresDetailExtList.add(bdWaresDetailExt);
            }
        }
        List<BdWaresDetailExt> waresDetailExtList = baseMapper.queryWaresDetailByCondition(specialArea, transType, orderItemsParams, systemType);
        if (CollectionUtil.isNotEmpty(waresDetailExtList)) {
            Map<String, BdWaresDetailExt> bdWaresDetailExtMap = new HashMap<>();
            waresDetailExtList.forEach(waresDetailExt -> {
                bdWaresDetailExtMap.put(waresDetailExt.getWaresCode() + waresDetailExt.getPkWaresSpecsSku(), waresDetailExt);
            });
            bdWaresDetailExtList.forEach(waresDetailExt -> {
                String key = waresDetailExt.getWaresCode() + waresDetailExt.getPkWaresSpecsSku();
                if (bdWaresDetailExtMap.containsKey(key)) {
                    BeanUtil.copyProperties(bdWaresDetailExtMap.get(key), waresDetailExt, "waresQuantity", "quantity", "pkMakerSpace");
                }
            });
        } else {
            bdWaresDetailExtList.clear();
        }
        return bdWaresDetailExtList;
    }

    @Override
    public List<IcAvailableNum> queryWaresDetailSpecsByCondition(Integer specialArea, Integer pkCountry, Integer pkCorp, Integer pkStorehouse, Integer province,
                                                                 String parentCode, CuMember cuMember, List<OrderItemsParam> orderItemsParams) {
        List<BdWaresDetailExt> bdWaresDetailExtList = new ArrayList<>();
        for (OrderItemsParam orderItemsParam : orderItemsParams) {
            for (WaresItemsParam waresItemsParam : orderItemsParam.getWaresItemsParamList()) {
                BdWaresDetailExt bdWaresDetailExt = BdWaresDetailExt.builder()
                        .waresCode(orderItemsParam.getWaresCode())
                        .pkWaresSpecsSku(waresItemsParam.getPkWaresSpecsSku())
                        .waresQuantity(orderItemsParam.getQuantity())
                        .build();
                bdWaresDetailExt.setQuantity(waresItemsParam.getQuantity());
                bdWaresDetailExtList.add(bdWaresDetailExt);
            }
        }
        List<BdWaresDetailExt> waresDetailExtList = baseMapper.queryWaresDetailSpecsByCondition(specialArea, orderItemsParams);
        if (CollectionUtil.isNotEmpty(waresDetailExtList)) {
            Map<String, BdWaresDetailExt> bdWaresDetailExtMap = new HashMap<>();
            waresDetailExtList.forEach(waresDetailExt -> {
                bdWaresDetailExtMap.put(waresDetailExt.getWaresCode() + waresDetailExt.getPkWaresSpecsSku(), waresDetailExt);
            });
            bdWaresDetailExtList.forEach(waresDetailExt -> {
                String key = waresDetailExt.getWaresCode() + waresDetailExt.getPkWaresSpecsSku();
                if (bdWaresDetailExtMap.containsKey(key)) {
                    BeanUtil.copyProperties(bdWaresDetailExtMap.get(key), waresDetailExt, "waresQuantity", "quantity");
                }
                waresDetailExt.setQuantity(waresDetailExt.getWaresQuantity() * waresDetailExt.getQuantity());
            });
        }

        // 活动赠品 赠送封装
        List<BdWaresDetailExt> newWaresDetailExtList = iActivityService.generateActivityGiftWaresAchieve(specialArea, pkCountry, bdWaresDetailExtList,
                parentCode, cuMember);
        if (newWaresDetailExtList.size() > 0) {
            bdWaresDetailExtList.addAll(newWaresDetailExtList);
        }

        Map<String, IcAvailableNum> availableNumHashMap = new HashMap<>();
        // key为产品id
        List<Integer> productIdList = new ArrayList<>();
        for (BdWaresDetailExt bdWaresDetailExt : bdWaresDetailExtList) {
            // 三方品目前不控制库存
            if (EShippingChannel.A_PIECE.getValue().equals(bdWaresDetailExt.getShippingChannel())) {
                continue;
            }
            if (null != bdWaresDetailExt.getPkProduct()) {
                // 存在产品信息，才进行后续处理
                String key = bdWaresDetailExt.getWaresCode() + "_" + bdWaresDetailExt.getPkWaresSpecsSku() + "_" + bdWaresDetailExt.getPkProduct();
                if (availableNumHashMap.containsKey(key)) {
                    IcAvailableNum availableNum = availableNumHashMap.get(key);
                    availableNum.setAvailableNum(ComputeUtil.computeAdd(availableNum.getAvailableNum(), BigDecimal.valueOf(bdWaresDetailExt.getQuantity())));
                } else {
                    IcAvailableNum availableNum = IcAvailableNum.builder()
                            .availableNum(BigDecimal.valueOf(bdWaresDetailExt.getQuantity()))
                            .pkProduct(bdWaresDetailExt.getPkProduct())
                            .pkCorp(pkCorp)
                            .pkProductBas(bdWaresDetailExt.getPkProductBas())
                            .pkUnit(bdWaresDetailExt.getPkUnit())
                            .pkStorehouse(pkStorehouse)
                            .preSaleStatus(bdWaresDetailExt.getPreSaleStatus())
                            .build();
                    productIdList.add(bdWaresDetailExt.getPkProduct());
                    List<ScmItemSpecs> scmItemSpecs = BeanUtil.copyToList(bdWaresDetailExt.getWaresSpecsList(), ScmItemSpecs.class);
                    availableNum.setScmItemSpecsList(scmItemSpecs);
                    availableNumHashMap.put(key, availableNum);
                }
            }
        }
        if (productIdList.size() > 0 && province != null) {
            // 根据产品，省查看是否由仓库，有仓库的话修改仓库
            List<BdProductStorehouseExt> bdProductStorehouseList = iAreaServiceApi.queryBdProductStorehouseByCondition(productIdList, province).getData();
            Map<Integer, BdProductStorehouseExt> bdProductStorehouseMap = new HashMap<>();
            if (CollectionUtil.isNotEmpty(bdProductStorehouseList)) {
                bdProductStorehouseList.forEach(bdProductStorehouse -> bdProductStorehouseMap.put(bdProductStorehouse.getPkProduct(), bdProductStorehouse));
                for (String key : availableNumHashMap.keySet()) {
                    IcAvailableNum icAvailableNum = availableNumHashMap.get(key);
                    if (bdProductStorehouseMap.containsKey(icAvailableNum.getPkProduct())) {
                        BdProductStorehouseExt bdProductStorehouseExt = bdProductStorehouseMap.get(icAvailableNum.getPkProduct());
                        icAvailableNum.setPkCorp(bdProductStorehouseExt.getPkCorp());
                        icAvailableNum.setPkStorehouse(bdProductStorehouseExt.getPkStorehouse().intValue());
                    }
                }
            }
        }
        return new ArrayList<>(availableNumHashMap.values());
    }

    /**
     * 查询商品编号
     *
     * @param waresCode
     * @return
     */
    @Override
    public List<CuProductParams> selectByWaresCode(String waresCode, Integer specialArea, Integer isGift) {
        return baseMapper.selectByWaresCode(waresCode, specialArea, isGift);
    }

    /**
     * 根据商品主键查询
     *
     * @param pkWares
     * @return
     */
    @Override
    public List<BdWaresDetailExt> selectByPkWares(Integer pkWares) {
        return baseMapper.selectByPkWares(pkWares);
    }

    /**
     * 根据产品主键查询商品列表
     *
     * @param pkProduct
     * @return
     */
    @Override
    public List<WaresDetailVo> listByPkProduct(List<Integer> pkProduct) {
        return baseMapper.listByPkProduct(pkProduct);
    }


    /**
     * 商品下产品查询
     *
     * @param pkWares
     * @return
     */
    @Override
    public List<WaresProductDetailVo> selectByList(Integer pkWares) {
        return baseMapper.selectByList(pkWares);
    }


}
