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


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yc.ship.module.trade.api.dto.RuleSpecDTO;
import com.yc.ship.module.trade.api.dto.RuleVerifyDTO;
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.TradeOrderBindDO;
import com.yc.ship.module.trade.dal.dataobject.order.TradeOrderDO;
import com.yc.ship.module.trade.enums.SellMethodEnum;
import com.yc.ship.module.trade.enums.TradeOrderBindEnum;
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.order.bo.TradeOrderDetailBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * &#064;Description 合同处理
 * &#064;Author qsl
 * &#064;Date 2025/8/16 14:49
 */
@Component
@Order(TradeOrderHandler.MARKETING)
@Slf4j
public class MarketingHandler implements TradeOrderHandler{

    @Resource
    private TradeOrderRepositoryService tradeOrderRepositoryService;

    @Override
    public void beforeOrderCreate(TradeOrderBO order) {
        //验证是否有符合营销政策的优惠券
        try {
            //目前只考虑外部旅行社
//            if(ObjectUtil.notEqual(order.getTradeOrderDO().getSellMethod(), SellMethodEnum.OTC_MOVE_ORDER.getType())){
//                return;
//            }
//            //此处只考虑一种产品
//            TradeOrderDetailBO tradeOrderDetailBO = order.getTradeOrderDetailBOList().get(0);
//            RuleVerifyDTO ruleVerifyDTO = new RuleVerifyDTO();
//            ruleVerifyDTO.setProductId(tradeOrderDetailBO.getProductSpuRespDTO().getId());
//            ruleVerifyDTO.setOrderId(order.getTradeOrderDO().getId());
//            Map<String, List<TradeDetailDO>> tradeDetailMap = tradeOrderDetailBO.getTradeDetailDOList().stream().collect(Collectors.groupingBy(TradeDetailDO::getSpecType));
//            List<RuleSpecDTO> ruleSpecList = tradeDetailMap.entrySet().stream().map(entry -> {
//                RuleSpecDTO ruleSpecDTO = new RuleSpecDTO();
//                ruleSpecDTO.setSpecType(entry.getKey());
//                ruleSpecDTO.setNum(entry.getValue().size());
//                return ruleSpecDTO;
//            }).collect(Collectors.toList());
//            ruleVerifyDTO.setRuleSpecNums(ruleSpecList);
//            ruleVerifyDTO.setStoreId(order.getTradeOrderDO().getStoreId());
        }catch (Exception e) {
            log.error("营销政策验券异常",e);
        }
    }

    @Override
    public void afterOrderCreate(TradeOrderBO order) {

    }

    @Override
    public void afterProcessSuccess(TradeOrderDO tradeOrderDO) {
        try {
            //marketingService.marketingApplyByOrderId(tradeOrderDO);
//            marketingService.marketingApplyByOrderIdNew(tradeOrderDO);
        }catch (Exception e){
            log.error("营销政策申请异常",e);
        }
        try {
            List<TradeOrderBindDO> bindList = tradeOrderRepositoryService.getBindOrderByOrderId(tradeOrderDO.getId(), TradeOrderBindEnum.MARKETING_POLICY_COUPON);
            if(CollUtil.isEmpty(bindList)){
                return;
            }

            RuleVerifyDTO ruleVerifyDTO = JSONUtil.toBean(bindList.get(0).getCustom(), RuleVerifyDTO.class);
//            marketingService.marketingCouponExecute(ruleVerifyDTO);
        }catch (Exception e){
            log.error("订单优惠劵执行",e);
        }
    }

    /**
     * 重置订单金额
     * @param order
     */
    private void resetOrderPrice(TradeOrderBO order){
        BigDecimal payAmount = order.getTradeOrderDO().getPayAmount();
        BigDecimal originPayAmount = order.getExtraInfo().getOriginPayAmount();
        if(originPayAmount.compareTo(BigDecimal.ZERO) == 0){
            return;
        }
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (TradeOrderDetailBO tradeOrderDetailBO : order.getTradeOrderDetailBOList()) {
            for (TradeDetailDO tradeDetailDO : tradeOrderDetailBO.getTradeDetailDOList()) {
                BigDecimal price = tradeDetailDO.getActualPrice().multiply(payAmount).divide(originPayAmount,2, RoundingMode.HALF_DOWN);
                BigDecimal originPrice = tradeDetailDO.getActualPrice();
                tradeDetailDO.setActualPrice(price);
                totalAmount = totalAmount.add(price);
                if(tradeDetailDO == tradeOrderDetailBO.getTradeDetailDOList().get(tradeOrderDetailBO.getTradeDetailDOList().size() -1)){
                    //最后一个了
                    BigDecimal subPrice = payAmount.subtract(totalAmount);
                    tradeDetailDO.setActualPrice(subPrice.add(price));
                }
                //重置detailBase金额
                List<TradeDetailBaseDO> tradeDetailBaseDOList = tradeOrderDetailBO.getTradeDetailBaseDOList().stream().filter(detailBase -> ObjectUtil.equal(detailBase.getDetailId(), tradeDetailDO.getId())).collect(Collectors.toList());
                resetDetailBasePrice(tradeDetailBaseDOList,tradeDetailDO.getActualPrice(),originPrice);
            }
        }
    }

    private void resetDetailBasePrice(List<TradeDetailBaseDO> tradeDetailBaseDOList,BigDecimal newPrice,BigDecimal originPrice){
        if(originPrice.compareTo(BigDecimal.ZERO) == 0){
            return;
        }
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (TradeDetailBaseDO tradeDetailBaseDO : tradeDetailBaseDOList) {
            BigDecimal price = tradeDetailBaseDO.getPrice().multiply(newPrice).divide(originPrice,2, RoundingMode.HALF_DOWN);
            tradeDetailBaseDO.setPrice(price);
            totalAmount = totalAmount.add(price);
            if(tradeDetailBaseDO == tradeDetailBaseDOList.get(tradeDetailBaseDOList.size() - 1)) {
                //最后一个了
                BigDecimal subPrice = newPrice.subtract(totalAmount);
                tradeDetailBaseDO.setPrice(subPrice.add(price));
            }
        }
    }
}
