package cn.pluss.platform.task;

import cn.pluss.platform.channel.MerchantAuditService;
import cn.pluss.platform.channel.MerchantCertService;
import cn.pluss.platform.entity.MerchantChannelStatus;
import cn.pluss.platform.entity.Notice;
import cn.pluss.platform.entity.UserApp;
import cn.pluss.platform.notice.NoticeService;
import cn.pluss.platform.user.impl.GeneralPushUtil;
import cn.pluss.platform.ys.YSConstants;
import cn.pluss.platform.ys.YsService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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 org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;

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

    @Autowired
    private GeneralPushUtil generalPushUtil;

    @Autowired
    @Lazy
    protected MerchantCertService ysCertService;

    @Autowired
    @Lazy
    protected MerchantAuditService ysAuditService;

    @Autowired
    @Lazy
    private YsService ysService;

    @Autowired
    @Lazy
    private NoticeService noticeService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MerchantChannelStatus auditCallback(JSONObject auditResult) {
        log.info("=============回调参数=============");
        log.info(auditResult.toJSONString());
        try {
            ysService.checkSign(auditResult);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("=============进件回调参数验签异常=============");
        }

        String bizRespStr = auditResult.getString(YSConstants.BIZ_RESPONSE_JSON);
        JSONObject bizResp = JSONObject.parseObject(bizRespStr);
        String status = bizResp.getString("status");
        String statusMsg = bizResp.getString("statusMeg");
        String outMerchantCode = bizResp.getString(YSConstants.MER_CODE);
        String merchantId = bizResp.getString("merchantNo");
        if (StringUtils.isEmpty(outMerchantCode)) {
            log.info("查询进件信息异常, {}", statusMsg);

            return null;
        }

        String merchantCode = outMerchantCode.substring(0, 19);

        MerchantChannelStatus channelStatus = mcsService.getByMerchantCodeWithChannel(merchantCode, "4");
        if (channelStatus == null) {
            channelStatus = new MerchantChannelStatus();
            channelStatus.setMerchantCode(merchantCode);
        } else {
            if (channelStatus.getStatus().equals(MerchantChannelStatus.AUDIT_STATUS_QUICK_CASH)) {
                return channelStatus;
            }

            if (channelStatus.getStatus().equals(MerchantChannelStatus.AUDIT_STATUS_SUCCESS)) {
                return channelStatus;
            }
        }

        channelStatus.setThirdStatus(status);
        if ("wait".equals(status)) {
            return null;
        }

        // 通过有没有商编来判断是否进件初审状态, 避开待审核状态
        if (StringUtils.isNotBlank(merchantId)) {
            channelStatus.setMerchantId(merchantId);
            channelStatus.setStatus(MerchantChannelStatus.AUDIT_STATUS_QUICK_CASH);
            // 微信认证
            try {
                ysCertService.wxCert(merchantId, merchantCode);
            } catch (Exception e) {
                log.debug("微信认证异常");
                e.printStackTrace();
            }

            mcsService.saveOrUpdate(channelStatus);

            JSONObject param = new JSONObject();
            param.put("merchantCode", merchantCode);
            try {
                ysAuditService.merchantAuditResult(param);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("查询银盛进件信息异常: {}", merchantCode);
            }

            return channelStatus;
        } else {
            channelStatus.setStatus(MerchantChannelStatus.AUDIT_STATUS_REJECT);
            channelStatus.setRemark(statusMsg);

            String pushMsg = "实时到账申请失败";
            if (StringUtils.isNotEmpty(statusMsg)) {
                // 有原因则写，没有则不拼接
                pushMsg += ", 原因：" + statusMsg;
            }

            LambdaQueryWrapper<UserApp> qWrapper = new LambdaQueryWrapper<UserApp>().eq(UserApp::getMerchantCode, merchantCode).eq(UserApp::getUserType, "promoter");
            UserApp userApp = userAppMapper.selectOne(qWrapper);
            Notice notice = new Notice();
            String uniqueKey = "auditReq" + System.currentTimeMillis();
            notice.setNoticeCode(uniqueKey);
            notice.setUniqueKey(uniqueKey);
            notice.setCreateDt(new Date());
            notice.setConrtent(pushMsg);
            notice.setUserId(userApp.getUserId() + "");
            noticeService.saveMerAuthNotice(notice);
            generalPushUtil.sendAllPlatByAlias(Collections.singletonList(userApp.getUserId() + ""), "商家审核通知", pushMsg, "1");

            mcsService.saveOrUpdate(channelStatus);
            return null;
        }
    }

    @Override
    public void afterAudit(JSONObject auditResult) { }
}
