package cn.pluss.platform.ysExtension.v20220615;

import cn.pluss.platform.entity.*;
import cn.pluss.platform.jft.JftMercBaseInfoService;
import cn.pluss.platform.merchant.JftMercPaymentChannelService;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.task.IJftMercAuditHandler;
import cn.pluss.platform.task.SxfMerAuditHandler;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.userInfo.UserInfoService;
import cn.pluss.platform.yinsheng.v20210929.ReqMethod;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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 IJftMercAuditHandler ysMerAuditExtensionV2Handler;

    @Autowired
    private YsServiceV2 ysServiceV2;

    @Autowired
    private UserAppService uaService;

    @Autowired
    private SxfMerAuditHandler sxfMerAuditHandler;

    @Autowired
    protected JftMercPaymentChannelService jpcService;

    @Autowired
    protected JftMercBaseInfoService jbiService;

    @Autowired
    private UserInfoService uiService;

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

    @Override
    public JSONObject merchantAuditCallback(JSONObject auditResult) throws Exception {
        ysMerAuditExtensionV2Handler.auditCallback(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(YsConfigExtensionV2.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");
        JftMercPaymentChannel jpc = getMcsInfoByAppId(sysFlowId);
        commonPropSet(jpc, data);

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

    public void remainSigned(JSONObject data) {
        String sysFlowId = (String) data.get("sysFlowId");
        JftMercPaymentChannel jpc = getMcsInfoByAppId(sysFlowId);
        if (jpc.getStatus().equals(MerchantChannelStatus.AUDIT_STATUS_SUCCESS)) {
            // 已经进件通过的，不进行初次进件的逻辑操作
            return;
        }

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

        String pushMsg = "缴费通开通进度，当前待签约";
        LambdaQueryWrapper<UserApp> qWrapper2 = Wrappers.lambdaQuery();
        qWrapper2.eq(UserApp::getUserId, jpc.getUserId());
        qWrapper2.eq(UserApp::getUserType, "promoter");
        UserApp userApp = uaService.getOne(qWrapper2);

        sxfMerAuditHandler.sendNotice(userApp, "收银呗审核通知", pushMsg, jpc.getApplicationId());

    }

    /**
     * 开户成功
     */
    public void success(JSONObject data) {

        String sysFlowId = (String) data.get("sysFlowId");
        JftMercPaymentChannel jpc = getMcsInfoByAppId(sysFlowId);
        if (jpc.getStatus().equals(MerchantChannelStatus.AUDIT_STATUS_SUCCESS)) {
            // 已经进件通过的，不进行初次进件的逻辑操作
            return;
        }

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

        // 开通D0
        openOnlinePay(jpc);

        String pushMsg = "缴费通审核通过";
        LambdaQueryWrapper<UserApp> qWrapper2 = Wrappers.lambdaQuery();
        qWrapper2.eq(UserApp::getUserId, jpc.getUserId());
        UserApp userApp = uaService.getOne(qWrapper2);

        sxfMerAuditHandler.sendNotice(userApp, "收银呗审核通知", pushMsg, jpc.getApplicationId());

    }

    /**
     * 失败
     */
    public void fail(JSONObject data) {
        String sysFlowId = data.getString("sysFlowId");
        JftMercPaymentChannel jpc = getMcsInfoByAppId(sysFlowId);
        jpc.setStatus(MerchantChannelStatus.AUDIT_STATUS_REJECT);
        // 此处的状态是参考文档上的状态，接口未传该信息
        commonPropSet(jpc, data);
        jpcService.updateById(jpc);

        LambdaQueryWrapper<UserApp> qWrapper2 = Wrappers.lambdaQuery();
        qWrapper2.eq(UserApp::getUserId, jpc.getUserId());
        qWrapper2.eq(UserApp::getUserType, "promoter");
        UserApp userApp = uaService.getOne(qWrapper2);
        String uniqueKey = sysFlowId + System.currentTimeMillis();
        sxfMerAuditHandler.sendNotice(userApp, "收银呗审核通知", "缴费通审核不通过: " + data.getString("nogoRemark"), uniqueKey);

    }

    private JftMercPaymentChannel getMcsInfoByAppId(String applicationId) {
        return jpcService.getByApplicationId(applicationId);
    }

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

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

    /**
     * 开通D0
     */
    abstract void openOnlinePay(JftMercPaymentChannel jpc);
}
