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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.jeequan.jeepay.core.entity.MchApplyment;
import com.jeequan.jeepay.core.entity.MchInfo;
import com.jeequan.jeepay.core.entity.MchSubInfo;
import com.jeequan.jeepay.core.interfaces.paychannel.IIsvmchWxConfigService;
import com.jeequan.jeepay.core.model.applyment.ApplymentSignInfo;
import com.jeequan.jeepay.core.model.applyment.PaywayFee;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.model.params.dgpay.DgpayIsvParams;
import com.jeequan.jeepay.core.model.rqrs.msg.ChannelRetMsg;
import com.jeequan.jeepay.core.utils.DateKit;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.db.entity.MchSubInfoEntity;
import com.jeequan.jeepay.service.impl.MchSubInfoService;
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.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class DgpayIsvmchWxConfigService implements IIsvmchWxConfigService {

    @Autowired
    protected SysConfigService sysConfigService;

    @Autowired
    private MchSubInfoService mchSubInfoService;

    @Override
    public ChannelRetMsg configPayBaseUrl(String configBaseUrl, String isvNo, String mchNo, String mchAppId, String ifCode) {
        return null;
    }

    @Override
    public ChannelRetMsg applyModifyMchRate(List<PaywayFee> paywayFeeList, String isvNo, String mchNo, String mchAppId, String ifCode) {
        return null;
    }

    @Override
    public String queryConfiguredInfo(String isvNo, String mchNo, String mchAppId, String ifCode) {
        return null;
    }

    @Override
    public ChannelRetMsg configBindAppId(String configAppId, String isvNo, String mchNo, String mchAppId, String ifCode) {
        return null;
    }

    @Override
    public ChannelRetMsg configSubscribeAppId(String configAppId, String isvNo, String mchNo, String mchAppId, String ifCode) {
        return ChannelRetMsg.confirmSuccess(null);
    }

    @Override
    public ChannelRetMsg applyModifyMchShortName(String mchShortName, String isvNo, String mchNo, String mchAppId, String ifCode) {
        return ChannelRetMsg.confirmSuccess(null);
    }

    @Override
    public ChannelRetMsg applyModifyMchAppPublicKey(String appPublicKey, String isvNo, String mchNo, String mchAppId, String ifCode) {
        return ChannelRetMsg.confirmSuccess(null);
    }

    @Override
    public ApplymentSignInfo wxOpenSignInfo(MchApplyment mchApplyment) {

        ApplymentSignInfo result = new ApplymentSignInfo();

        JSONObject suJson = JSON.parseObject(mchApplyment.getSuccResParameter());
        MchAppConfigContext mchAppConfigContext = new MchAppConfigContext();
        mchAppConfigContext.setMchType(MchInfo.TYPE_ISVSUB);
        mchAppConfigContext.setMchApplyment(mchApplyment);
        // 服务商配置参数
        ConfigContextQueryService configContextQueryService = SpringBeansUtil.getBean(ConfigContextQueryService.class);
        DgpayIsvParams isvParams = (DgpayIsvParams) configContextQueryService.queryIsvParams(mchApplyment.getIsvNo(), mchApplyment.getIfCode());

        if (suJson == null || StringUtils.isEmpty(suJson.getString("huifuId"))) {
            result.setState("查询失败");
            result.setErrInfo("商户参数为空，该商户还未进件成功");
            return result;
        }

        // 微信开通意愿二维码地址
        result.setSignUrl(isvParams.getWxOpenUrl());
        result.setImgType(ApplymentSignInfo.IMG_TYPE_QRCONTENT);
        // 请求参数
        JSONObject reqParams = new JSONObject();
        // 汇付ID
        reqParams.put("huifu_id", suJson.getString("huifuId"));
        // 请求日期
        reqParams.put("req_date", DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN));
        // 请求流水号
        reqParams.put("req_seq_id", DateKit.currentTimeMillis() + "");

        // 发送请求
        JSONObject response = DgPayKit.request(mchAppConfigContext, reqParams, "/merchant/busi/realname/query", mchApplyment.getIfCode());

        // 请求流水号
        reqParams.put("req_seq_id", DateKit.currentTimeMillis() + "_info");
        // 商户详情is_open_small_flag -> 0
        JSONObject mchInfoData = DgPayKit.request(mchAppConfigContext, reqParams, "/merchant/basicdata/query", mchApplyment.getIfCode()).getJSONObject("data");

        String respCode = mchInfoData.getString("resp_code");
        String respDesc = mchInfoData.getString("resp_desc");

        if (!respCode.equals("00000000")) {
            result.setState("获取子商户状态异常");
            result.setErrInfo("【" + respDesc + "】");
            result.setImgType("qrContent");
            result.setSignUrl(isvParams.getAliChannelExtUrl());
            return result;
        }

        String feeConfig = "";
        JSONArray wxConfList = mchInfoData.getJSONArray("qry_wx_conf_list");
        JSONArray aliConfList = mchInfoData.getJSONArray("qry_ali_conf_list");
        JSONObject unionConf = mchInfoData.getJSONObject("qry_union_conf");
        JSONObject bankCardConf = mchInfoData.getJSONObject("qry_bank_card_conf");
        log.info("【商户信息】微信配置：{}, 支付宝配置：{}, 银联配置：{}, 银行卡配置：{}", wxConfList, aliConfList, unionConf, bankCardConf);

        if (!CollUtil.isEmpty(wxConfList)) {
            feeConfig = "【微信费率配置成功】";
        }
        if (!CollUtil.isEmpty(aliConfList)) {
            feeConfig = feeConfig + "【支付宝费率配置成功】";
        }
        if (!CollUtil.isEmpty(unionConf)) {
            feeConfig = feeConfig + "【银联费率配置成功】";
        }
        if (!CollUtil.isEmpty(bankCardConf)) {
            feeConfig = feeConfig + "【银行卡支付配置成功】";
        }

        for (int wxIndex = 0; wxIndex < wxConfList.size(); wxIndex++) {
            JSONArray aliMerInfos = wxConfList.getJSONObject(wxIndex).getJSONArray("wx_mer_infos");

            if (!CollUtil.isEmpty(aliMerInfos)) {

                for (int i = 0; i < aliMerInfos.size(); i++) {
                    JSONObject item = aliMerInfos.getJSONObject(i);
                    // 支付宝子商户号存在时
                    MchSubInfoEntity wxSubInfo = new MchSubInfoEntity();
                    wxSubInfo.setMchApplyId(mchApplyment.getApplyId());

                    String payChannelId = item.getString("pay_channel_id");
                    String bankMerCode = item.getString("bank_mer_code");
                    if (Objects.equals(isvParams.getChannelNo(), payChannelId)) {
                        wxSubInfo.setMainUse(1);
                        result.setChannelSubMchId(bankMerCode);
                    } else {
                        wxSubInfo.setMainUse(0);
                    }
                    wxSubInfo.setSubMchWay("DG");
                    wxSubInfo.setChannelMchNo(mchApplyment.getChannelMchNo());
                    wxSubInfo.setChannelId(payChannelId);
                    wxSubInfo.setAuthStatus(MchSubInfo.AUTH_STATUS_UNAUTHORIZED);
                    wxSubInfo.setSubMchId(bankMerCode);
                    wxSubInfo.setSubMchType("WX");
                    // 此处取1为正常
                    wxSubInfo.setStatus("1");
                    wxSubInfo.setExt(item);

                    try {
                        mchSubInfoService.save(wxSubInfo);
                    } catch (DuplicateKeyException e) {
                        log.info("子商户信息已存储过");
                    }
                }
            }
        }

        result.setOriginData(feeConfig);

        JSONObject resData = response.getJSONObject("data");
        String code = resData.getString("resp_code");
        // 驳回原因
        String rejectMsg = resData.getString("reject_reason");

        // 请求异常
        if (!DgPayKit.STATE_SUCCESS.equals(code)) {
            result.setErrInfo(resData.getString("resp_desc"));
            return result;
        }

        // 申请单状态
        String applymentStat = resData.getString("applyment_stat");
        // 授权状态
        String authorizeStat = resData.getString("authorize_stat");

//        // 小程序码
//        result.setSignUrl(resData.getString("qrcode_data"));

        LambdaUpdateChainWrapper<MchSubInfoEntity> stateUpdate = mchSubInfoService.lambdaUpdate()
                .eq(MchSubInfoEntity::getMchApplyId, mchApplyment.getApplyId())
                .eq(MchSubInfoEntity::getMainUse, 1)
                .eq(MchSubInfoEntity::getSubMchType, "WX");
        // 覆写状态
        if (StringUtils.isNotEmpty(authorizeStat)) {
            if ("0".equals(authorizeStat)) {
                stateUpdate.set(MchSubInfoEntity::getAuthStatus, MchSubInfo.AUTH_STATUS_UNAUTHORIZED).update();
                result.setState("未授权");
            } else if ("1".equals(authorizeStat)) {
                result.setState("已授权"); // 覆写状态 ， 其他不考虑
                stateUpdate.set(MchSubInfoEntity::getAuthStatus, MchSubInfo.AUTH_STATUS_AUTHORIZED).update();
            }
        }

        return result;
    }

}
