package cn.pluss.platform.ys.impl.v20210929;

import cn.pluss.platform.channel.MerchantCertService;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchant.MerchantCashPlaceService;
import cn.pluss.platform.merchant.MerchantRateNewService;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.subMerchant.SubMerchantService;
import cn.pluss.platform.task.IMerAuditHandler;
import cn.pluss.platform.task.MercIncomSetRateHandler;
import cn.pluss.platform.task.SxfMerAuditHandler;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.util.LogExceptionUtils;
import cn.pluss.platform.yinsheng.v20210929.ReqMethod;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.util.Map;

/**
 * @author DJH
 */
@Slf4j
public abstract class AbstractYsResultService extends AbstractYsImgUploadService {

    @Autowired
    protected MerchantChannelStatusService mcsService;

    @Autowired
    @Lazy
    private IMerAuditHandler ysMerAuditV2Handler;

    @Autowired
    private YsServiceV2 ysServiceV2;

    @Autowired
    private SubMerchantService smService;

    @Autowired
    private MerchantCertService ysCertV2Service;

    @Autowired
    private UserAppService uaService;

    @Autowired
    private SxfMerAuditHandler sxfMerAuditHandler;

    @Autowired
    private MerchantRateNewService rateNewService;

    @Autowired
    private MercIncomSetRateHandler mercIncomSetRateHandler;

    @Autowired @Lazy
    private MerchantBaseInfoService mbiService;

    @Autowired @Lazy
    private MerchantCashPlaceService cashPlaceService;

    @Override
    public JSONObject editMerchantCallback(JSONObject auditResult) throws Exception {
        return null;
    }

    @Override
    public JSONObject merchantAuditCallback(JSONObject auditResult) throws Exception {
        ysMerAuditV2Handler.auditHandler(auditResult);
        return null;
    }

    @Override
    public JSONObject merchantAuditResult(Map<String, Object> param) throws Exception {
        try {
            JSONObject reqParam = new JSONObject();
            reqParam.putAll(param);
            JSONObject data = ysServiceV2.req(YsConfigV2.MER_RESULT, ReqMethod.MERCHANT_QUERY, reqParam);

            String status = data.getString("status");

            if (YsConstant.AuditStatus.AUDIT_FIRST_TRIAL_SUCCESS.getCode().equals(status)
                    || YsConstant.AuditStatus.AUDIT_NO_AUDIT.getCode().equals(status)) {
                firstTrial(data);
            } else if (YsConstant.AuditStatus.AUDIT_SUCCESS.getCode().equals(status)) {
                success(data);
            } else if (YsConstant.AuditStatus.AUDIT_FIRST_TRIAL_FAIL.getCode().equals(status)) {
                fail(data);
            }

        } catch (Exception ignored) {
            ignored.printStackTrace();
        }

        return null;
    }

    /**
     * 初审
     */
    private void firstTrial(JSONObject data) {
        String status = data.getString("status");
        // 初审完成，判断电子合同签约状态
        String sysFlowId = data.getString("sysFlowId");
        MerchantChannelStatus mcs = getMcsInfoByAppId(sysFlowId);
        commonPropSet(mcs, data);

        if (!mcs.getStatus().equals(MerchantChannelStatus.AUDIT_STATUS_SIGNED)
//                && !YsConstant.AuditStatus.AUDIT_NO_AUDIT.getCode().equals(status)
                && !"wait".equals(status)) {
            reqMerProtocolStatus(mcs);
        }
    }

    public void collectSubMerId(JSONArray thirdMercIdList, String mercId) {
        try {
            if (thirdMercIdList != null) {

                int size = thirdMercIdList.size();
                for (int i = 0; i < size; i++) {
                    JSONObject thirdMerc = thirdMercIdList.getJSONObject(i);
                    String flag = thirdMerc.getString("flag");
                    String thirdMercId = thirdMerc.getString("thirdMercId");
                    String type = thirdMerc.getString("type");

                    SubMerchant subMerchant = new SubMerchant();
                    subMerchant.setMerchantId(mercId);

                    if ("wx".equals(flag)) {
                        flag = "WX";
                    }

                    if ("alipay".equals(flag)) {
                        flag = "ZFB";
                    }

                    if (StringUtils.isEmpty(thirdMercId)) {
                        continue;
                    }

                    subMerchant.setSubMchId(thirdMercId + "_" + type);
                    subMerchant.setSubMchType(flag);
                    subMerchant.setChannelTypeId("4");
                    smService.save(subMerchant);
                }
            }
        } catch (Exception ignored) {
        }
    }

