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

import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.MchStore;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.interfaces.IConfigContextQueryService;
import com.jeequan.jeepay.core.interfaces.paychannel.alipaybiz.IAlipayShopService;
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.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.apache.commons.lang3.tuple.MutablePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/***
* 蚂蚁门店
*
* @author zx
* @date 2023/03/13 15:26
*/
@Component
public class AlipayShopManage {

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

    /** 查询店铺详情  **/
    public ApiRes query(String mchNo, String storeId) {
        try {
            MutablePair<AlipayIsvParams, AlipaySpOperationInfo> mutablePair = checkAndGetAlipaySpOperationInfo(mchNo, storeId);

            IAlipayShopService alipayShopService = SpringBeansUtil.getBean(IAlipayShopService.class);
            MchStore result = alipayShopService.query(mutablePair.getLeft(), String.valueOf(storeId), mutablePair.getRight().getMerchantNo());

            MchStore dbRecord = mchStoreService.getById(storeId);
            result.setStoreId(storeId);
            result.setAlipayShopStatus(dbRecord.getAlipayShopStatus());

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

    /** 创建店铺  **/
    public ApiRes create(String mchNo, String storeId, MchStore mchStore) {
        try {
            MutablePair<AlipayIsvParams, AlipaySpOperationInfo> mutablePair = checkAndGetAlipaySpOperationInfo(mchNo, storeId);

            IAlipayShopService alipayShopService = SpringBeansUtil.getBean(IAlipayShopService.class);
            MchStore result = alipayShopService.create(mutablePair.getLeft(), mchStore, mutablePair.getRight().getMerchantNo());

            // 蚂蚁店铺申请创建成功，保存申请单号，用于查询申请状态
            com.jeequan.jeepay.db.entity.MchStore updateRecord = new com.jeequan.jeepay.db.entity.MchStore();
            updateRecord.setStoreId(storeId);
            updateRecord.setAlipayShopCreateId(result.getAlipayShopCreateId());
            updateRecord.setAlipayShopStatus(MchStore.ALIPAY_SHOP_STATUS_AUDITING); // 审核中
            mchStoreService.updateById(updateRecord);

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

    /** 修改店铺  **/
    public ApiRes update(String mchNo, String storeId, MchStore mchStore) {
        try {
            // 查询商户门店是否已成功创建蚂蚁店铺
            com.jeequan.jeepay.db.entity.MchStore dbRecord = mchStoreService.getById(storeId);
            if (dbRecord == null || !MchStore.ALIPAY_SHOP_STATUS_SUCCESS.equals(dbRecord.getAlipayShopStatus()) || StringUtils.isBlank(dbRecord.getAlipayShopId())) {
                throw new BizException("门店不存在或未成功创建蚂蚁店铺！");
            }
            mchStore.setAlipayShopId(dbRecord.getAlipayShopId()); // 蚂蚁店铺ID

            MutablePair<AlipayIsvParams, AlipaySpOperationInfo> mutablePair = checkAndGetAlipaySpOperationInfo(mchNo, storeId);

            IAlipayShopService alipayShopService = SpringBeansUtil.getBean(IAlipayShopService.class);
            MchStore result = alipayShopService.update(mutablePair.getLeft(), mchStore);

            // 蚂蚁店铺申请创建成功，保存申请单号，用于查询申请状态
            com.jeequan.jeepay.db.entity.MchStore updateRecord = new com.jeequan.jeepay.db.entity.MchStore();
            updateRecord.setStoreId(storeId);
            updateRecord.setAlipayShopCreateId(result.getAlipayShopCreateId());
            updateRecord.setAlipayShopStatus(MchStore.ALIPAY_SHOP_STATUS_AUDITING); // 审核中
            mchStoreService.updateById(updateRecord);

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

    /** 关闭店铺  **/
    public ApiRes close(String mchNo, String storeId) {
        try {
            MutablePair<AlipayIsvParams, AlipaySpOperationInfo> mutablePair = checkAndGetAlipaySpOperationInfo(mchNo, storeId);

            // 查询商户门店是否已成功创建蚂蚁店铺
            com.jeequan.jeepay.db.entity.MchStore dbRecord = mchStoreService.getById(storeId);
            if (dbRecord == null || !MchStore.ALIPAY_SHOP_STATUS_SUCCESS.equals(dbRecord.getAlipayShopStatus()) || StringUtils.isBlank(dbRecord.getAlipayShopId())) {
                throw new BizException("门店不存在或未成功创建蚂蚁店铺！");
            }

            // 查询门店下是否绑定了设备
            long count = mchStoreDeviceService.count(MchStoreDevice.gw()
                    .eq(MchStoreDevice::getAlipayBindState, CS.YES)
                    .eq(MchStoreDevice::getAlipayShopId, dbRecord.getAlipayShopId()));
            if (count > 0) {
                throw new BizException("当前门店下存在绑定的设备，请先解绑");
            }

            IAlipayShopService alipayShopService = SpringBeansUtil.getBean(IAlipayShopService.class);
            alipayShopService.close(mutablePair.getLeft(), dbRecord.getAlipayShopId());

            // 蚂蚁店铺关闭成功，将本地蚂蚁门店信息改为初始未创建状态
            com.jeequan.jeepay.db.entity.MchStore updateRecord = new com.jeequan.jeepay.db.entity.MchStore();
            updateRecord.setStoreId(storeId);
            updateRecord.setAlipayShopId("");
            updateRecord.setAlipayShopCreateId("");
            updateRecord.setAlipayShopStatus(MchStore.ALIPAY_SHOP_STATUS_NOT_EXISTS); // 未创建
            mchStoreService.updateById(updateRecord);

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


    /** 根据申请单查询店铺创建结果  **/
    public ApiRes createResultQuery(String mchNo, String storeId) {
        try {
            // 查询商户门店下  蚂蚁店铺是否为审核中
            com.jeequan.jeepay.db.entity.MchStore dbRecord = mchStoreService.getById(storeId);
            if (dbRecord == null) {
                throw new BizException("门店不存在！");
            }
            if (MchStore.ALIPAY_SHOP_STATUS_SUCCESS.equals(dbRecord.getAlipayShopStatus())) {
                return ApiRes.ok(dbRecord);
            }
            if (StringUtils.isBlank(dbRecord.getAlipayShopCreateId())) {
                throw new BizException("未发起创建蚂蚁店铺！");
            }

            MutablePair<AlipayIsvParams, AlipaySpOperationInfo> mutablePair = checkAndGetAlipaySpOperationInfo(mchNo, storeId);

            IAlipayShopService alipayShopService = SpringBeansUtil.getBean(IAlipayShopService.class);
            MchStore result = alipayShopService.createResultQuery(mutablePair.getLeft(), dbRecord.getAlipayShopCreateId());

            // 更新蚂蚁店铺授权状态
            com.jeequan.jeepay.db.entity.MchStore updateRecord = new com.jeequan.jeepay.db.entity.MchStore();
            updateRecord.setStoreId(storeId);
            updateRecord.setAlipayShopId(result.getAlipayShopId());
            updateRecord.setAlipayShopStatus(result.getAlipayShopStatus());
            mchStoreService.updateById(updateRecord);

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


    /** 查询当前商户支付宝授权信息  **/
    private MutablePair<AlipayIsvParams, AlipaySpOperationInfo> checkAndGetAlipaySpOperationInfo(String mchNo, String storeId) {
        MchStore mchStore = mchStoreService.getById(storeId);
        if (mchStore == null) {
            throw new BizException("门店不存在");
        }
        // 运营平台只传storeId，商户系统传递mchNo并校验权限
        if (StringUtils.isNotBlank(mchNo) && !mchNo.equals(mchStore.getMchNo())) {
            throw new BizException(ApiCodeEnum.SYS_PERMISSION_ERROR);
        }
        mchNo = StringUtils.defaultIfBlank(mchNo, mchStore.getMchNo());

        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 operationInfo = JSONObject.parseObject(mchConfig.getConfigVal(), AlipaySpOperationInfo.class);
        if (!AlipaySpOperationInfo.HANDLE_STATUS_SUCCESS.equals(operationInfo.getHandleStatus()) || StringUtils.isBlank(operationInfo.getMerchantNo())) {
            throw new BizException("支付宝代运营授权未通过，无法操作蚂蚁店铺");
        }

        return MutablePair.of(alipayIsvParams, operationInfo);
    }

}
