package com.yc.ship.module.trade.service.order.handler;

import com.yc.ship.framework.common.util.object.ObjectUtils;
import com.yc.ship.module.ota.api.OtaDistributorApi;
import com.yc.ship.module.product.enums.SpecTypeEnum;
import com.yc.ship.module.trade.dal.dataobject.order.TradeDetailBaseDO;
import com.yc.ship.module.trade.dal.dataobject.order.TradeDetailDO;
import com.yc.ship.module.trade.dal.dataobject.order.TradeOrderDO;
import com.yc.ship.module.trade.service.order.TradeOrderRepositoryService;
import com.yc.ship.module.trade.service.order.bo.TradeOrderBO;
import com.yc.ship.module.trade.service.refund.TradeRefundRepositoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * &#064;Description ：产品库存处理
 * &#064;Author ：qsl
 * &#064;Date ：2025/6/6 21:23
 */
@Component
@Order(TradeOrderHandler.ORDER_STOCK)
@Slf4j
public class TradeProductStockOrderHandler implements TradeOrderHandler{

    @Resource
    private OtaDistributorApi otaDistributorApi;
    @Resource
    private TradeOrderRepositoryService tradeOrderRepositoryService;
    @Resource
    private TradeRefundRepositoryService tradeRefundRepositoryService;

    @Override
    public void beforeOrderCreate(TradeOrderBO order) {

    }

    private Map<Long,List<TradeDetailBaseDO>> getTradeDetailBaseDO(List<TradeDetailBaseDO> tradeDetailBaseDOList){
        return tradeDetailBaseDOList.stream().collect(Collectors.groupingBy(TradeDetailBaseDO::getProductBaseId));
    }



    @Override
    public void afterOrderCreateFail(TradeOrderBO order) {
        //还库存
        try {
//            List<ReduceStockReqDTO> productList = getProductList(order);
//
//            if(CollUtil.isEmpty(productList)){
//                return;
//            }
//            //如果是改签则不扣除，沿用原库存
//            if(ObjectUtil.equal(order.getExtraInfo().getIsChange(),YES)){
//                stockApi.backResourceStock(productList);
//            }else{
//                stockApi.backStock(productList);
//                //根据当前产品、分销商查找分销产品，归还库存，此情况只能是单票种下单
//                ReduceStockReqDTO reduceStockReqDTO = productList.get(0);
//                backDistributorProduct(reduceStockReqDTO.getId(),Long.parseLong(order.getTradeOrderDO().getSourceId()),order.getTradeOrderDO().getSellMethod(),reduceStockReqDTO.getUseDate(),reduceStockReqDTO.getNum());
//
//            }

        }catch (Exception e){
            log.error("归还库存异常",e);
        }
    }

    @Override
    public void afterSupplierOrderCreateFail(TradeOrderDO tradeOrderDO) {
        //还库存
        backStock(tradeOrderDO);
    }

    @Override
    public void afterCancelOrder(TradeOrderDO tradeOrderDO) {
        //还库存
        backStock(tradeOrderDO);
    }

