package cn.pluss.platform.task;

import cn.pluss.platform.channel.MerchProtocolService;
import cn.pluss.platform.channel.MerchantAuditService;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.mapper.MerchantChannelStatusMapper;
import cn.pluss.platform.merchant.AccountService;
import cn.pluss.platform.merchant.MerchantRateNewRecordService;
import cn.pluss.platform.merchant.MerchantRateNewService;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.yinsheng.v20210929.AuditCallbackInfo;
import cn.pluss.platform.ys.impl.v20210929.AbstractYsResultService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author djh
 */
@Slf4j
@Component("ysMerAuditV2Handler")
public class YsMerAuditV2Handler extends BaseMerAuditHandler<YsMerAuditV2Handler> {

    @Autowired
    private MerchantAuditService ysAuditServiceV2;

    @Autowired
    private MerchantChannelStatusService mcsService;

    @Autowired
    private SxfMerAuditHandler sxfMerAuditHandler;

    @Resource
    private MerchantChannelStatusMapper mcsMapper;

    @Autowired
    private MerchantRateNewRecordService mrnrService;

    @Autowired
    private AccountService accountService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MerchantChannelStatus auditCallback(JSONObject auditResult) {
        if (auditResult == null) {
            return null;
        }

        String notifyType = auditResult.getString("notifyType");
        String status = auditResult.getString("status");

        MerchantChannelStatus mcs = null;
        if (Objects.equals(notifyType, "00")) {

            JSONObject urm = auditResult.getJSONObject("urm");
            // 进件通知
            AuditCallbackInfo callbackInfo = JSONObject.parseObject(urm.toString(), AuditCallbackInfo.class);
            LambdaQueryWrapper<MerchantChannelStatus> qWrapper = Wrappers.lambdaQuery();
            qWrapper.eq(MerchantChannelStatus::getApplicationId, callbackInfo.getSysFlowId())
                    .eq(MerchantChannelStatus::getChannel, 4);
            mcs = mcsService.getOne(qWrapper);

            if ("00".equals(status)) {
                // 进件成功
                ((AbstractYsResultService) ysAuditServiceV2).success(urm);
            } else if ("10".equals(status)){
                // 转人工审核，待复审
                mcs.setStatus(MerchantChannelStatus.AUDIT_STATUS_ARTIFICIAL_EXAMINING);
                mcsService.updateById(mcs);
            } else if ("20".equals(status)) {
                // 审核通过，待签约
                ((MerchProtocolService) ysAuditServiceV2).reqMerProtocolStatus(mcs);
            } else {
                // 进件驳回
                ((AbstractYsResultService) ysAuditServiceV2).fail(urm);
            }
        }

        if (Objects.equals(notifyType, "01")) {
            // 报备通知
            JSONObject report = auditResult.getJSONObject("report");
            AuditCallbackInfo callbackInfo = JSONObject.parseObject(report.toString(), AuditCallbackInfo.class);
            LambdaQueryWrapper<MerchantChannelStatus> qWrapper = Wrappers.lambdaQuery();
            qWrapper.eq(MerchantChannelStatus::getApplicationId, callbackInfo.getSysFlowId())
                    .eq(MerchantChannelStatus::getChannel, 4);
            mcs = mcsService.getOne(qWrapper);

            if ("00".equals(status)) {
                String thridMercList = callbackInfo.getThridMercList();
                JSONArray objects = JSON.parseArray(thridMercList);
                ((AbstractYsResultService) ysAuditServiceV2)
                        .collectSubMerId(objects, mcs.getMerchantId());
            } else {
                LambdaQueryWrapper<UserApp> qWrapper2 = Wrappers.lambdaQuery();
                qWrapper2.eq(UserApp::getMerchantCode, mcs.getMerchantCode());
                qWrapper2.eq(UserApp::getUserType, "promoter");
                UserApp userApp = userAppMapper.selectOne(qWrapper2);
                String pushMsg = "D0通道报备失败，请联系客服进行处理";
                sxfMerAuditHandler.sendNotice(userApp, "收银呗审核通知", pushMsg, mcs.getApplicationId());
            }
        }

        if (Objects.equals(notifyType, "02")) {
            JSONObject change = auditResult.getJSONObject("change");
            String changeFlowId = change.getString("changeFlowId");
            String nogoRemark = change.getString("nogoRemark");

            LambdaQueryWrapper<MerchantRateNewRecord> qWrapper = Wrappers.lambdaQuery();
            qWrapper.eq(MerchantRateNewRecord::getRemark, changeFlowId);
            MerchantRateNewRecord mrnr = mrnrService.getOne(qWrapper);
            if (mrnr != null) {
                // 费率变更
                if ("00".equals(status)) {
                    //费率变更成功
                    mrnrService.onSuccess(mrnr);
                } else {
                    // 费率变更失败
                    mrnrService.onFail(mrnr);
                }

                return null;
            }

            // 变更通知
            mcs = mcsMapper.selectByChangeFlowId(changeFlowId);

            if (mcs != null) {
                // 结算卡变更
                if ("00".equals(status)) {
                    // 结算卡变更成功
                    accountService.editSuccess(mcs, Account.CHANNEL_TYPE_D0);
                } else {
                    // 结算卡变更失败
                    accountService.editFail(mcs, changeFlowId + "_" + System.currentTimeMillis(), nogoRemark, Account.CHANNEL_TYPE_D0);
                }

                return mcs;
            }
        }

        return mcs;
    }

    @Override
    public void afterAudit(JSONObject auditResult) {

    }
}
