package com.hfkj.service.order;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.channel.gas.newlink.NewLinkRequestService;
import com.hfkj.channel.gas.shell.CqShellPetroleumRequestService;
import com.hfkj.common.exception.BaseException;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.utils.DateUtil;
import com.hfkj.entity.*;
import com.hfkj.model.order.OrderChildModel;
import com.hfkj.service.agent.BsAgentMerAccountService;
import com.hfkj.service.gas.BsGasOrderReceiptService;
import com.hfkj.service.gas.BsGasOrderService;
import com.hfkj.service.gas.BsGasOrderSpreadService;
import com.hfkj.service.merchant.BsMerchantAccountService;
import com.hfkj.service.merchant.BsMerchantChainBrandAccountService;
import com.hfkj.service.merchant.BsMerchantService;
import com.hfkj.service.spread.BsUserSpreadAccountService;
import com.hfkj.sysenum.gas.GasOrderReceiptStatusEnum;
import com.hfkj.sysenum.merchant.MerchantChainBrandSettleTypeEnum;
import com.hfkj.sysenum.merchant.MerchantSourceTypeEnum;
import com.hfkj.sysenum.gas.OrderOilStatus;
import com.hfkj.sysenum.order.OrderChildProductTypeEnum;
import com.hfkj.sysenum.spread.UserSpreadAccountRecordSourceTypeEnum;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

/**
 * 退款业务
 * @className: OrderRefundService
 * @author: HuRui
 * @date: 2024/6/24
 **/
@Component
public class OrderRefundBusiness {
    @Resource
    private BsOrderChildService orderChildService;
    @Resource
    private BsGasOrderService gasOrderService;
    @Resource
    private BsMerchantService merchantService;
    @Resource
    private BsMerchantAccountService merchantAccountService;
    @Resource
    private BsMerchantChainBrandAccountService merchantChainBrandAccountService;
    @Resource
    private BsGasOrderReceiptService gasOrderReceiptService;
    @Resource
    private BsAgentMerAccountService agentMerAccountService;
    @Resource
    private BsGasOrderSpreadService gasOrderSpreadService;
    @Resource
    private BsUserSpreadAccountService userSpreadAccountService;

    /**
     * 前置业务处理
     * @param refund
     */
    public BsOrderRefund prepose(BsOrderRefund refund) {
        // 查询商品订单
        OrderChildModel orderChild = orderChildService.getDetail(refund.getOrderChildNo());
        if (orderChild.getProductType().equals(OrderChildProductTypeEnum.type1.getCode())) {
            // 查询加油订单
            BsGasOrder gasOrder = gasOrderService.getDetailByOrderNo(refund.getOrderNo());
            if (gasOrder != null) {
                if (gasOrder.getChannelType().equals(MerchantSourceTypeEnum.type2.getNumber())) {
                    try {
                        // 请求团油渠道申请退款
                        JSONObject object = NewLinkRequestService.refuelingOrderRefund(gasOrder.getUserPhone(), gasOrder.getOrderNo(), refund.getRefundRemark());
                        if (object == null || !object.getString("code").equals("200")) {
                            gasOrder.setAbnormal(true);
                            gasOrder.setAbnormalContent("渠道申请退款失败！原因：" + object.getString("message"));
                            gasOrderService.updateGasOrder(gasOrder);
                        } else {
                            gasOrder.setStatus(OrderOilStatus.STATUS5.getNumber());
                            gasOrderService.updateGasOrder(gasOrder);
                        }
                    } catch (Exception e) {
                        gasOrder.setAbnormal(true);
                        gasOrder.setAbnormalContent("渠道申请退款失败！原因：未知原因");
                        gasOrderService.updateGasOrder(gasOrder);
                    }
                }
            }
        }
        return refund;
    }

