package com.hfkj.channel.tianque.service;

import com.alibaba.fastjson.JSONObject;
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.config.CommonSysConst;
import com.hfkj.entity.*;
import com.hfkj.service.*;
import com.hfkj.sysenum.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

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

    private static Logger log = LoggerFactory.getLogger(TianQueLedgerService.class);
    @Resource
    private BsMerLedgerService merLedgerService;
    @Resource
    private BsMerLedgerApplyService merLedgerApplyService;

    /**
     * 分账协议签署
     * @param merLedgerId
     * @return
     */
    public JSONObject applyLedger(Long merLedgerId) {
        log.info("========= Start 分账协议签署 Start ===========");
        BsMerLedger merLedger = merLedgerService.getMerLedgerById(merLedgerId);
        if (merLedger == null || !merLedger.getPlatformType().equals(PlatformTypeEnum.type5.getNumber())) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
        }
        Map<String, Object> param = new HashMap<>();
        param.put("mno", merLedger.getCupNo());
        param.put("signType", "02"); // 线下签约
        param.put("ledgerLetter", RequestUtil.requestUpload("77", new File(CommonSysConst.getSysConfig().getFile_url() + "/" + merLedger.getSplitEntrustFilePath())).getString("PhotoUrl"));

        JSONObject responseBody = RequestUtil.request(TianQueConfig.requestUrl + "/merchant/sign/getUrl", 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"));
        }

        merLedger.setStatus(MerLedgerStatusEnum.status2.getNumber());
        merLedgerService.editMerLedger(merLedger);

        BsMerLedgerApply merLedgerApply = new BsMerLedgerApply();
        merLedgerApply.setMerLedgerId(merLedger.getId());
        merLedgerApply.setMerId(merLedger.getMerId());
        merLedgerApply.setOrderNo(System.currentTimeMillis()+"");
        merLedgerApply.setRequestBody(JSONObject.toJSONString(param));
        merLedgerApply.setResponseBody(responseBody.toJSONString());
        merLedgerApplyService.editMerLedgerApply(merLedgerApply);

        log.info("========= END 分账协议签署 END ===========");
        return responseBody;
    }

    /**
     * 分账协议签署结果查询
     * @param mno
     * @return
     */
    public JSONObject querySignContract(String mno) {
        log.info("========= Start 分账协议签署结果查询 Start ===========");
        Map<String, Object> param = new HashMap<>();
        param.put("mno", mno);

        JSONObject responseBody = RequestUtil.request(TianQueConfig.requestUrl + "/merchant/sign/querySignContract", 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;
    }

    /**
     * 分账接收方设置
     * @param mno
     * @return
     */
    public JSONObject querySignContract(String mno,List<String> mnoArray) {
        log.info("========= Start 分账设置 Start ===========");
        Map<String, Object> param = new HashMap<>();
        param.put("mno", mno);
        param.put("mnoArray", mnoArray.stream().distinct().collect(Collectors.joining(",")));// 分账收款商户编号（逗号分隔）

        JSONObject responseBody = RequestUtil.request(TianQueConfig.requestUrl + "/query/ledger/setMnoArray", 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;
    }
}
