package com.gree.mall.manager.logic.settle.repair.cmc;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.gree.mall.manager.bean.settle.repair.cmc.*;
import com.gree.mall.manager.plus.entity.SettleDailySecretKey;
import com.gree.mall.manager.plus.service.SettleDailySecretKeyService;
import com.gree.mall.manager.utils.CommonUtils;
import com.gree.mall.manager.utils.sm4.DCHelper;
import com.gree.mall.manager.utils.sm4.SMHttpTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class CmcBankLogic {

    @Value("${cmc.bank.url}")
    private String requestUrl;

    private String publicKey;

    private String privateKey;

    private String sm4key;

    private String userId;

    @Autowired
    SettleDailySecretKeyService settleDailySecretKeyService;

    //联动代发明细查询
    private final String CMC_TRANSFER_RESULT = "NTLKATLD";
    //联动代发账号已签约代发协议列表查询
    private final String CMC_QUERY_PROTOCOL = "NTLKACVD";
    //代发经办
    private final String CMC_DAIFA = "NTLKAOPD";
    //批量获取账户余额
    private final String CMC_GET_BALANCE_CODE = "NTQADINF";
    //联动支付经办
    private final String CMC_GET_K_PAY = "NTOPRLKP";
    //查询可经办业务列表 NTLKPCTL
    private final String CMC_CAN_DO = "NTLKPCTL";
    //查询授权帐号列表 NTLPALST
    private final String CMC_AUTH_ACCOUNT = "NTLPALST";

    //联动支付综合查询 NTQRYLKP
    private final String CMC_GET_PAY_RESULT = "NTQRYLKP";
    // 联动代发业务查询NTLKAQRD
    private final String CMC_DAIFA_SEL = "NTLKAQRD";

    public Map<String, Object> doRequestWithParams(JsonObject jsonObject, String funCode) throws Exception {
        return SMHttpTool.doProcess(jsonObject, funCode, requestUrl, publicKey, privateKey, sm4key, userId);
    }

    /**
     * @param list bankOrgCode: 分行代码 bankAccount：银行卡号
     * @return
     * @throws Exception
     */
    public Map<String, Object> getAccountBalance(List<BankCardInfoBean> list, String summaryNumber) throws Exception {
        log.info("【查询银行卡余额开始------】");
        putSecretKey(summaryNumber);
        JsonArray array = new JsonArray();
        for (BankCardInfoBean bean : list) {
            JsonObject item = new JsonObject();
            item.addProperty("bbknbr", bean.getBankOrgCode());
            item.addProperty("accnbr", bean.getBankAccount());
            array.add(item);
        }
        Map<String, Object> result = this.doRequestWithParams(putParams("ntqadinfx", array, CMC_GET_BALANCE_CODE), CMC_GET_BALANCE_CODE);
        log.info("【查询银行卡余额结束------】");
        return result;
    }

    /**
     * 查询可经办业务列表
     *
     * @param busmod 业务模式编号
     * @return
     * @throws Exception
     */
    public Map<String, Object> getCanDo(String busmod, String summaryNumber) throws Exception {
        log.info("【查询可经办业务列表开始------】");
        putSecretKey(summaryNumber);
        JsonArray array = new JsonArray();
        JsonObject item = new JsonObject();
        item.addProperty("busmod", busmod);
        array.add(item);
        Map<String, Object> result = doResult(this.doRequestWithParams(putParams("ntlkpctlx1", array, CMC_CAN_DO), CMC_CAN_DO), "ntlkpctlz1");
        log.info("【查询可经办业务列表结束------】");
        return result;
    }

    /**
     * 查询授权业务列表
     *
     * @param list 业务模式编号 summaryNumber 结算单位编号
     * @return
     * @throws Exception
     */
    public Map<String, Object> getAuthAccount(List<BankCardInfoBean> list, String summaryNumber) throws Exception {
        log.info("【查询授权业务列表开始------】");
        putSecretKey(summaryNumber);
        JsonArray array = new JsonArray();
        for (BankCardInfoBean bean : list) {
            JsonObject item = new JsonObject();
            item.addProperty("bbknbr", bean.getBankOrgCode());
            item.addProperty("accnbr", bean.getBankAccount());
            item.addProperty("auttyp", bean.getAuthType());
            array.add(item);
        }
        Map<String, Object> result = doResult(this.doRequestWithParams(putParams("ntlpalstx1", array, CMC_AUTH_ACCOUNT), CMC_AUTH_ACCOUNT), "ntlpalstz1");
        log.info("【查询授权业务列表结束------】");
        return result;
    }


    /**
     * 企银支付批量经办 (废弃暂时不使用)
     *
     * @param
     * @return
     * @throws Exception
     */
    @Deprecated
    public Map<String, Object> kPay(LinkPayBean linkPayBean, String summaryNumber) {
        putSecretKey(summaryNumber);
        log.info("【企银支付批量经办开始】");
        Map<String, Object> result = new HashMap<>();
        try {
            JsonObject obj = new JsonObject();
            JsonObject req = new JsonObject();
            JsonObject body = new JsonObject();
            JsonObject head = new JsonObject();
            head.addProperty("funcode", CMC_GET_K_PAY);
            head.addProperty("userid", userId);
            head.addProperty("reqid", DCHelper.getTime() + "0000001");

            JsonArray bmdArray = new JsonArray();
            JsonArray payArray = new JsonArray();

            for (ModBean mod : linkPayBean.getModList()) {
                JsonObject item = new JsonObject();
                item.addProperty("busMod", mod.getBusmod());
                bmdArray.add(item);
            }

            for (PayBean pay : linkPayBean.getPayList()) {
                JsonObject item = new JsonObject();
                item.addProperty("yurref", pay.getYurref());
                item.addProperty("dbtbbk", pay.getDbtbbk());
                item.addProperty("dbtacc", pay.getDbtacc());
                item.addProperty("auteac", pay.getAuteac());
                item.addProperty("crtacc", pay.getCrtacc());
                item.addProperty("crtnam", pay.getCrtnam());
                item.addProperty("crtadr", pay.getCrtadr());
                item.addProperty("trsamt", pay.getTrsamt());
                item.addProperty("busnar", pay.getBusnar());
                item.addProperty("trstyp", "100001");
                payArray.add(item);
            }

            body.add("ntbusmody", bmdArray);
            body.add("ntoprlkpx1", payArray);
            req.add("head", head);
            req.add("body", body);
            obj.add("request", req);

            result = doResult(this.doRequestWithParams(obj, CMC_GET_K_PAY), "ntoprrtnz");
        } catch (Exception e) {
            log.info("【KPay】: {}", e);
            result.put("code", "201");
        }
        return result;
    }


    /**
     * 联动支付综合查询 (废弃暂不使用，单个转账)
     *
     * @param
     * @return
     * @throws Exception
     */
    @Deprecated
    public Map<String, Object> kPayResult(List<PayResultBean> payResults, String summaryNumber) throws Exception {
        putSecretKey(summaryNumber);
        log.info("【联动支付综合查询开始】" + summaryNumber);

        JsonArray payResultArray = new JsonArray();
        for (PayResultBean resultBean : payResults) {
            JsonObject item = new JsonObject();
            item.addProperty("bgndat", resultBean.getBgndat());
            item.addProperty("enddat", resultBean.getEnddat());
            item.addProperty("refkey", resultBean.getRefkey());
            payResultArray.add(item);
        }

        Map<String, Object> result = doResult(this.doRequestWithParams(putParams("ntqrylkpy1", payResultArray, CMC_QUERY_PROTOCOL), CMC_QUERY_PROTOCOL), "ntqrylkpz1");
        log.info("【联动代发账号已签约代发协议列表查询 结束】");
        return result;
    }


    /**
     * 联动代发账号已签约代发协议列表查询 NTLKACV
     */
    public Map<String, Object> queryProtocol(BankCardInfoBean cardInfoBean, String summaryNumber) throws Exception {
        putSecretKey(summaryNumber);
        log.info("【联动代发账号已签约代发协议列表查询 开始】");
        JsonArray array = new JsonArray();
        JsonObject item = new JsonObject();
        item.addProperty("bbknbr", cardInfoBean.getBankOrgCode());
        item.addProperty("accnbr", cardInfoBean.getBankAccount());
        item.addProperty("autacc", cardInfoBean.getAuthBankAccount());
        array.add(item);
        Map<String, Object> result = doResult(this.doRequestWithParams(putParams("ntlkacvdx1", array, CMC_QUERY_PROTOCOL), CMC_QUERY_PROTOCOL), "ntlkacvdz1");
        log.info("【联动代发账号已签约代发协议列表查询 结束】");
        return result;
    }

    /**
     * 组装
     *
     * @return
     */
    public JsonObject putParams(String bodyName, JsonArray array, String method) {

        JsonObject head = new JsonObject();
        head.addProperty("funcode", method);
        head.addProperty("userid", userId);
        head.addProperty("reqid", DCHelper.getTime() + "0000001");

        JsonObject obj = new JsonObject();
        JsonObject req = new JsonObject();
        JsonObject body = new JsonObject();

        body.add(bodyName, array);
        req.add("head", head);
        req.add("body", body);
        obj.add("request", req);
        return obj;
    }

    /**
     * 组装请求码值
     */
    public Map<String, Object> doResult(Map<String, Object> response, String bodyName) {
        Map<String, Object> result = new HashMap<>();
        JSONObject respHead = JSONObject.parseObject(response.get("head").toString());
        if (respHead != null && respHead.get("resultcode").equals("SUC0000")) {
            Map<String, Map<String, Object>> respBody = (Map<String, Map<String, Object>>) response.get("body");
            result.put("code", "200");
            result.put("data", respBody.get(bodyName));
        } else {
            result.put("code", "201");
        }
        // log.info(bodyName + ":"+ result);
        return result;
    }


    /**
     * 代发经办 BB6BTHHL
     */
    public Map<String, Object> insteadIssue(PayItem payItem, List<ReceivedItem> receivedItems, String summaryNumber) throws Exception {
        String busmod = putSecretKey(summaryNumber);
        log.info("【代发经办开始...】");
        JsonObject obj = new JsonObject();
        JsonObject req = new JsonObject();
        JsonObject body = new JsonObject();
        JsonObject head = new JsonObject();
        head.addProperty("funcode", CMC_DAIFA);
        head.addProperty("userid", userId);
        head.addProperty("reqid", DCHelper.getTime() + "0000001");

        //经办业务列表
        JsonArray bmdArray = new JsonArray();
        JsonObject item = new JsonObject();
        item.addProperty("buscod", "N39010");
        item.addProperty("busmod", busmod);
        bmdArray.add(item);

        JsonArray payArray = new JsonArray();
        JsonObject payItemJson = new JsonObject();
        Map<String, Object> payItemMap = CommonUtils.objectToMap(payItem);
        for (Map.Entry<String, Object> entry : payItemMap.entrySet()) {
            if (entry.getValue() != null) {
                payItemJson.addProperty(entry.getKey(), entry.getValue().toString());
            }
        }
        payArray.add(payItemJson);

        JsonArray recArray = new JsonArray();
        for (ReceivedItem receive : receivedItems) {
            JsonObject recItem = new JsonObject();
            Map<String, Object> receiveMap = CommonUtils.objectToMap(receive);
            for (Map.Entry<String, Object> entry : receiveMap.entrySet()) {
                if (entry.getValue() != null) {
                    recItem.addProperty(entry.getKey(), entry.getValue().toString());
                }
            }
            recArray.add(recItem);
        }

        body.add("ntbusmody", bmdArray);
        body.add("ntlkaopdx1", payArray);
        body.add("ntlkaopdx2", recArray);
        req.add("head", head);
        req.add("body", body);
        obj.add("request", req);

        Map<String, Object> result = doResult(this.doRequestWithParams(obj, CMC_DAIFA), "ntlkaopdz1");
        log.info("【代发经办结束...】");
        return result;

    }


    /**
     * 10.联动代发明细查询NTLKATLD
     *
     * @return
     * @throws Exception
     */
    public Map<String, Object> insteadResult(String reqnbr, String summaryNumber) throws Exception {
        putSecretKey(summaryNumber);
        log.info("【联动代发明细查询 开始】");
        JsonArray array = new JsonArray();
        JsonObject item = new JsonObject();
        item.addProperty("reqnbr", reqnbr);
        array.add(item);
        Map<String, Object> result = doResult(this.doRequestWithParams(putParams("ntlkatldy1", array, CMC_TRANSFER_RESULT), CMC_TRANSFER_RESULT), "ntlkatldz1");
        log.info("【联动代发明细查询 结束】");
        return result;
    }

    /**
     * 联动代发业务查询 NTLKAQRD
     *
     * @return
     * @throws Exception
     */
    public Map<String, Object> instead9(String beginDate, String endDate, String summaryNumber) throws Exception {
        putSecretKey(summaryNumber);
        log.info("【联动代发业务查询 开始】");
        JsonArray array = new JsonArray();
        JsonObject item = new JsonObject();
        item.addProperty("datflg", "A");
        item.addProperty("begdat", beginDate);
        item.addProperty("enddat", endDate);
        array.add(item);
        Map<String, Object> result = doResult(this.doRequestWithParams(putParams("ntlkaqrdy1", array, CMC_DAIFA_SEL), CMC_DAIFA_SEL), "ntlkaqrdz1");
        log.info("【联动代发业务查询 结束】");
        return result;
    }

    //根据不同公司选择秘钥
    public String putSecretKey(String summaryNumber) {
        SettleDailySecretKey secretKey = settleDailySecretKeyService.lambdaQuery()
                .eq(SettleDailySecretKey::getSummaryNumber, summaryNumber)
                .one();
        publicKey = secretKey.getPublicKey();
        privateKey = secretKey.getPrivateKey();
        sm4key = secretKey.getSm4Key();
        userId = secretKey.getUid();
        return secretKey.getBusMod();
    }

}
