package com.hzs.scm.store.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.common.core.domain.R;
import com.hzs.common.core.enums.ELevelValue;
import com.hzs.common.core.enums.EOrderStatus;
import com.hzs.common.core.enums.EScmOrderType;
import com.hzs.common.core.enums.EStoreStatus;
import com.hzs.common.core.utils.ComputeUtil;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import com.hzs.common.domain.sale.ext.SaOrderItemsExt;
import com.hzs.common.domain.scm.store.IcStoreOutB;
import com.hzs.common.domain.scm.store.IcStoreOutH;
import com.hzs.common.domain.scm.store.ext.IcStoreOutBExt;
import com.hzs.common.domain.scm.store.ext.IcStoreOutHExt;
import com.hzs.member.store.ICuStoreServiceApi;
import com.hzs.member.store.dto.StoreDto;
import com.hzs.sale.order.ISaOrderServiceApi;
import com.hzs.scm.ic.service.IIcOnHandNumService;
import com.hzs.scm.no.service.IScmBillNoService;
import com.hzs.scm.store.mapper.IcStoreOutHMapper;
import com.hzs.scm.store.param.OrderQueryParam;
import com.hzs.scm.store.service.IIcStoreHandNumService;
import com.hzs.scm.store.service.IIcStoreOutBService;
import com.hzs.scm.store.service.IIcStoreOutHService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * <p>
 * 店铺出库单表头 服务实现类
 * </p>
 *
 * @author hzs
 * @since 2024-05-11
 */
@Service
public class IcStoreOutHServiceImpl extends ServiceImpl<IcStoreOutHMapper, IcStoreOutH> implements IIcStoreOutHService {

    @DubboReference
    private ICuStoreServiceApi cuStoreServiceApi;

    @DubboReference
    private ISaOrderServiceApi saOrderServiceApi;

    @Autowired
    private IScmBillNoService scmBillNoService;

    @Autowired
    private IIcStoreOutBService storeOutBiService;

    @Autowired
    private IIcOnHandNumService onHandNumService;