    private void backStock(TradeOrderDO tradeOrderDO){

//        List<Map<String, Object>> orderProductList = tradeOrderRepositoryService.getOrderProductV2(tradeOrderDO.getId(),Collections.singletonList(SpecTypeEnum.CARRYING_CHILDREN.getType()));
//        List<TradeOrderDetailBaseBO> productBaseList = tradeOrderRepositoryService.getProductBaseByOrder(tradeOrderDO.getId());
//        List<ReduceStockReqDTO> productList = new ArrayList<>();
//        for (Map<String, Object> productMap : orderProductList) {
//            Long productId = MapUtil.getLong(productMap,"product_id");
//            Long routePlanId = MapUtil.getLong(productMap,"route_plan_id");//暂时不考虑订单出现重复产品的情况
//            Integer routePlanGroupType = MapUtil.getInt(productMap,"route_plan_group_type");
//            int productType = MapUtil.getInt(productMap,"product_type");
//            int quantityOfOne = MapUtil.getInt(productMap,"quantity_of_one");
//            if(productType!=PRODUCT_BASE_TYPE_SELF){
//                continue;
//            }
//            ReduceStockReqDTO reqDTO = new ReduceStockReqDTO();
//            Date useDate =  MapUtil.getDate(productMap,"use_date");
//            int buyCount = MapUtil.getInt(productMap,"buyCount") * quantityOfOne;
//            reqDTO.setId(productId);
//            reqDTO.setNum(buyCount);
//            reqDTO.setSellMethod(tradeOrderDO.getSellMethod());
//            reqDTO.setRoutePlanId(routePlanId);
//            reqDTO.setRoutePlanGroupType(routePlanGroupType);
//            reqDTO.setUseDate(useDate);
//            if(ObjectUtils.equalsAny(tradeOrderDO.getSellMethod(), SellMethodEnum.OTA.getType(),SellMethodEnum.OTC.getType(), SellMethodEnum.OTA_SYSTEM.getType(),SellMethodEnum.OTC_MOVE_ORDER.getType())){
//                reqDTO.setDistributorId(Long.parseLong(tradeOrderDO.getSourceId()));
//                reqDTO.setStoreId(tradeOrderDO.getStoreId());
//            }
//            List<ReduceStockReqDTO> baseReduceList = new ArrayList<>();
//
//            productBaseList.stream().filter(productBase ->ObjectUtil.equal(productBase.getProductId(),productId.toString())).forEach(productBase->{
//                if(productBase.getProductBaseType() == PRODUCT_BASE_TYPE_SELF){
//                    //自建产品库存
//                    ReduceStockReqDTO baseReqDto = new ReduceStockReqDTO();
//                    baseReqDto.setId(productBase.getProductBaseId());
//                    baseReqDto.setNum(productBase.getQuantity() * quantityOfOne);
//                    baseReqDto.setProductResourceId(productBase.getProductResourceId());
//                    baseReqDto.setUseDate(DateUtils.of(productBase.getUseDate()));
//                    baseReqDto.setSellMethod(tradeOrderDO.getSellMethod());
//                    baseReqDto.setRoutePlanId(routePlanId);
//                    baseReqDto.setRoutePlanGroupType(routePlanGroupType);
//                    if(ObjectUtils.equalsAny(tradeOrderDO.getSellMethod(), SellMethodEnum.OTA.getType(),SellMethodEnum.OTC.getType(), SellMethodEnum.OTA_SYSTEM.getType(),SellMethodEnum.OTC_MOVE_ORDER.getType())){
//                        baseReqDto.setDistributorId(Long.parseLong(tradeOrderDO.getSourceId()));
//                        baseReqDto.setStoreId(tradeOrderDO.getStoreId());
//                    }
//                    baseReduceList.add(baseReqDto);
//                }
//            });
//            reqDTO.setBaseReduceList(baseReduceList);
//            productList.add(reqDTO);
//        }
//        if(CollUtil.isNotEmpty(productList)){
//
//            //如果是改签则不扣除，沿用原库存
//            if(ObjectUtil.equal(tradeOrderDO.getIsChangeOrder(),ORDER_CHANGE_TYPE_NEW)){
//                stockApi.backResourceStock(productList);
//            }else{
//                stockApi.backStock(productList);
//
//                //根据当前产品、分销商查找分销产品，归还库存，此情况只能是单票种下单
//                ReduceStockReqDTO reduceStockReqDTO = productList.get(0);
//                backDistributorProduct(reduceStockReqDTO.getId(),Long.parseLong(tradeOrderDO.getSourceId()),tradeOrderDO.getSellMethod(),reduceStockReqDTO.getUseDate(),reduceStockReqDTO.getNum());
//
//            }
//
//        }
    }

