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


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.yc.ship.framework.common.util.collection.CollectionUtils;
import com.yc.ship.framework.common.util.object.ObjectUtils;
import com.yc.ship.module.trade.api.insurance.InsuranceApi;
import com.yc.ship.module.trade.api.insurance.dto.InsuranceApplyReqDTO;
import com.yc.ship.module.trade.api.insurance.dto.InsuredDTO;
import com.yc.ship.module.trade.api.insurance.dto.InsuredRespDTO;
import com.yc.ship.module.trade.dal.dataobject.order.TradeOrderDO;
import com.yc.ship.module.trade.dal.dataobject.refund.RefundDO;
import com.yc.ship.module.trade.enums.InsuranceStatusEnum;
import com.yc.ship.module.trade.service.order.TradeOrderRepositoryService;
import com.yc.ship.module.trade.service.order.bo.TradeVisitorBO;
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.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * &#064;Description 保险处理
 * &#064;Author qsl
 * &#064;Date 2025/8/16 14:49
 */
@Component
@Order(TradeOrderHandler.INSURANCE)
@Slf4j
public class InsuranceHandler implements TradeOrderHandler{


    @Resource
    private InsuranceApi insuranceApi;
    @Resource
    private TradeOrderRepositoryService tradeOrderRepositoryService;
    @Resource
    private TradeRefundRepositoryService tradeRefundRepositoryService;

    @Override
    public void afterProcessSuccess(TradeOrderDO tradeOrderDO) {
        try {
            insure(tradeOrderDO);
        }catch (Exception e){
            log.error("投保异常",e);
        }
    }
    private void insure(TradeOrderDO tradeOrderDO){
        //获取订单中的投保产品
        List<Map<String, Object>> insuranceProductList = tradeOrderRepositoryService.getInsuranceProductFromOrder(tradeOrderDO.getId());
        if(CollUtil.isEmpty(insuranceProductList)){
            return;
        }

        List<InsuranceApplyReqDTO> dataList = new ArrayList<>();
        for (Map<String, Object> insuranceProduct : insuranceProductList) {
            if(StrUtil.isBlank(MapUtil.getStr(insuranceProduct,"insurance_code"))){
                continue;
            }
            //查询订单是否需要投保，根据订单下的游客信息是否有投保标志
            List<TradeVisitorBO> visitorDOList = tradeOrderRepositoryService.getInsureVisitor(tradeOrderDO.getId(),MapUtil.getLong(insuranceProduct,"product_id"));
            if(CollUtil.isEmpty(visitorDOList)){
                log.info("当前产品无投保信息{}",MapUtil.getLong(insuranceProduct,"product_id"));
                continue;
            }
            TradeVisitorBO holder = visitorDOList.get(0);
            InsuranceApplyReqDTO reqDTO = new InsuranceApplyReqDTO();
//            reqDTO.setOrderId(tradeOrderDO.getId());
//            reqDTO.setAmount(MapUtil.get(insuranceProduct,"insurance_amount", BigDecimal.class));
//            reqDTO.setPremium(MapUtil.get(insuranceProduct,"num", BigDecimal.class));
//            reqDTO.setRationType(MapUtil.get(insuranceProduct,"insurance_code", String.class));
//            reqDTO.setTravelDate(holder.getUseDate());
//            reqDTO.setHolderName(holder.getName());
//            reqDTO.setHolderNo(holder.getCredentialNo());
//            reqDTO.setInsuredList(CollectionUtils.convertList(visitorDOList, this::convert));
            dataList.add(reqDTO);
        }

        int insureFlag = 1;
        for (InsuranceApplyReqDTO reqDTO : dataList) {
            InsuredRespDTO insuredRespDTO = insuranceApi.applyInsurance(reqDTO).getCheckedData();
            if(ObjectUtils.equalsAny(insuredRespDTO.getInsuranceStatus() , InsuranceStatusEnum.INSURE.getValue(),InsuranceStatusEnum.FAIL.getValue(),InsuranceStatusEnum.CANCELLED.getValue())){
                insureFlag = 0;
            }
        }
        tradeOrderRepositoryService.updateOrderInsureStatus(tradeOrderDO.getId(),insureFlag);
    }
    @Override
    public void afterRefundOrder(Long refundId) {
        try {
            RefundDO refundDO = tradeRefundRepositoryService.getById(refundId);
            TradeOrderDO tradeOrderDO = tradeOrderRepositoryService.getById(refundDO.getOrderId());
            if(tradeOrderDO.getIsInsure() == null){
                return;
            }
            //先取消
            List<Long> orderIdList = new ArrayList<>();
            orderIdList.add(tradeOrderDO.getId());
            insuranceApi.cancelInsurance(orderIdList);
            //再重新投保
            insure(tradeOrderDO);
        }catch (Exception e){
            log.error("再投保异常",e);
        }
    }

    private InsuredDTO convert(TradeVisitorBO tradeVisitorBO){
        InsuredDTO insuredDTO = new InsuredDTO();
//        insuredDTO.setInsuredIdNo(tradeVisitorBO.getCredentialNo());
        insuredDTO.setInsuredName(tradeVisitorBO.getName());
//        insuredDTO.setInsuredIdType(String.valueOf(tradeVisitorBO.getCredentialType()));
        return insuredDTO;
    }

}
