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

import com.alibaba.fastjson.JSON;
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.IAlipayIotDeviceBindService;
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.MchApplyment;
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.*;
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;

/***
* 支付宝Iot设备-店铺绑定ctrl
*
* @author zx
* @date 2023/03/13 15:26
*/
@Component
public class AlipayIotDeviceBindManage {

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

    /** 绑定蚂蚁店铺  **/
    public ApiRes bind(String mchNo, Long deviceId, Byte alipayBindState, String bindStoreId) {
        try {
            if (CS.YES == alipayBindState && bindStoreId == null) {
                return ApiRes.customFail("请选择要绑定的蚂蚁店铺");
            }

            // 校验&&获取绑定设备所需信息
            MutablePair<AlipayIsvParams, MchStoreDevice> pair = checkAndGetAlipaySpOperationInfo(mchNo, bindStoreId, deviceId);
            MchStoreDevice mchStoreDevice = pair.getRight();
            String supplierId = MchStoreDevice.ALIPAY_IOT_DEVICE_MAP.get(mchStoreDevice.getProvider());

            IAlipayIotDeviceBindService alipayIotDeviceBindService = SpringBeansUtil.getBean(IAlipayIotDeviceBindService.class);

            // 绑定
            if (CS.YES == alipayBindState) {
                // 换绑  需先解绑
                if (mchStoreDevice.getAlipayBindState() == CS.YES) {
                    alipayIotDeviceBindService.unbind(pair.getLeft(), mchStoreDevice.getMchNo(), mchStoreDevice.extv().getString("alipayMerchantNo"),
                            mchStoreDevice.getAlipayShopId(), supplierId, mchStoreDevice.getDeviceNo());
                }

                JSONObject deviceJSON = new JSONObject();
                deviceJSON.put("deviceType", mchStoreDevice.getDeviceType());
                deviceJSON.put("deviceNo", mchStoreDevice.getDeviceNo());
                deviceJSON.put("provider", mchStoreDevice.getProvider());

                alipayIotDeviceBindService.bind(pair.getLeft(), mchStoreDevice.getMchNo(), mchStoreDevice.extv().getString("alipayMerchantNo"),
                        mchStoreDevice.extv().getString("alipayShopId"), supplierId, deviceJSON);

                // 蚂蚁店铺设备绑定成功
                MchStoreDevice updateRecord = new MchStoreDevice();
                updateRecord.setDeviceId(deviceId);
                updateRecord.setAlipayBindState(CS.YES);
                updateRecord.setAlipayShopId(mchStoreDevice.extv().getString("alipayShopId"));
                mchStoreDeviceService.updateById(updateRecord);
            }
            // 解绑
            else {
                alipayIotDeviceBindService.unbind(pair.getLeft(), mchStoreDevice.getMchNo(), mchStoreDevice.extv().getString("alipayMerchantNo"),
                        mchStoreDevice.getAlipayShopId(), supplierId, mchStoreDevice.getDeviceNo());

                // 蚂蚁店铺设备解绑成功
                MchStoreDevice updateRecord = new MchStoreDevice();
                updateRecord.setDeviceId(deviceId);
                updateRecord.setAlipayBindState(CS.NO);
                updateRecord.setAlipayShopId("");
                mchStoreDeviceService.updateById(updateRecord);
            }

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

    /** 查询设备信息  **/
    public ApiRes query(String mchNo, String storeId, Long deviceId) {
        try {
            MutablePair<AlipayIsvParams, MchStoreDevice> pair = checkAndGetAlipaySpOperationInfo(mchNo, storeId, deviceId);
            MchStoreDevice mchStoreDevice = pair.getRight();

            IAlipayIotDeviceBindService alipayIotDeviceBindService = SpringBeansUtil.getBean(IAlipayIotDeviceBindService.class);
            JSONObject resJSON = alipayIotDeviceBindService.query(pair.getLeft(), mchStoreDevice.getDeviceNo());

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


    /** 查询当前商户支付宝授权信息  **/
    private MutablePair<AlipayIsvParams, MchStoreDevice> checkAndGetAlipaySpOperationInfo(String mchNo, String bindStoreId, Long deviceId) {
        // 查询绑定设备信息
        MchStoreDevice storeDevice = mchStoreDeviceService.getById(deviceId);
        if (storeDevice == null || storeDevice.getState() != CS.YES || storeDevice.getBindState() != CS.YES || storeDevice.getDeviceType() != MchStoreDevice.DEVICE_TYPE_RUYI) {
            throw new BizException("设备不存在或未绑定");
        }
        // 运营平台只传deviceId，商户系统传递mchNo并校验权限
        if (StringUtils.isNotBlank(mchNo) && !mchNo.equals(storeDevice.getMchNo())) {
            throw new BizException(ApiCodeEnum.SYS_PERMISSION_ERROR);
        }
        mchNo = StringUtils.defaultIfBlank(mchNo, storeDevice.getMchNo());
        com.jeequan.jeepay.db.entity.MchStore mchStore2 = mchStoreService.getById(storeDevice.getStoreId());
        MchApplyment mchApplyment = mchApplymentService.getById(mchStore2.getMchApplyId());

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

        AlipayIsvParams alipayIsvParams = (AlipayIsvParams) configContextQueryService.queryIsvParams(mchApplyment.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 = JSON.parseObject(mchConfig.getConfigVal(), AlipaySpOperationInfo.class);
        if (!AlipaySpOperationInfo.HANDLE_STATUS_SUCCESS.equals(operationInfo.getHandleStatus()) || StringUtils.isBlank(operationInfo.getMerchantNo())) {
            throw new BizException("请先发起支付宝代运营授权");
        }

        // 查询蚂蚁店铺ID
        if (bindStoreId != null) {
            com.jeequan.jeepay.db.entity.MchStore mchStore = mchStoreService.getById(bindStoreId);
            if (!MchStore.ALIPAY_SHOP_STATUS_SUCCESS.equals(mchStore.getAlipayShopStatus()) || StringUtils.isBlank(mchStore.getAlipayShopId())) {
                throw new BizException("当前店铺未同步至蚂蚁店铺");
            }
            storeDevice.addExt("alipayShopId", mchStore.getAlipayShopId());
        }

        storeDevice.addExt("alipayMerchantNo", operationInfo.getMerchantNo());

        return MutablePair.of(alipayIsvParams, storeDevice);
    }

}
