package com.hfkj.channel.tianque.service;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.channel.lakala.config.LaKaLaConfig;
import com.hfkj.channel.tianque.config.TianQueConfig;
import com.hfkj.channel.tianque.utils.RequestUtil;
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.common.utils.HttpsUtils;
import com.hfkj.config.CommonSysConst;
import com.hfkj.entity.*;
import com.hfkj.service.*;
import com.hfkj.sysenum.ProfitSharingCmdTypeEnum;
import com.hfkj.sysenum.ProfitSharingReceiverStatusEnum;
import com.hfkj.sysenum.ProfitSharingStatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 分账业务
 * @className: TianQueSeparateService
 * @author: HuRui
 * @date: 2023/9/22
 **/
@Component
public class TianQueSeparateService {

    private static Logger log = LoggerFactory.getLogger(TianQueSeparateService.class);

    @Resource
    private BsTradeOrderService tradeOrderService;
    @Resource
    private BsTradeOrderProfitSharingService tradeOrderProfitSharingService;
    @Resource
    private BsTradeOrderProfitSharingReceiverService tradeOrderProfitSharingReceiverService;
    @Resource
    private BsMerService merService;
    @Resource
    private CommonService commonService;

    /**
     * 发起分账
     * @param profitSharingOrderNo
     * @return
     */
    public BsTradeOrderProfitSharing separate(String profitSharingOrderNo) {
        log.info("========= Start 分账 Start ===========");
        // 交易分账
        BsTradeOrderProfitSharing tradeOrderProfitSharing = tradeOrderProfitSharingService.getDetailByProfitSharingOrderNo(profitSharingOrderNo);
        if (null == tradeOrderProfitSharing) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到交易分账记录");
        }
        if (!tradeOrderProfitSharing.getStatus().equals(ProfitSharingStatusEnum.status0.getNumber())) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "业务不处于待处理状态");
        }
        // 查询交易详情
        BsTradeOrder tradeOrder = tradeOrderService.getOrderByOutTradeNo(tradeOrderProfitSharing.getTradeOrderNo());
        // 分账接收方
        List<BsTradeOrderProfitSharingReceiver> profitSharingReceiverList = tradeOrderProfitSharingReceiverService.getReceiverListByProfitSharingId(tradeOrderProfitSharing.getId());

        Map<String, Object> param = new HashMap<>();
        param.put("mno", tradeOrder.getPlatformMerNo());
        param.put("ordNo", tradeOrder.getOutTradeNo());
        param.put("uuid", tradeOrderProfitSharing.getProfitSharingOrderNo());
        // 异步分账枚举：00 取消分账  01 分账
        param.put("ledgerAccountFlag", tradeOrderProfitSharing.getCmdType().equals(ProfitSharingCmdTypeEnum.CMD_TYPE_1.getNumber())?"01":"00");

        List<Map<String,Object>> recvDatasMapList = new ArrayList<>();
        Map<String,Object> recvDatasMap;

        for (BsTradeOrderProfitSharingReceiver receiver : profitSharingReceiverList) {
            if (receiver.getReceiverAmount().compareTo(new BigDecimal("0")) != 0) {
                recvDatasMap = new HashMap<>();
                recvDatasMap.put("mno", receiver.getReceiverAccount());
                recvDatasMap.put("allotValue", receiver.getReceiverAmount());
                recvDatasMapList.add(recvDatasMap);
            }
        }
        param.put("ledgerRule", recvDatasMapList);

        JSONObject responseBody = RequestUtil.request(TianQueConfig.requestUrl + "/query/ledger/launchLedger", param);
        log.info("请求参数：",JSONObject.toJSONString(param));
        log.info("响应参数：", responseBody.toJSONString());
        System.out.println("body：" + JSONObject.toJSONString(param));
        System.out.println("response：" + responseBody.toJSONString());
        if (!"0000".equals(responseBody.getString("bizCode"))) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, responseBody.getString("bizMsg"));
        }
        // 	分账状态 00 分账成功  01 分账失败  05 分账中
        String statusCode = responseBody.getString("ledgerStatus");
        if (statusCode.equals("05")) {
            tradeOrderProfitSharing.setStatus(ProfitSharingStatusEnum.status2.getNumber());
        } else if (statusCode.equals("00")) {
            tradeOrderProfitSharing.setStatus(ProfitSharingStatusEnum.status1.getNumber());
            tradeOrderProfitSharing.setProfitSharingTime(new Date());
            tradeOrderProfitSharing.setFinishTime(new Date());
        } else if (statusCode.equals("01")) {
            tradeOrderProfitSharing.setStatus(ProfitSharingStatusEnum.status4.getNumber());
        }
        tradeOrderProfitSharing.setPlatformProfitSharingOrderNo(responseBody.getString("uuid"));
        tradeOrderProfitSharingService.editData(tradeOrderProfitSharing);

        // 处理接收方数据
        if (tradeOrderProfitSharing.equals(ProfitSharingStatusEnum.status1.getName())) {
            for (BsTradeOrderProfitSharingReceiver receiver : profitSharingReceiverList) {
                receiver.setStatus(ProfitSharingReceiverStatusEnum.status1.getNumber());
                receiver.setProfitSharingTime(new Date());
                receiver.setFinishTime(new Date());
                tradeOrderProfitSharingReceiverService.editData(receiver);
            }
        }
        log.info("========= END 分账 END ===========");
        return tradeOrderProfitSharing;
    }

    /**
     * 分账撤销
     * @param profitSharingOrderNo 交易订单号
     * @return
     */
    public JSONObject cancel(String profitSharingOrderNo) {
        log.info("========= Start 分账撤销 Start ===========");
        // 交易订单分账
        BsTradeOrderProfitSharing tradeOrderProfitSharing = tradeOrderProfitSharingService.getDetailByProfitSharingOrderNo(profitSharingOrderNo);
        if (null == tradeOrderProfitSharing) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "未找到交易分账记录");
        }

        Map<String, Object> param = new HashMap<>();
        param.put("mno", tradeOrderProfitSharing.getPlatformMerNo());
        param.put("origUuid", tradeOrderProfitSharing.getOriginProfitSharingOrderNo());
        param.put("uuid",  tradeOrderProfitSharing.getProfitSharingOrderNo());

        List<Map<String,Object>> recvDatasMapList = new ArrayList<>();
        Map<String,Object> recvDatasMap;
        List<BsTradeOrderProfitSharingReceiver> receiverList = tradeOrderProfitSharingReceiverService.getReceiverListByProfitSharingId(tradeOrderProfitSharing.getId());
        for (BsTradeOrderProfitSharingReceiver receiver : receiverList) {
            recvDatasMap = new HashMap<>();
            recvDatasMap.put("mno", receiver.getReceiverNo());
            recvDatasMap.put("allotValue", receiver.getReceiverAmount());
            recvDatasMapList.add(recvDatasMap);
        }
        param.put("ledgerRule", recvDatasMapList);

        JSONObject responseBody = RequestUtil.request(TianQueConfig.requestUrl + "/query/ledger/ledgerBack", param);
        log.info("请求参数：",JSONObject.toJSONString(param));
        log.info("响应参数：", responseBody.toJSONString());
        System.out.println("body：" + JSONObject.toJSONString(param));
        System.out.println("response：" + responseBody.toJSONString());
        if (!"0000".equals(responseBody.getString("bizCode"))) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, responseBody.getString("bizMsg"));
        }
        tradeOrderProfitSharing.setStatus(ProfitSharingStatusEnum.status2.getNumber());
        tradeOrderProfitSharing.setPlatformProfitSharingOrderNo(responseBody.getJSONObject("resp_data").getString("separate_no"));
        tradeOrderProfitSharingService.editData(tradeOrderProfitSharing);
        log.info("========= end 分账撤销 end ===========");
        return responseBody;
    }

    /**
     * 分账交易金额查询
     * @param profitSharingOrderNo
     * @return
     */
    public JSONObject queryAmt(String tradeNo) {
        // 交易订单分账
        BsTradeOrder outTradeNo = tradeOrderService.getOrderByOutTradeNo(tradeNo);
        if (null == outTradeNo) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "未找到交易记录");
        }
        Map<String, Object> param = new HashMap<>();
        param.put("mno", outTradeNo.getPlatformMerNo());
        param.put("ordNo", outTradeNo.getOutTradeNo());

        JSONObject responseBody = RequestUtil.request(TianQueConfig.requestUrl + "/query/ledger/queryLedgerAmt", param);
        log.info("请求参数：",JSONObject.toJSONString(param));
        log.info("响应参数：", responseBody.toJSONString());
        System.out.println("body：" + JSONObject.toJSONString(param));
        System.out.println("response：" + responseBody.toJSONString());
        if (!"0000".equals(responseBody.getString("bizCode"))) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, responseBody.getString("bizMsg"));
        }
        return responseBody;
    }

    /**
     * 分账结果查询
     * @param profitSharingOrderNo 交易订单号
     * @return
     */
    public JSONObject query(String profitSharingOrderNo) {
        log.info("========= Start 分账结果查询 Start ===========");
        // 交易订单分账
        BsTradeOrderProfitSharing tradeOrderProfitSharing = tradeOrderProfitSharingService.getDetailByProfitSharingOrderNo(profitSharingOrderNo);
        if (null == tradeOrderProfitSharing) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "未找到交易分账记录");
        }
        Map<String, Object> param = new HashMap<>();
        param.put("mno", tradeOrderProfitSharing.getPlatformMerNo());
        param.put("uuid", tradeOrderProfitSharing.getProfitSharingOrderNo());

        JSONObject responseBody = RequestUtil.request(TianQueConfig.requestUrl + "/query/ledger/queryLedgerAccount", param);
        log.info("请求参数：",JSONObject.toJSONString(param));
        log.info("响应参数：", responseBody.toJSONString());
        System.out.println("body：" + JSONObject.toJSONString(param));
        System.out.println("response：" + responseBody.toJSONString());
        if (!"0000".equals(responseBody.getString("bizCode"))) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, responseBody.getString("bizMsg"));
        }
        log.info("========= end 分账结果查询 end ===========");
        return responseBody;
    }

}
