package com.jeequan.jeepay.thirdparty.channel.dgpay;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.entity.MchApplyment;
import com.jeequan.jeepay.core.entity.MchInfo;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.interfaces.paychannel.IDgApplymentApiService;
import com.jeequan.jeepay.core.model.applyment.DgpayApplymentInfo;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.params.dgpay.DgpayIsvParams;
import com.jeequan.jeepay.core.model.params.dgpay.DgpayIsvsubMchParams;
import com.jeequan.jeepay.core.utils.DateKit;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.service.impl.RateConfigService;
import com.jeequan.jeepay.service.impl.SysConfigService;
import com.jeequan.jeepay.thirdparty.service.ConfigContextQueryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 斗拱 接口
 *
 * @author xiaoyu
 *
 * @date 2022/6/9 9:25
 */
@Service
@Slf4j
public class DgpayApplymentApiService implements IDgApplymentApiService {

    @Autowired
    protected SysConfigService sysConfigService;
    @Autowired
    protected RateConfigService rateConfigService;

    @Override
    public MchApplyment dgpayConfigOpen(MchApplyment mchApplyment, JSONObject paramJSON) {
        String logPrefix = "【斗拱商户分账配置】";
        MchApplyment result = new MchApplyment();
        try {
            MchAppConfigContext mchAppConfigContext = new MchAppConfigContext();
            mchAppConfigContext.setMchType(MchInfo.TYPE_ISVSUB)
                    .setMchApplyment(mchApplyment);
            JSONObject succResJson = JSON.parseObject(mchApplyment.getSuccResParameter());
            if (succResJson == null || StringUtils.isEmpty(succResJson.getString("huifuId"))) {
                result.setApplyErrorInfo("无汇付商户号（huifu_id），请确认是否进件成功");
                return result;
            }

            // 最大分账比例
            String applyRatio = paramJSON.getString("applyRatio");
            if (StringUtils.isEmpty(applyRatio)) {
                result.setApplyErrorInfo("请填写最大分账比例");
                return result;
            }

            // 进件商户号
            String huifuId = succResJson.getString("huifuId");

            JSONObject reqParams = new JSONObject();
            // 汇付ID
            reqParams.put("huifu_id", huifuId);
            // 请求日期
            reqParams.put("req_date", DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN));
            // 请求流水号
            reqParams.put("req_seq_id", DateKit.currentTimeMillis() + "");
            // 分账规则来源 01-接口发起 02-控台配置
            reqParams.put("rule_origin", "01");
            // 分账是否支持撤销交易
            reqParams.put("repeal_flag", "Y");
            // 分账是否支持退货交易
            reqParams.put("refund_flag", "Y");
            // 分账开关
            reqParams.put("div_flag", "Y");

            // 最大分账比例 未填写分账比例不请求开通分账
            reqParams.put("apply_ratio", applyRatio);
            // 生效类型
            reqParams.put("start_type", "0");

            // 发送请求
            JSONObject response = DgPayKit.request(mchAppConfigContext, reqParams, "/merchant/split/config", mchApplyment.getIfCode());
            JSONObject resData = response.getJSONObject("data");
            log.info("{} 响应结果：resData={}", logPrefix, resData);

            if (!"00000000".equals(resData.getString("resp_code"))) {
                result.setApplyErrorInfo(resData.getString("resp_desc"));
            }

            result.setChannelVar1(paramJSON.toJSONString());

        } catch (BizException e) {
            result.setApplyErrorInfo("[" + e.getMessage() + "]");
            log.error("{} 操作失败：", logPrefix, e);
        } catch (Exception e) {
            result.setApplyErrorInfo("[" + e.getMessage() + "]");
            log.error("{} 操作失败：", logPrefix, e);
        }
        return result;
    }

    @Override
    public MchApplyment dgpayConfigOpenQuery(MchApplyment mchApplyment) {
        String logPrefix = "【斗拱商户分账配置查询】";
        MchApplyment result = new MchApplyment();
        try {
            MchAppConfigContext mchAppConfigContext = new MchAppConfigContext();
            mchAppConfigContext.setMchType(MchInfo.TYPE_ISVSUB);
            mchAppConfigContext.setMchApplyment(mchApplyment);
            JSONObject succResJson = JSON.parseObject(mchApplyment.getSuccResParameter());
            if (succResJson == null || StringUtils.isEmpty(succResJson.getString("huifuId"))) {
                result.setApplyErrorInfo("无汇付商户号（huifu_id），请确认是否进件成功");
                return result;
            }

            // 进件商户号
            String huifuId = succResJson.getString("huifuId");

            JSONObject reqParams = new JSONObject();
            // 汇付ID
            reqParams.put("huifu_id", huifuId);
            // 请求日期
            reqParams.put("req_date", DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN));
            // 请求流水号
            reqParams.put("req_seq_id", DateKit.currentTimeMillis() + "_" + huifuId);

            // 发送请求
            JSONObject response = DgPayKit.request(mchAppConfigContext, reqParams, "/merchant/split/query", mchApplyment.getIfCode());
            JSONObject resData = response.getJSONObject("data");
            log.info("{} 响应结果：resData={}", logPrefix, resData);

            result.setChannelVar2(resData.toJSONString());

        } catch (BizException e) {
            result.setApplyErrorInfo("[" + e.getMessage() + "]");
            log.error("{} 操作失败：", logPrefix, e);
        } catch (Exception e) {
            result.setApplyErrorInfo("[" + e.getMessage() + "]");
            log.error("{} 操作失败：", logPrefix, e);
        }
        return result;
    }

    @Override
    public MchApplyment wechatConfigSet(String isvNo, String mchNo, String appId, String jsapiPath, String feeType, String configWxBindLiteAppId, String configWxBindAppId, String bankChannelNo, String ifCode) {
        String logPrefix = "【斗拱商户微信配置】";
        MchApplyment result = new MchApplyment();
        try {

            ConfigContextQueryService configContextQueryService = SpringBeansUtil.getBean(ConfigContextQueryService.class);
            // 获取支付参数
            DgpayIsvParams isvParams = (DgpayIsvParams) configContextQueryService.queryIsvParams(isvNo, ifCode);
            MchAppConfigContext mchAppConfigContext = new MchAppConfigContext();
            mchAppConfigContext.setMchType(MchInfo.TYPE_ISVSUB).setMchApplyment(new MchApplyment().setIsvNo(isvNo));

            DgpayIsvsubMchParams mchParams = (DgpayIsvsubMchParams) configContextQueryService.queryIsvsubMchParams(mchNo, appId, ifCode);

            if (mchParams == null || StringUtils.isEmpty(mchParams.getHuifuId())) {
                result.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
                result.setApplyErrorInfo("商户参数未配置，请先配置商户应用参数");
                return result;
            }

            // 进件商户号
            String huifuId = mchParams.getHuifuId();

            // 请求参数
            JSONObject reqParams = new JSONObject();
            // 汇付ID
            reqParams.put("huifu_id", huifuId);
            // 产品编号
            reqParams.put("product_id", isvParams.getProductId());
            // 请求日期
            reqParams.put("req_date", DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN));
            // 请求流水号
            reqParams.put("req_seq_id", DateKit.currentTimeMillis() + "");

            // 业务开通类型
            reqParams.put("fee_type", feeType);
            // 授权目录
            reqParams.put("wx_woa_path", jsapiPath);
            // 微信小程序APPID
            reqParams.put("wx_applet_app_id", configWxBindLiteAppId);
            // 公众号APPID
            reqParams.put("wx_woa_app_id", configWxBindAppId);
            if (StringUtils.isNotEmpty(bankChannelNo)) {
                // 渠道号
                reqParams.put("bank_channel_no", bankChannelNo);
            }

            // 发送请求
            JSONObject response = DgPayKit.request(mchAppConfigContext, reqParams, DgPayKit.MCH_BUSI_CONFIG_URL, ifCode);
            JSONObject resData = response.getJSONObject("data");
            String code = resData.getString("resp_code");
            if (DgPayKit.STATE_SUCCESS.equals(code)) {
                result.setState(MchApplyment.STATE_SUCCESS);
            } else {
                result.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
                result.setApplyErrorInfo(code + "[" + resData.getString("resp_desc") + "]");
                log.error("{} 请求失败：code={}, msg={}", logPrefix, code, resData.getString("resp_desc"));
                return result;
            }
        } catch (Exception e) {
            result.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
            result.setApplyErrorInfo("[" + e.getMessage() + "]");
            log.error("{} 配置异常：", logPrefix, e);
        }
        return result;
    }

    @Override
    public MchApplyment wechatRealName(MchApplyment mchApplyment) {
        String logPrefix = "【斗拱商户微信实名认证】";
        MchApplyment result = new MchApplyment();
        try {
            // 获取支付参数
            MchAppConfigContext mchAppConfigContext = new MchAppConfigContext();
            mchAppConfigContext.setMchType(MchInfo.TYPE_ISVSUB);
            mchAppConfigContext.setMchApplyment(mchApplyment);
            JSONObject succResJson = JSON.parseObject(mchApplyment.getSuccResParameter());
            if (succResJson == null || StringUtils.isEmpty(succResJson.getString("huifuId"))) {
                result.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
                result.setApplyErrorInfo("商户参数未配置，请先配置商户应用参数");
                return result;
            }
            // 进件商户号
            String huifuId = succResJson.getString("huifuId");

            // 获取详细参数
            DgpayApplymentInfo info = JSON.parseObject(mchApplyment.getApplyDetailInfo(), DgpayApplymentInfo.class);

            // 请求参数
            JSONObject reqParams = new JSONObject();
            // 汇付ID
            reqParams.put("huifu_id", huifuId);
            // 请求日期
            reqParams.put("req_date", DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN));
            // 请求流水号
            reqParams.put("req_seq_id", DateKit.currentTimeMillis() + "");

            // 联系人姓名
            reqParams.put("name", info.getIdcardName());
            // 联系人手机号
            reqParams.put("mobile", info.getContactPhone());
            // 联系人身份证号
            reqParams.put("id_card_number", info.getIdcardNo());

            // 法人身份证人像面照片
            reqParams.put("identification_front_copy", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F02", info.getIdcard1Img(), mchApplyment.getIfCode()));
            // 法人身份证国徽面照片
            reqParams.put("identification_back_copy", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F03", info.getIdcard2Img(), mchApplyment.getIfCode()));

            // 证书类型 【营业执照】
            reqParams.put("cert_type", "CERTIFICATE_TYPE_2392");
            // 证书编号
            reqParams.put("cert_number", info.getLicenseNo());
            // 证书照片
            reqParams.put("cert_copy", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F07", info.getLicenseImg(), mchApplyment.getIfCode()));
            // 小微经营类型
            reqParams.put("micro_biz_type", info.getMicroBizType());
            // 门店名称
            reqParams.put("store_name", info.getMchShortName());
            // 门店门头照
            reqParams.put("store_header_copy", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F49", info.getStoreOuterImg(), mchApplyment.getIfCode()));
            // 门店环境照
            reqParams.put("store_indoor_copy", DgPayKit.uploadFile(mchApplyment.getIsvNo(), "F50", info.getStoreInnerImg(), mchApplyment.getIfCode()));
            // 门店省市编码
            reqParams.put("store_address_code", info.getAreaCode().get(1));
            // 门店地址
            reqParams.put("store_address", info.getMchShortName());
            // 发送请求
            JSONObject response = DgPayKit.request(mchAppConfigContext, reqParams, "/merchant/busi/realname", mchApplyment.getIfCode());
            JSONObject resData = response.getJSONObject("data");
            String code = resData.getString("resp_code");
            if (DgPayKit.STATE_SUCCESS.equals(code)) {
//                String channelOrderNo = resData.getString("applyment_id");
//                result.setChannelApplyNo(channelOrderNo);
                result.setState(MchApplyment.STATE_SUCCESS);
            } else {
                result.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
                result.setApplyErrorInfo(code + "[" + resData.getString("resp_desc") + "]");
                log.error("{} 请求失败：code={}, msg={}", logPrefix, code, resData.getString("resp_desc"));
                return result;
            }

        } catch (Exception e) {
            result.setState(MchApplyment.STATE_REJECT_WAIT_MODIFY);
            result.setApplyErrorInfo("[" + e.getMessage() + "]");
            log.error("{} 实名认证失败：", logPrefix, e);
        }
        return result;
    }

}
