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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.jeequan.jeepay.core.entity.MchApplyment;
import com.jeequan.jeepay.core.entity.MchSubInfo;
import com.jeequan.jeepay.core.interfaces.paychannel.IIsvmchAlipayConfigService;
import com.jeequan.jeepay.core.model.applyment.ApplymentSignInfo;
import com.jeequan.jeepay.core.model.params.sxfpay.SxfpayIsvParams;
import com.jeequan.jeepay.core.utils.JeepayKit;
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.thirdparty.channel.IsvFactory;
import com.jeequan.jeepay.thirdparty.channel.sxfpay.model.ReqMethod;
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;

@Service
@Slf4j
public class SxfpayIsvmchAlipayConfigService implements IIsvmchAlipayConfigService {

    @Autowired
    private MchSubInfoService mchSubInfoService;

    @Override
    public ApplymentSignInfo alipayOpenSignInfo(MchApplyment mchApplyment) {

        ApplymentSignInfo result = new ApplymentSignInfo();

        JSONObject suJson = JSON.parseObject(mchApplyment.getSuccResParameter());
        // 获取到 服务商配置信息
        ConfigContextQueryService configContextQueryService = SpringBeansUtil.getBean(ConfigContextQueryService.class);
        SxfpayIsvParams isvParams = (SxfpayIsvParams) configContextQueryService.queryIsvParams(mchApplyment);
        // 支付宝渠道拓展地址
        result.setSignUrl(isvParams.getAliUrl());
        // 图片类型
        result.setImgType(ApplymentSignInfo.IMG_TYPE_QRCONTENT);

        if (StringUtils.isEmpty(mchApplyment.getChannelMchNo())) {
            result.setErrInfo("随行付商户号为空");
            return result;
        }
        // 银盛商户号
        String mercId = suJson.getString("mercId");

        LambdaQueryChainWrapper<MchSubInfoEntity> zfbSubInfoQuery = mchSubInfoService.lambdaQuery()
                .eq(MchSubInfoEntity::getMchApplyId, mchApplyment.getApplyId())
                .eq(MchSubInfoEntity::getChannelMchNo, mchApplyment.getChannelMchNo())
                .eq(MchSubInfoEntity::getMainUse, 1)
                .eq(MchSubInfoEntity::getSubMchType, "ZFB");
        MchSubInfoEntity zfb = zfbSubInfoQuery.one();

        if (zfb == null) {
            IsvFactory.getIsvMchApplymentService(JeepayKit.getIfCodeOrigin(mchApplyment.getIfCode()))
                    .subMchColl(mchApplyment);

            zfb = zfbSubInfoQuery.one();
        }

        if (zfb == null) {
            result.setState("未报备");
            result.setErrInfo("[未获取到子商户信息]");
            return result;
        } else if ("01".equals(zfb.getStatus())) {
            result.setChannelSubMchId(zfb.getSubMchId());
        } else {
            result.setState("未报备");
            result.setErrInfo("[" + zfb.getRemark() + "]");
            return result;
        }

        // 请求参数
        JSONObject bizContent = new JSONObject();
        bizContent.put("subMchId", zfb.getSubMchId());

        // 发送请求
        JSONObject response = SxfpayKit.reqApi(ReqMethod.Method.ALI_CERT_STATUS, isvParams, bizContent);
        if (!"0000".equals(response.getString("bizCode"))) {
//            throw new BizException(response.getString("bizMsg"));

            result.setState("04");
            result.setErrInfo(response.getString("code") + "[" + response.getString("msg") + "]");

            return result;
        }

        // 解密后数据
        String authState = response.getString("checkResult");

        LambdaUpdateChainWrapper<MchSubInfoEntity> stateUpdate = mchSubInfoService.lambdaUpdate()
                .eq(MchSubInfoEntity::getMchApplyId, mchApplyment.getApplyId())
                .eq(MchSubInfoEntity::getMainUse, 1)
                .eq(MchSubInfoEntity::getSubMchType, "ZFB");
        if ("AUTHORIZED".equals(authState)) {
            result.setState("已授权");
            stateUpdate.set(MchSubInfoEntity::getAuthStatus, MchSubInfo.AUTH_STATUS_AUTHORIZED).update();
        } else if ("CLOSED".equals(authState)) {
            result.setState("已销户");
            stateUpdate.set(MchSubInfoEntity::getAuthStatus, MchSubInfo.AUTH_STATUS_LOGOFF).update();
        } else {
            result.setState("未授权");
            stateUpdate.set(MchSubInfoEntity::getAuthStatus, MchSubInfo.AUTH_STATUS_UNAUTHORIZED).update();
        }

        return result;
    }

}
