package com.jeequan.jeepay.bizcommons.manage.alipay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.interfaces.IConfigContextQueryService;
import com.jeequan.jeepay.core.interfaces.paychannel.alipaybiz.IAlipayOpenSpOperationService;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.model.alipay.AlipaySpOperationInfo;
import com.jeequan.jeepay.core.model.params.alipay.AlipayIsvParams;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.db.entity.MchConfig;
import com.jeequan.jeepay.db.entity.MchInfo;
import com.jeequan.jeepay.db.entity.MchStore;
import com.jeequan.jeepay.db.entity.MchStoreDevice;
import com.jeequan.jeepay.service.impl.MchConfigService;
import com.jeequan.jeepay.service.impl.MchInfoService;
import com.jeequan.jeepay.service.impl.MchStoreDeviceService;
import com.jeequan.jeepay.service.impl.MchStoreService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/***
* 支付宝服务商代运营授权
*
* @author zx
* @date 2023/03/13 15:26
*/
@Component
public class AlipayOpenSpOperationManage {

    @Autowired private MchInfoService mchInfoService;
    @Autowired private MchConfigService mchConfigService;
    @Autowired private MchStoreService mchStoreService;
    @Autowired private MchStoreDeviceService mchStoreDeviceService;
    @Autowired private IConfigContextQueryService configContextQueryService;

    /** 获取授权码  **/
    public ApiRes queryQrcode(String mchNo, String alipayAccount) {
        try {
            AlipayIsvParams alipayIsvParams = applyCheck(mchNo);

            IAlipayOpenSpOperationService alipayOpenSpOperationService = SpringBeansUtil.getBean(IAlipayOpenSpOperationService.class);
            JSONObject resJSON = alipayOpenSpOperationService.querySpOperationQrcode(alipayIsvParams, alipayAccount);

            // 保存或更新发起授权的支付宝登录账号
            mchInfoService.saveOrUpdateAlipaySpOperationAccount(mchNo, alipayAccount, "qrcode");

            return ApiRes.ok(resJSON);
        }catch (Exception e) {
            return ApiRes.customFail(StringUtils.defaultString(e.getMessage(), "系统异常！"));
        }
    }

    /** 发起授权  **/
    public ApiRes apply(String mchNo, String alipayAccount) {
        try {
            AlipayIsvParams alipayIsvParams = applyCheck(mchNo);

            IAlipayOpenSpOperationService alipayOpenSpOperationService = SpringBeansUtil.getBean(IAlipayOpenSpOperationService.class);
            JSONObject resJSON = alipayOpenSpOperationService.applySpOperation(alipayIsvParams, alipayAccount);

            // 保存或更新发起授权的支付宝登录账号
            mchInfoService.saveOrUpdateAlipaySpOperationAccount(mchNo, alipayAccount, "apply");

            return ApiRes.ok(resJSON);
        }catch (Exception e) {
            return ApiRes.customFail(StringUtils.defaultString(e.getMessage(), "系统异常！"));
        }
    }

    /** 查询支付宝授权结果  **/
    public ApiRes queryResult(String mchNo) {
        try {
            MchInfo mchInfo = mchInfoService.getById(mchNo);
            if (MchInfo.TYPE_ISVSUB != mchInfo.getType()) {
                throw new BizException("仅支持特约商户");
            }
            AlipayIsvParams alipayIsvParams = (AlipayIsvParams) configContextQueryService.queryIsvParams(mchInfo.getIsvNo(), CS.IF_CODE.ALIPAY);
            if (alipayIsvParams == null) {
                throw new BizException("服务商未配置参数，请联系平台处理！");
            }

            MchConfig mchConfig = mchConfigService.getByMchNoAndConfigKey(mchNo, AlipaySpOperationInfo.MCH_CONFIG_KEY);
            if (mchConfig == null || StringUtils.isBlank(mchConfig.getConfigVal())) {
                throw new BizException("请先发起授权");
            }
            AlipaySpOperationInfo dbOperationInfo = JSON.parseObject(mchConfig.getConfigVal(), AlipaySpOperationInfo.class);
            if (AlipaySpOperationInfo.HANDLE_STATUS_SUCCESS.equals(dbOperationInfo.getHandleStatus())) {
                throw new BizException("已授权成功，无需再次查询");
            }

            // 查询支付宝授权状态
            IAlipayOpenSpOperationService alipayOpenSpOperationService = SpringBeansUtil.getBean(IAlipayOpenSpOperationService.class);
            AlipaySpOperationInfo operationResult = alipayOpenSpOperationService.querySpOperationResult(alipayIsvParams, dbOperationInfo.getAlipayAccount());

            // 更新授权状态
            if (AlipaySpOperationInfo.HANDLE_STATUS_SUCCESS.equals(operationResult.getHandleStatus())) {
                dbOperationInfo.setHandleStatus(operationResult.getHandleStatus());
                dbOperationInfo.setMerchantNo(operationResult.getMerchantNo());

                MchConfig updateRecord = new MchConfig();
                updateRecord.setConfigVal(JSON.toJSONString(dbOperationInfo));
                mchConfigService.update(updateRecord,
                        new LambdaUpdateWrapper<MchConfig>().eq(MchConfig::getConfigKey, AlipaySpOperationInfo.MCH_CONFIG_KEY).eq(MchConfig::getMchNo, mchNo));
            }

            return ApiRes.ok(operationResult);
        }catch (Exception e) {
            return ApiRes.customFail(StringUtils.defaultString(e.getMessage(), "系统异常！"));
        }
    }

    /** 查询当前商户支付宝授权信息  **/
    public ApiRes authInfo(String mchNo) {
        MchConfig mchConfig = mchConfigService.getByMchNoAndConfigKey(mchNo, AlipaySpOperationInfo.MCH_CONFIG_KEY);
        if (mchConfig == null || StringUtils.isBlank(mchConfig.getConfigVal())) {
            return ApiRes.ok();
        }

        return ApiRes.ok(JSON.parseObject(mchConfig.getConfigVal()));
    }


    private AlipayIsvParams applyCheck(String mchNo) {
        MchInfo mchInfo = mchInfoService.getById(mchNo);
        if (MchInfo.TYPE_ISVSUB != mchInfo.getType()) {
            throw new BizException("仅支持特约商户");
        }

        AlipayIsvParams alipayIsvParams = (AlipayIsvParams) configContextQueryService.queryIsvParams(mchInfo.getIsvNo(), CS.IF_CODE.ALIPAY);
        if (alipayIsvParams == null) {
            throw new BizException("服务商未配置参数，请联系平台处理！");
        }

        // 查询是否存在绑定的设备
        long count = mchStoreDeviceService.count(MchStoreDevice.gw()
                .eq(MchStoreDevice::getMchNo, mchNo)
                .eq(MchStoreDevice::getDeviceType, MchStoreDevice.DEVICE_TYPE_RUYI)
                .eq(MchStoreDevice::getAlipayBindState, CS.YES)
        );
        if (count > 0) {
            throw new BizException("存在绑定的如意设备，请先将如意设备从蚂蚁店铺解绑！");
        }

        // 查询是否存在绑定蚂蚁店铺
        count = mchStoreService.count(MchStore.gw().
                eq(MchStore::getMchNo, mchNo)
                .in(MchStore::getAlipayShopStatus, Arrays.asList(MchStore.ALIPAY_SHOP_STATUS_SUCCESS, MchStore.ALIPAY_SHOP_STATUS_AUDITING))
        );
        if (count > 0) {
            throw new BizException("已创建蚂蚁店铺，请先关闭蚂蚁店铺！");
        }
        return alipayIsvParams;
    }

}