    /**
     * 加油订单业务
     * @param refund
     */
    public void gasOrder(BsOrderRefund refund) throws Exception {
        // 查询加油订单
        BsGasOrder gasOrder = gasOrderService.getDetailByOrderNo(refund.getOrderNo());
        if (gasOrder != null) {
            gasOrder.setStatus(OrderOilStatus.STATUS4.getNumber());
            gasOrder.setRefundTime(refund.getFinishTime());
            gasOrder.setRefundRemarks(refund.getRefundRemark());
            gasOrderService.updateGasOrder(gasOrder);

            // 撤回开票记录
            Map<String,Object> param = new HashMap<>();
            param.put("orderNo", gasOrder.getOrderNo());
            param.put("status", GasOrderReceiptStatusEnum.status1.getStatus());
            List<BsGasOrderReceipt> orderReceiptList = gasOrderReceiptService.getList(param);
            for (BsGasOrderReceipt receipt : orderReceiptList) {
                receipt.setStatus(GasOrderReceiptStatusEnum.status99.getStatus());
                gasOrderReceiptService.editData(receipt);
            }

            if (gasOrder.getAgentId() != null && MerchantSourceTypeEnum.type1.getNumber().equals(gasOrder.getChannelType())) {
                try {
                    // 代理商商户账户退款
                    agentMerAccountService.refund(gasOrder.getAgentId(), gasOrder.getMerNo(), gasOrder.getGasAgentSettlePrice(), refund);

                } catch (BaseException e) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, e.getErrorMsg());
                } catch (Exception e) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "扣款失败，请稍后重新提交订单");
                }
            }
            try {
                // 订单是否异常 false：无异常  true：有异常
                if (gasOrder.getAbnormal().equals(false)) {
                    if (gasOrder.getChannelType().equals(MerchantSourceTypeEnum.type1.getNumber())) {
                        // 连锁品牌
                        if (gasOrder.getMerChainBrandId() != null) {
                            // 查询商户
                            BsMerchant merchant = merchantService.getMerchant(gasOrder.getMerNo());
                            if (MerchantChainBrandSettleTypeEnum.type1.getNumber().equals(merchant.getChainBrandSettleType())) {
                                // 退回连锁额度
                                merchantChainBrandAccountService.refund(gasOrder.getMerChainBrandId(), merchant.getMerNo(), gasOrder.getGasSettlePrice(), refund);
                            } else {
                                // 退回商户额度
                                merchantAccountService.refund(gasOrder.getMerNo(), gasOrder.getGasSettlePrice(), refund);
                            }
                        } else {
                            // 退回商户额度
                            merchantAccountService.refund(gasOrder.getMerNo(), gasOrder.getGasSettlePrice(), refund);
                        }
                    } else if (gasOrder.getChannelType().equals(MerchantSourceTypeEnum.type2.getNumber())) {
                        // 请求团油渠道退款
                        JSONObject object = NewLinkRequestService.refuelingOrderRefund(gasOrder.getUserPhone(), gasOrder.getOrderNo(), refund.getRefundRemark());
                        if (object == null || !object.getString("code").equals("200")) {
                            gasOrder.setAbnormal(true);
                            gasOrder.setAbnormalContent("渠道退款失败！原因：" + object.getString("message"));
                            gasOrderService.updateGasOrder(gasOrder);
                        }
                    } else if (gasOrder.getChannelType().equals(MerchantSourceTypeEnum.type3.getNumber())) {
                        try {
                            // 请求重庆壳牌渠道退款
                            CqShellPetroleumRequestService.gasSyncRefund(gasOrder.getPayTime(), gasOrder.getOrderNo());
                        } catch (BaseException e) {
                            gasOrder.setAbnormal(true);
                            gasOrder.setAbnormalContent("渠道退款失败！原因：" + e.getErrorMsg());
                            gasOrderService.updateGasOrder(gasOrder);
                        } catch (Exception e) {
                            gasOrder.setAbnormal(true);
                            gasOrder.setAbnormalContent("渠道退款失败！未知原因");
                            gasOrderService.updateGasOrder(gasOrder);
                        }
                    }
                }
            } catch (Exception e) {}

            // 分销
            Calendar payTime = Calendar.getInstance();
            payTime.setTime(gasOrder.getPayTime());
            LocalDate date = LocalDate.of(payTime.get(Calendar.YEAR),payTime.get(Calendar.MONDAY)+1,payTime.get(Calendar.DATE));
            // 不是今日的订单
            if (date.isBefore(LocalDate.now())) {
                // 扣除账户
                BsGasOrderSpread gasOrderSpread = gasOrderSpreadService.getDetailByOrderNo(gasOrder.getOrderNo());
                if (gasOrderSpread != null) {
                    Map<String,Object> otherParam = new HashMap<>();
                    otherParam.put("sourceContent","订单退款");

                    if (gasOrderSpread.getGainsRebateUserId() != null) {
                        userSpreadAccountService.minus(
                                gasOrderSpread.getGainsRebateUserId(),
                                gasOrderSpread.getGainsRebateAmount(),
                                UserSpreadAccountRecordSourceTypeEnum.type3,
                                otherParam
                                );
                    }

                    if (gasOrderSpread.getGainsRebateOneUserId() != null) {
                        userSpreadAccountService.minus(
                                gasOrderSpread.getGainsRebateOneUserId(),
                                gasOrderSpread.getGainsRebateOneAmount(),
                                UserSpreadAccountRecordSourceTypeEnum.type3,
                                otherParam
                        );
                    }

                    if (gasOrderSpread.getGainsRebateTwoUserId() != null) {
                        userSpreadAccountService.minus(
                                gasOrderSpread.getGainsRebateTwoUserId(),
                                gasOrderSpread.getGainsRebateTwoAmount(),
                                UserSpreadAccountRecordSourceTypeEnum.type3,
                                otherParam
                        );
                    }
                }
            }

        }
    }

}