    /**
     * 开户成功
     */
    public void success(JSONObject data) {
        String mercId = data.getString("mercId");

        String sysFlowId = (String) data.get("sysFlowId");
        MerchantChannelStatus mcs = getMcsInfoByAppId(sysFlowId);

        if (mcs.getStatus().equals(MerchantChannelStatus.AUDIT_STATUS_SUCCESS)) {
            // 已经进件通过的，不进行初次进件的逻辑操作
            return;
        }

        mcs.setStatus(MerchantChannelStatus.AUDIT_STATUS_SUCCESS);
        // 此处的状态是参考文档上的状态，接口未传该信息
        commonPropSet(mcs, data);
        mcsService.updateById(mcs);

        // 开通D0
        openOnlinePay(mcs);

        // 微信认证
        try {
            ysCertV2Service.wxCert(mercId, mcs.getMerchantCode());
        } catch (Exception e) {
            log.debug("微信认证异常");
            e.printStackTrace();
        }

        String pushMsg = "商家审核通过";
        LambdaQueryWrapper<UserApp> qWrapper2 = Wrappers.lambdaQuery();
        qWrapper2.eq(UserApp::getMerchantCode, mcs.getMerchantCode());
        qWrapper2.eq(UserApp::getUserType, "promoter");
        UserApp userApp = uaService.getOne(qWrapper2);
        sxfMerAuditHandler.sendNotice(userApp, "收银呗审核通知", pushMsg, mcs.getApplicationId());

        // 因为接口进件费率与默认进件费率不一致，所以这里将费率存下来
        try {
            MerchantRateNew merchRateNew = new MerchantRateNew();
            merchRateNew.setWxRate(38);
            merchRateNew.setAliRate(38);
            merchRateNew.setBankRate(38);
            merchRateNew.setBankRateLarge(37);
            merchRateNew.setChannel(4);
            merchRateNew.setUserId(userApp.getUserId() + "");
            merchRateNew.setMerchantId(mcs.getMerchantId());
            rateNewService.save(merchRateNew);
        } catch (Exception e) {
            log.info("费率信息保存失败");
        }

        // 统计当前进件商户的上级商户是否满足费率要求
        try {
            mercIncomSetRateHandler.installSuperMerchantRate(userApp);
        } catch (Exception e) {
            log.info("设置进件商户上级商户费率异常，异常信息:{}", e.getMessage());
        }

        // 以下代码为进件结果处理后的操作
        // 创建线上店铺
        try {
            log.info("===================>进件回调，创建店铺开始,商户编号为:{}<=====================", mcs.getMerchantId());
            sxfMerAuditHandler.createStore(mcs);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("创建店铺信息异常,异常信息:{}", e.getMessage());
        }

        try {
            MerchantBaseInfo merchantBaseInfo = mbiService.getMerchantBaseInfoByMerchantCode(mcs.getMerchantCode());
            if (StringUtils.isNotBlank(merchantBaseInfo.getUserId())) {
                cashPlaceService.createDefaultCashPlace(Long.parseLong(merchantBaseInfo.getUserId()));
            }
        } catch (Exception e) {
            LogExceptionUtils.printStack(log, e, "创建默认收银点失败,异常信息:{}");
        }
    }

    /**
     * 失败
     */
    public void fail(JSONObject data) {
        String mercId = data.getString("mercId");
        String remark = data.getString("nogoRemark");
        String sysFlowId = data.getString("sysFlowId");
        MerchantChannelStatus mcs = getMcsInfoByAppId(sysFlowId);

        mcs.setRemark(remark);
        mcs.setStatus(MerchantChannelStatus.AUDIT_STATUS_REJECT);
        // 此处的状态是参考文档上的状态，接口未传该信息
        commonPropSet(mcs, data);
        mcsService.updateById(mcs);

        LambdaQueryWrapper<UserApp> qWrapper2 = Wrappers.lambdaQuery();
        qWrapper2.eq(UserApp::getMerchantCode, mcs.getMerchantCode());
        qWrapper2.eq(UserApp::getUserType, "promoter");
        UserApp userApp = uaService.getOne(qWrapper2);
        String uniqueKey = sysFlowId + System.currentTimeMillis();
        sxfMerAuditHandler.sendNotice(userApp, "收银呗审核通知", remark, uniqueKey);
    }

    private MerchantChannelStatus getMcsInfoByAppId(String applicationId) {
        MerchantChannelStatus mcs = new MerchantChannelStatus();
        mcs.setApplicationId(applicationId);
        mcs.setChannel(4);
        mcs = mcsService.getOne(new QueryWrapper<>(mcs));

        MsgException.checkNull(mcs, "未获取到进件信息");
        mcs = mcsService.getByIdLock(mcs.getId());

        return mcs;
    }

    private void commonPropSet(MerchantChannelStatus mcs, JSONObject data) {
        String mercId = data.getString("mercId");
        String remark = data.getString("note1");
        String status = data.getString("status");

        mcs.setThirdStatus(status);
        mcs.setRemark(remark);
        mcs.setMerchantId(mercId);
        if (mcs.getExtra() == null) {
            mcs.setExtra(new JSONObject());
        }
        mcs.getExtra().putAll(data);
    }

    /**
     * 开通D0
     */
    abstract void openOnlinePay(MerchantChannelStatus mcs);
}