    @Autowired
    private IIcStoreHandNumService storeHandNumService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendDeliverByCorp(List<Long> orderItemIdList, Integer pkStorehouse, Long pkMember) {
        // 查询订单
        List<SaOrderExt> saOrderExtList = saOrderServiceApi.queryStoreSaOrderByParam(orderItemIdList).getData();
        // 查询所有店铺
        List<StoreDto> storeDtoList = cuStoreServiceApi.queryAllMemberStore().getData();
        List<SaOrderExt> updateSaOrderList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(storeDtoList)) {
            // 区域店铺
            Map<String, StoreDto> areaStoreMap = new HashMap<>();
            // 国家代理
            Map<Integer, StoreDto> cuntryStoreMap = new HashMap<>();
            for (StoreDto storeDto : storeDtoList) {
                if (ELevelValue.GOLD_DRILL.getValue() == storeDto.getLevelValue()) {
                    cuntryStoreMap.put(storeDto.getBindingCountry(), storeDto);
                } else if (ELevelValue.SILVER_DRILL.getValue() == storeDto.getLevelValue()) {
                    String key = storeDto.getPkCountry() + "_" + storeDto.getBindingProvince();
                    areaStoreMap.put(key, storeDto);
                }
            }
            List<IcStoreOutB> storeOutBiList = new ArrayList<>();
            for (SaOrderExt saOrderExt : saOrderExtList) {
                saOrderExt.setPkStorehouse(pkStorehouse);
                // 验证店铺等级,服务中心店铺的需要验证是否存在省代或者国代,存在省代国代的需要公司发给上一级
                IcStoreOutH icStoreOutH = IcStoreOutH.builder()
                        .pkCorp(saOrderExt.getPkCorp())
                        .orderCode(scmBillNoService.createScmBillNoByOrderType(EScmOrderType.STORE_ORDER.getValue()))
                        .remark("公司发货,发货到店铺;")
                        .build();
                icStoreOutH.setPkCreator(pkMember);
                icStoreOutH.setPkCountry(saOrderExt.getPkCountry());
                if (ELevelValue.COPPER_DRILL.getValue() == saOrderExt.getLevelValue()) {
                    // 先查看是否有省代
                    String provinceKey = saOrderExt.getPkCountry() + "_" + saOrderExt.getStoreProvince();
                    if (areaStoreMap.containsKey(provinceKey)) {
                        icStoreOutH.setPkAcceptStore(areaStoreMap.get(provinceKey).getPkId());
                    } else if (cuntryStoreMap.containsKey(saOrderExt.getPkCountry())) {
                        icStoreOutH.setPkAcceptStore(cuntryStoreMap.get(saOrderExt.getPkCountry()).getPkId());
                    } else {
                        icStoreOutH.setPkAcceptStore(saOrderExt.getPkMemberStore());
                    }
                } else {
                    // 直接发货给代理商店铺
                    icStoreOutH.setPkAcceptStore(saOrderExt.getPkMemberStore());
                }
                // 扣减库存，库存扣减成功后，保存发货单，更新订单
                if (onHandNumService.mergeIcOnHandNumByStoreOut(saOrderExt, EScmOrderType.SALE_ORDER.getValue(), pkMember)) {
                    // 保存店铺发货单
                    BigDecimal totalNum = BigDecimal.ZERO;
                    for (SaOrderItemsExt saOrderItemsExt : saOrderExt.getOrderItemsExtList()) {
                        totalNum = ComputeUtil.computeAdd(totalNum, BigDecimal.valueOf(saOrderItemsExt.getQuantity()));

                    }
                    icStoreOutH.setTotalNum(totalNum);
                    save(icStoreOutH);
                    for (SaOrderItemsExt saOrderItemsExt : saOrderExt.getOrderItemsExtList()) {
                        IcStoreOutB icStoreOutB = BeanUtil.copyProperties(saOrderItemsExt, IcStoreOutB.class);
                        icStoreOutB.setOrderStatus(EStoreStatus.CORP_SEND.getValue());
                        icStoreOutB.setPkStoreoutH(icStoreOutH.getPkId());
                        icStoreOutB.setPkOrder(saOrderExt.getPkId());
                        icStoreOutB.setPkOrderItems(saOrderItemsExt.getPkId());
                        icStoreOutB.setPkCreator(pkMember);
                        icStoreOutB.setPkCountry(saOrderExt.getPkCountry());
                        storeOutBiList.add(icStoreOutB);
                    }
                    updateSaOrderList.add(saOrderExt);
                }
            }
            if (storeOutBiList.size() > 0) {
                storeOutBiService.saveBatch(storeOutBiList);
            }
            // 回写订单明细,订单明细变为已发货
            R<Boolean> flag = saOrderServiceApi.sendDeliverBySaOrder(updateSaOrderList, pkMember);
            if (!flag.isSuccess() || !flag.getData()) {
                throw new RuntimeException("更新订单状态失败");
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void receiveDeliverByItemsIs(OrderQueryParam orderQueryParam, Long pkMember) {
        // 查询待入库的店铺发货单
        List<IcStoreOutHExt> storeOutList = baseMapper.queryStoreOutByCondition(orderQueryParam);
        if (CollectionUtil.isNotEmpty(storeOutList)) {
            storeHandNumService.mergeIcStoreHandNumByStoreOut(storeOutList, EScmOrderType.SO_ORDER.getValue(), pkMember);
            // 回写发货单状态，发货单变更为已发货
            storeOutBiService.updateStoreOutItemStatus(storeOutList, EStoreStatus.STORE_RECEIVE.getValue(), pkMember);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sendDeliverByStore(OrderQueryParam orderQueryParam, Long pkMember) {
        // 查询待入库的店铺发货单
        List<IcStoreOutHExt> storeOutList = baseMapper.queryStoreOutByCondition(orderQueryParam);
        // 发货操作
        List<IcStoreOutB> storeOutBiList = new ArrayList<>();
        List<IcStoreOutHExt> saveStoreOutExtList = new ArrayList<>();
        for (IcStoreOutHExt storeOutExt : storeOutList) {
            // 扣减库存, 扣减库存成功继续处理 发货单 有接受店铺的生成店铺发货单，
            // 最后更新店铺发货单状态，更新为已发货
            if (storeHandNumService.deductIcStoreHandNumByStoreOut(storeOutExt, EScmOrderType.STORE_ORDER.getValue(), pkMember)) {
                // 没有下级店铺发送到会员，直接扣减库存，更新订单状态就可以
                if (storeOutExt.getPkAcceptStore() != null) {
                    // 验证店铺等级,服务中心店铺的需要验证是否存在省代或者国代,存在省代国代的需要公司发给上一级
                    IcStoreOutH icStoreOutH = IcStoreOutH.builder()
                            .pkAcceptStore(storeOutExt.getPkAcceptStore())
                            .pkSendStore(storeOutExt.getPkSendStore())
                            .orderCode(scmBillNoService.createScmBillNoByOrderType(EScmOrderType.STORE_ORDER.getValue()))
                            .remark("店铺发货,发货到店铺;")
                            .build();
                    icStoreOutH.setPkCreator(pkMember);
                    icStoreOutH.setPkCountry(storeOutExt.getPkCountry());
                    // 保存店铺发货单
                    BigDecimal totalNum = BigDecimal.ZERO;
                    for (IcStoreOutBExt storeOutBiExt : storeOutExt.getStoreOutBiExtList()) {
                        totalNum = ComputeUtil.computeAdd(totalNum, BigDecimal.valueOf(storeOutBiExt.getQuantity()));

                    }
                    icStoreOutH.setTotalNum(totalNum);
                    save(icStoreOutH);
                    for (IcStoreOutBExt storeOutBiExt : storeOutExt.getStoreOutBiExtList()) {
                        IcStoreOutB icStoreOutB = BeanUtil.copyProperties(storeOutBiExt, IcStoreOutB.class);
                        icStoreOutB.setOrderStatus(EStoreStatus.CORP_SEND.getValue());
                        icStoreOutB.setPkStoreoutH(icStoreOutH.getPkId());
                        icStoreOutB.setPkSource(storeOutBiExt.getPkStoreoutH());
                        icStoreOutB.setPkSourceB(storeOutBiExt.getPkId());
                        icStoreOutB.setPkCreator(pkMember);
                        icStoreOutB.setPkCountry(storeOutExt.getPkCountry());
                        storeOutBiList.add(icStoreOutB);
                    }
                }
                // 更新发货店铺发货单状态，更新为已发货
                saveStoreOutExtList.add(storeOutExt);
            }
        }
        if (storeOutBiList.size() > 0) {
            storeOutBiService.saveBatch(storeOutBiList);
        }
        if (saveStoreOutExtList.size() > 0) {
            storeOutBiService.updateStoreOutItemStatus(saveStoreOutExtList, EStoreStatus.STORE_SEND.getValue(), pkMember);
        }
    }

    @Override
    public List<IcStoreOutHExt> queryStoreOutByCondition(OrderQueryParam orderQueryParam) {
        return baseMapper.queryStoreOutByCondition(orderQueryParam);
    }
}
