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

import cn.hutool.core.util.StrUtil;
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.yspay.YspayIsvParams;
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.yspay.utils.YspayKit;
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 YspayIsvmchAlipayConfigService 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);
        YspayIsvParams isvParams = (YspayIsvParams) configContextQueryService.queryIsvParams(mchApplyment);
        // 支付宝渠道拓展地址
        result.setSignUrl(isvParams.getAliChannelExtUrl());
        // 图片类型
        result.setImgType(ApplymentSignInfo.IMG_TYPE_QRCONTENT);

        if (suJson == null || StringUtils.isEmpty(suJson.getString("mercId"))) {
            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 (StrUtil.isEmpty(zfb.getSubMchId())) {
            result.setState("未报备");
            result.setErrInfo("[" + zfb.getRemark() + "]");
            return result;
        } else {
            result.setChannelSubMchId(zfb.getSubMchId());
        }

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

        // 发送请求
        String resultStr = YspayKit.applymentRequest("/openapi/pregate/alipay/getAuthState", "pregate.alipay.getAuthState", isvParams, bizContent);
        JSONObject response = JSON.parseObject(resultStr);

        // 解密后数据
        JSONObject resData = response.getJSONObject("data");
        if (resData == null) {
            result.setState("04");
            result.setErrInfo(response.getString("code") + "[" + response.getString("msg") + "]");
            return result;
        }

        String authState = resData.getString("authState");

        LambdaUpdateChainWrapper<MchSubInfoEntity> stateUpdate = mchSubInfoService.lambdaUpdate()
                .eq(MchSubInfoEntity::getMchApplyId, mchApplyment.getApplyId())
                .eq(MchSubInfoEntity::getMainUse, 1)
                .eq(MchSubInfoEntity::getSubMchType, "ZFB");
        if ("1".equals(authState)) {
            result.setState("已授权");
            stateUpdate.set(MchSubInfoEntity::getAuthStatus, MchSubInfo.AUTH_STATUS_AUTHORIZED).update();
        } else if ("2".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;
    }

}