    @Override
    public void afterRefundOrder(Long refundId) {
//        //还库存
//        RefundDO refundDO = tradeRefundRepositoryService.getById(refundId);
//        List<Map<String, Object>> orderProductList = tradeRefundRepositoryService.getRefundOrderProductV2(refundId,Collections.singletonList(SpecTypeEnum.CARRYING_CHILDREN.getType()));
//        List<TradeOrderDetailBaseBO> productBaseList = tradeRefundRepositoryService.getProductBaseByRefund(refundId);
//        TradeOrderDO tradeOrderDO = tradeOrderRepositoryService.getById(refundDO.getOrderId());
//        List<ReduceStockReqDTO> productList = new ArrayList<>();
//        for (Map<String, Object> productMap : orderProductList) {
//            Long productId = MapUtil.getLong(productMap,"product_id");
//            Long routePlanId = MapUtil.getLong(productMap,"route_plan_id");//暂时不考虑订单出现重复产品的情况
//            Integer routePlanGroupType = MapUtil.getInt(productMap,"route_plan_group_type");
//            int productType = MapUtil.getInt(productMap,"product_type");
//            int quantityOfOne = MapUtil.getInt(productMap,"quantity_of_one");
//            if(productType!=PRODUCT_BASE_TYPE_SELF){
//                continue;
//            }
//            ReduceStockReqDTO reqDTO = new ReduceStockReqDTO();
//            Date useDate =  MapUtil.getDate(productMap,"use_date");
//            int buyCount = MapUtil.getInt(productMap,"refundCount") * quantityOfOne;
//            reqDTO.setId(productId);
//            reqDTO.setNum(buyCount);
//            reqDTO.setSellMethod(refundDO.getSellMethod());
//            reqDTO.setRoutePlanId(routePlanId);
//            reqDTO.setRoutePlanGroupType(routePlanGroupType);
//            reqDTO.setUseDate(useDate);
//            if(ObjectUtils.equalsAny(refundDO.getSellMethod(), SellMethodEnum.OTA.getType(),SellMethodEnum.OTC.getType(), SellMethodEnum.OTA_SYSTEM.getType(),SellMethodEnum.OTC_MOVE_ORDER.getType())){
//                reqDTO.setDistributorId(Long.parseLong(tradeOrderDO.getSourceId()));
//                reqDTO.setStoreId(tradeOrderDO.getStoreId());
//            }
//            List<ReduceStockReqDTO> baseReduceList = new ArrayList<>();
//
//            productBaseList.stream().filter(productBase ->ObjectUtil.equal(productBase.getProductId(),productId.toString())).forEach(productBase->{
//                if(productBase.getProductBaseType() == PRODUCT_BASE_TYPE_SELF){
//                    //自建产品库存
//                    ReduceStockReqDTO baseReqDto = new ReduceStockReqDTO();
//                    baseReqDto.setId(productBase.getProductBaseId());
//                    baseReqDto.setNum(productBase.getQuantity() * quantityOfOne);
//                    baseReqDto.setProductResourceId(productBase.getProductResourceId());
//                    baseReqDto.setUseDate(DateUtils.of(productBase.getUseDate()));
//                    baseReqDto.setSellMethod(refundDO.getSellMethod());
//                    baseReqDto.setRoutePlanId(routePlanId);
//                    baseReqDto.setRoutePlanGroupType(routePlanGroupType);
//                    if(ObjectUtils.equalsAny(refundDO.getSellMethod(), SellMethodEnum.OTA.getType(),SellMethodEnum.OTC.getType(), SellMethodEnum.OTA_SYSTEM.getType(),SellMethodEnum.OTC_MOVE_ORDER.getType())){
//                        baseReqDto.setDistributorId(Long.parseLong(tradeOrderDO.getSourceId()));
//                        baseReqDto.setStoreId(tradeOrderDO.getStoreId());
//                    }
//                    baseReduceList.add(baseReqDto);
//                }
//            });
//            reqDTO.setBaseReduceList(baseReduceList);
//            productList.add(reqDTO);
//        }
//        if(CollUtil.isNotEmpty(productList)){
//            try {
//                //改签退款不处理
//                if(ObjectUtil.equal(refundDO.getRefundMethod(),REFUND_METHOD_CHANGE_ORDER)){
//                    stockApi.backResourceStock(productList).getCheckedData();
//                }else{
//                    stockApi.backStock(productList).getCheckedData();
//                    if(ObjectUtils.equalsAny(refundDO.getSellMethod(), SellMethodEnum.OTA.getType(),SellMethodEnum.OTC.getType(),SellMethodEnum.OTC_MOVE_ORDER.getType(),SellMethodEnum.OTA_SYSTEM.getType())){
//                        //根据当前产品、分销商查找分销产品，归还库存，此情况只能是单票种下单
//                        ReduceStockReqDTO reduceStockReqDTO = productList.get(0);
//                        backDistributorProduct(reduceStockReqDTO.getId(),Long.parseLong(tradeOrderDO.getSourceId()),tradeOrderDO.getSellMethod(),reduceStockReqDTO.getUseDate(),reduceStockReqDTO.getNum());
//                    }
//                }
//
//            }catch (Exception e){
//                log.error("归还库失败",e);
//            }
//        }
    }

    private void backDistributorProduct(Long productId,Long distributorId,Integer sellMethod,Date useDate,Integer num){
//        if(ObjectUtils.equalsAny(sellMethod, SellMethodEnum.OTA.getType(),SellMethodEnum.OTC.getType(),SellMethodEnum.OTA_SYSTEM.getType(),SellMethodEnum.OTC_MOVE_ORDER.getType())){
//            DistributorProductRespDTO distributorProduct = otaDistributorApi.getDistributorProductByProductAndDistributor(productId,distributorId).getCheckedData();
//            StockDistributorDeductReqDTO deductReqDTO = new StockDistributorDeductReqDTO();
//            deductReqDTO.setNum(num);
//            deductReqDTO.setUseDate(useDate);
//            deductReqDTO.setDistributorProductId(Long.parseLong(distributorProduct.getId()));
//            stockApi.backDistributorStock(deductReqDTO).getCheckedData();
//        }
    }
}
