package com.ruoyi.logistics.callback;

import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.logistics.domain.BizFinancialFeeItems;
import com.ruoyi.logistics.domain.BizWaybillCostDetails;
import com.ruoyi.logistics.domain.BizWaybillOrder;
import com.ruoyi.logistics.dto.JDOrderFeeRequestDTO;
import com.ruoyi.logistics.service.FeeItemsCacheService;
import com.ruoyi.logistics.service.IBizWaybillCostDetailsService;
import com.ruoyi.logistics.service.IBizWaybillOrderService;
import com.ruoyi.system.api.domain.SysDept;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDeptService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@Slf4j
@RestController
@RequestMapping("/callback/jd")
public class JDPushOrderFeeCallback {

    @Autowired
    private IBizWaybillOrderService bizWaybillOrderService;

    @Autowired
    private IBizWaybillCostDetailsService bizWaybillCostDetailsService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private FeeItemsCacheService feeItemsCacheService;

    @Autowired
    private ISysConfigService sysConfigService;

    @RequestMapping("/fee")
    public AjaxResult fee(@RequestBody JDOrderFeeRequestDTO request) {
        log.info("京东物流运单费用回调，参数：{}", request);

        // 根据运单号查询订单
        BizWaybillOrder query = new BizWaybillOrder();
        query.setExternalWaybillNo(request.getWaybillCode());
        BizWaybillOrder bizWaybillOrder = bizWaybillOrderService.selectBizWaybillOrderByQuery(query);
        if (bizWaybillOrder == null) {
            return AjaxResult.error("订单不存在");
        }
        SysDept sysDept = sysDeptService.selectDeptById(bizWaybillOrder.getDeptId());
        String rate = sysConfigService.selectConfigByKey(bizWaybillOrder.getProductCode());

        List<BizWaybillCostDetails> details = new ArrayList<>();
        if (CollectionUtils.isEmpty(request.getCommonActualFeeInfoDetails())) {
            return AjaxResult.error("费用信息为空");
        }
        request.getCommonActualFeeInfoDetails().forEach(item -> {
            BizWaybillCostDetails costDetail = new BizWaybillCostDetails();
            costDetail.setWaybillId(bizWaybillOrder.getWaybillId());
            costDetail.setExternalWaybillNo(bizWaybillOrder.getExternalWaybillNo());

            // 匹配费用类型项
            BizFinancialFeeItems feeItemByExtFeeCode = feeItemsCacheService.getFeeItemByExtFeeCode(item.getFeeType());
            if (feeItemByExtFeeCode != null) {
                costDetail.setFeeItemCode(feeItemByExtFeeCode.getFeeItemCode());
                costDetail.setFeeItemName(feeItemByExtFeeCode.getFeeItemName());
                costDetail.setFeeName(item.getFeeTypeName());
                costDetail.setAmount(item.getStandardAmount());
                if (StringUtils.isNotBlank(rate) && "快递运费".equals(feeItemByExtFeeCode.getFeeItemName())) {
                    BigDecimal subtract = new BigDecimal("1").subtract(new BigDecimal(rate).divide(new BigDecimal("100")));
                    costDetail.setPurchaseAmount(subtract.multiply(item.getStandardAmount()).setScale(2, BigDecimal.ROUND_HALF_UP));
                }
                if (!"快递运费".equals(feeItemByExtFeeCode.getFeeItemName())) {
                    costDetail.setRateAmount(item.getStandardAmount());
                    costDetail.setPurchaseAmount(item.getStandardAmount());
                }
                costDetail.setDeptId(bizWaybillOrder.getDeptId());
                costDetail.setUserId(bizWaybillOrder.getUserId());
            }

            details.add(costDetail);
        });

        details.forEach(detail -> {
            bizWaybillCostDetailsService.upsertBizWaybillCostDetails(detail);
        });

        return AjaxResult.success().put("message", "成功");
    }
}
