package com.hfkj.channel.lakala;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.channel.lakala.config.LaKaLaConfig;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.utils.GenerateUtil;
import com.hfkj.common.utils.HttpsUtils;
import com.hfkj.config.CommonSysConst;
import com.hfkj.entity.BsMer;
import com.hfkj.entity.BsMerLedger;
import com.hfkj.entity.BsMerPlatformNo;
import com.hfkj.entity.SecDictionary;
import com.hfkj.service.BsMerLedgerService;
import com.hfkj.service.BsMerPlatformNoService;
import com.hfkj.service.BsMerService;
import com.hfkj.service.CommonService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 拉卡拉钱包
 * @author hurui
 */
@Service("laKaLaWalletService")
public class LaKaLaWalletService {

    @Resource
    private BsMerPlatformNoService merPlatformNoService;
    @Resource
    private BsMerLedgerService merLedgerService;
    @Resource
    private BsMerService merService;
    @Resource
    private CommonService commonService;

    /**
     * 商户开通主动结算业务
     * @param merCupNo
     * @return
     */
    public JSONObject activeSettleApply(String merCupNo) {
        // 查询平台商户号
        BsMerPlatformNo merPlatform = merPlatformNoService.getPlatformNoByCupNo(merCupNo);
        if (merPlatform == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到平台商户号");
        }
        // 商户平台
        BsMer mer = merService.getMer(merPlatform.getMerId());
        if (mer == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的商户");
        }
        SecDictionary org = commonService.mappingSysCode("ORG_NO", mer.getOrgNo());
        if (org == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的机构");
        }

        // 请求参数
        Map<String, Object> param = new HashMap<>();
        param.put("timestamp", new Date().getTime());
        param.put("rnd", GenerateUtil.generateRandomString(18));
        param.put("ver", "1.0.0");
        param.put("reqId", new Date().getTime());

        Map<String, Object> map = new HashMap<>();
        map.put("version", "1.0");
        map.put("orderNo", System.currentTimeMillis()+"");
        map.put("orgCode", org.getExt1());
        map.put("merCupNo", merCupNo);
        param.put("reqData", map);

        // 生成签名
        Map<String, Object> reqParam = LaKaLaConfig.generateSignParamsV2(JSONObject.parseObject(JSONObject.toJSONString(param)));

        // 头部参数
        Map<String, Object> heard = new HashMap<>();
        heard.put("Authorization", reqParam.get("Authorization"));

        JSONObject responseBody = HttpsUtils.doPost(CommonSysConst.getSysConfig().getLkl_request_url() + "/api/v2/mms/openApi/activeSettle/apply", param, heard);
        System.out.println("Authorization" + JSONObject.toJSONString(reqParam.get("Authorization")));
        System.out.println("request：" + JSONObject.toJSONString(param));
        System.out.println("response：" + responseBody.toJSONString());
        if (!responseBody.getString("retCode").equals("000000")) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, responseBody.getString("retMsg"));
        }
        return responseBody.getJSONObject("respData");
    }

    /**
     * 账管家提现D1
     * @param merCupNo
     * @return
     */
    public JSONObject ewalletWithdrawD1(String merCupNo, BigDecimal drawAmt, String remark) {
        // 查询平台商户号
        BsMerPlatformNo merPlatform = merPlatformNoService.getPlatformNoByCupNo(merCupNo);
        if (merPlatform == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到平台商户号");
        }
        // 商户平台
        BsMer mer = merService.getMer(merPlatform.getMerId());
        if (mer == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的商户");
        }
        SecDictionary org = commonService.mappingSysCode("ORG_NO", mer.getOrgNo());
        if (org == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的机构");
        }

        // 请求参数
        Map<String, Object> param = new HashMap<>();
        param.put("timestamp", new Date().getTime());
        param.put("rnd", GenerateUtil.generateRandomString(18));
        param.put("ver", "1.0.0");
        param.put("reqId", new Date().getTime());

        Map<String, Object> map = new HashMap<>();
        map.put("orgNo", org.getExt1());
        map.put("merchantNo", merCupNo);
        map.put("drawAmt", drawAmt);
        map.put("notifyUrl", "");
        map.put("remark", remark);
        param.put("reqData", map);

        // 生成签名
        Map<String, Object> reqParam = LaKaLaConfig.generateSignParamsV2(JSONObject.parseObject(JSONObject.toJSONString(param)));

        // 头部参数
        Map<String, Object> heard = new HashMap<>();
        heard.put("Authorization", reqParam.get("Authorization"));

        JSONObject responseBody = HttpsUtils.doPost(CommonSysConst.getSysConfig().getLkl_request_url() + "/api/v2/laep/industry/ewalletWithdrawD1", param, heard);
        System.out.println("Authorization" + JSONObject.toJSONString(reqParam.get("Authorization")));
        System.out.println("request：" + JSONObject.toJSONString(param));
        System.out.println("response：" + responseBody.toJSONString());
        if (!responseBody.getString("retCode").equals("000000")) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, responseBody.getString("retMsg"));
        }
        return responseBody.getJSONObject("respData");
    }

    /**
     * 账管家余额查询
     * @param merCupNo 	商户号
     * @param payNo     账号
     * @param payType  账号类型（01：收款账户，02：付款账户，03：分账商户账户，04：分账接收方账户，05：充值代付账户，06：结算代付账户）- 未上送则默认为01
     * @return
     */
    public JSONObject ewalletBalanceQuery(String merCupNo, String payNo, String payType) {
        // 查询平台商户号
        BsMerPlatformNo merPlatform = merPlatformNoService.getPlatformNoByCupNo(merCupNo);
        if (merPlatform == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到平台商户号");
        }
        // 商户平台
        BsMer mer = merService.getMer(merPlatform.getMerId());
        if (mer == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的商户");
        }
        SecDictionary org = commonService.mappingSysCode("ORG_NO", mer.getOrgNo());
        if (org == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的机构");
        }

        // 请求参数
        Map<String, Object> param = new HashMap<>();
        param.put("timestamp", new Date().getTime());
        param.put("rnd", GenerateUtil.generateRandomString(18));
        param.put("ver", "1.0.0");
        param.put("reqId", new Date().getTime());

        Map<String, Object> map = new HashMap<>();
        map.put("orgNo", org.getExt1());
        map.put("merchantNo", merCupNo);
        map.put("payNo", payNo);
        map.put("payType", payType);
        param.put("reqData", map);

        // 生成签名
        Map<String, Object> reqParam = LaKaLaConfig.generateSignParamsV2(JSONObject.parseObject(JSONObject.toJSONString(param)));

        // 头部参数
        Map<String, Object> heard = new HashMap<>();
        heard.put("Authorization", reqParam.get("Authorization"));

        JSONObject responseBody = HttpsUtils.doPost(CommonSysConst.getSysConfig().getLkl_request_url() + "/api/v2/laep/industry/ewalletBalanceQuery", param, heard);
        System.out.println("Authorization" + JSONObject.toJSONString(reqParam.get("Authorization")));
        System.out.println("request：" + JSONObject.toJSONString(param));
        System.out.println("response：" + responseBody.toJSONString());
        if (!responseBody.getString("retCode").equals("000000")) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, responseBody.getString("retMsg"));
        }
        return responseBody.getJSONObject("respData");
    }

    /**
     * 账管家提现结果查询
     * @param merCupNo
     * @return
     */
    public JSONObject ewalletWithdrawQuery(String merCupNo,String drawJnl) {
        // 查询平台商户号
        BsMerPlatformNo merPlatform = merPlatformNoService.getPlatformNoByCupNo(merCupNo);
        if (merPlatform == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到平台商户号");
        }
        // 商户平台
        BsMer mer = merService.getMer(merPlatform.getMerId());
        if (mer == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的商户");
        }
        SecDictionary org = commonService.mappingSysCode("ORG_NO", mer.getOrgNo());
        if (org == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的机构");
        }

        // 请求参数
        Map<String, Object> param = new HashMap<>();
        param.put("timestamp", new Date().getTime());
        param.put("rnd", GenerateUtil.generateRandomString(18));
        param.put("ver", "1.0.0");
        param.put("reqId", new Date().getTime());

        Map<String, Object> map = new HashMap<>();
        map.put("orgNo", org.getExt1());
        map.put("merchantNo", merCupNo);
        map.put("drawJnl", drawJnl);
        param.put("reqData", map);

        // 生成签名
        Map<String, Object> reqParam = LaKaLaConfig.generateSignParamsV2(JSONObject.parseObject(JSONObject.toJSONString(param)));

        // 头部参数
        Map<String, Object> heard = new HashMap<>();
        heard.put("Authorization", reqParam.get("Authorization"));

        JSONObject responseBody = HttpsUtils.doPost(CommonSysConst.getSysConfig().getLkl_request_url() + "/api/v2/laep/industry/ewalletWithdrawQuery", param, heard);
        System.out.println("Authorization" + JSONObject.toJSONString(reqParam.get("Authorization")));
        System.out.println("request：" + JSONObject.toJSONString(param));
        System.out.println("response：" + responseBody.toJSONString());
        if (!responseBody.getString("retCode").equals("000000")) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, responseBody.getString("retMsg"));
        }
        return responseBody.getJSONObject("respData");
    }

    /**
     * 账管家提款模式设置
     * @param merCupType     商户号类型  1：商户号  2：分账接收方账户
     * @param merCupNo      商户号
     * @param settleType   	提款模式（01主动提款 02自动结算）
     * @param settleTime    结算时间（小时）- 默认值：06。如08:00-09:00到账，则传入08
     * @param notifyUrl     通知地址
     * @return
     */
    public JSONObject ewalletSettleProfile(Integer merCupType,String merCupNo, String settleType, String settleTime,String notifyUrl) {
        BsMer mer = null;

        if (merCupType.equals(1)) {
            // 查询平台商户号
            BsMerPlatformNo merPlatform = merPlatformNoService.getPlatformNoByCupNo(merCupNo);
            if (merPlatform == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到平台商户号");
            }
            // 商户平台
            mer = merService.getMer(merPlatform.getMerId());

        } else if (merCupType.equals(2)) {
            // 查询分账信息
            BsMerLedger merLedger = merLedgerService.getMerLedgerByReceiverNo(merCupNo);
            if (merLedger == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到商户分账信息");
            }
            // 商户平台
            mer = merService.getMer(merLedger.getMerId());
        }
        if (mer == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的商户");
        }
        SecDictionary org = commonService.mappingSysCode("ORG_NO", mer.getOrgNo());
        if (org == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的机构");
        }

        // 请求参数
        Map<String, Object> param = new HashMap<>();
        param.put("timestamp", new Date().getTime());
        param.put("rnd", GenerateUtil.generateRandomString(18));
        param.put("ver", "1.0.0");
        param.put("reqId", new Date().getTime());

        Map<String, Object> map = new HashMap<>();
        map.put("bmcpNo", org.getExt1());
        map.put("mercId", merCupNo);
        map.put("settleType", settleType);
        map.put("settleTime", settleTime);
        map.put("notifyUrl", notifyUrl);
        param.put("reqData", map);

        // 生成签名
        Map<String, Object> reqParam = LaKaLaConfig.generateSignParamsV2(JSONObject.parseObject(JSONObject.toJSONString(param)));

        // 头部参数
        Map<String, Object> heard = new HashMap<>();
        heard.put("Authorization", reqParam.get("Authorization"));

        JSONObject responseBody = HttpsUtils.doPost(CommonSysConst.getSysConfig().getLkl_request_url() + "/api/v2/laep/industry/ewallet/settleProfile", param, heard);
        System.out.println("Authorization" + JSONObject.toJSONString(reqParam.get("Authorization")));
        System.out.println("request：" + JSONObject.toJSONString(param));
        System.out.println("response：" + responseBody.toJSONString());
        if (!responseBody.getString("retCode").equals("000000")) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, responseBody.getString("retMsg"));
        }
        return responseBody.getJSONObject("respData");
    }

    /**
     * 账管家提款模式查询
     * @param merCupNo      商户号
     * @return
     */
    public JSONObject ewalletSettleQuery(String merCupNo) {
        // 查询平台商户号
        BsMerPlatformNo merPlatform = merPlatformNoService.getPlatformNoByCupNo(merCupNo);
        if (merPlatform == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到平台商户号");
        }
        // 商户平台
        BsMer mer = merService.getMer(merPlatform.getMerId());
        if (mer == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的商户");
        }
        SecDictionary org = commonService.mappingSysCode("ORG_NO", mer.getOrgNo());
        if (org == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的机构");
        }
        // 请求参数
        Map<String, Object> param = new HashMap<>();
        param.put("timestamp", new Date().getTime());
        param.put("rnd", GenerateUtil.generateRandomString(18));
        param.put("ver", "1.0.0");
        param.put("reqId", new Date().getTime());

        Map<String, Object> map = new HashMap<>();
        map.put("bmcpNo", org.getExt1());
        map.put("mercId", merCupNo);
        param.put("reqData", map);

        // 生成签名
        Map<String, Object> reqParam = LaKaLaConfig.generateSignParamsV2(JSONObject.parseObject(JSONObject.toJSONString(param)));

        // 头部参数
        Map<String, Object> heard = new HashMap<>();
        heard.put("Authorization", reqParam.get("Authorization"));

        JSONObject responseBody = HttpsUtils.doPost(CommonSysConst.getSysConfig().getLkl_request_url() + "/api/v2/laep/industry/ewallet/settleQuery", param, heard);
        System.out.println("Authorization" + JSONObject.toJSONString(reqParam.get("Authorization")));
        System.out.println("request：" + JSONObject.toJSONString(param));
        System.out.println("response：" + responseBody.toJSONString());
        if (!responseBody.getString("retCode").equals("000000")) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, responseBody.getString("retMsg"));
        }
        return responseBody.getJSONObject("respData");
    }

}
