package cn.pluss.platform.ys.impl;

import cn.pluss.platform.channel.MerchantCertService;
import cn.pluss.platform.entity.MerchantChannelStatus;
import cn.pluss.platform.entity.Notice;
import cn.pluss.platform.entity.SubMerchant;
import cn.pluss.platform.entity.UserApp;
import cn.pluss.platform.mapper.UserAppMapper;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.notice.NoticeService;
import cn.pluss.platform.subMerchant.SubMerchantService;
import cn.pluss.platform.task.IMerAuditHandler;
import cn.pluss.platform.user.impl.GeneralPushUtil;
import cn.pluss.platform.ys.YSConstants;
import cn.pluss.platform.ys.YsConfig;
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.dao.DuplicateKeyException;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Date;
import java.util.Map;

/**
 * 实现进件结果返回的逻辑
 *
 * @author djh
 */
@Slf4j
public abstract class AbYsAuditResultService extends AbYsImgUploadService {

    @Autowired
    protected IMerAuditHandler ysMerAuditHandler;

    @Autowired
    protected MerchantBaseInfoService merchantBaseInfoService;

    @Autowired
    protected MerchantChannelStatusService mcsService;

    @Autowired
    protected MerchantCertService ysCertService;

    @Autowired
    protected YsService ysService;

    @Autowired
    protected MerchantChannelStatusService channelStatusService;

    @Autowired
    protected NoticeService noticeService;

    @Resource
    protected UserAppMapper userAppMapper;

    @Autowired
    protected SubMerchantService smService;

    @Autowired
    private GeneralPushUtil generalPushUtil;


    @Override
    public JSONObject merchantAuditResult(Map<String, Object> result) throws Exception {
        String merchantCode = (String) result.get("merchantCode");
        LambdaQueryWrapper<MerchantChannelStatus> qWrapper = new LambdaQueryWrapper<MerchantChannelStatus>()
                .eq(MerchantChannelStatus::getChannel, 4)
                .eq(MerchantChannelStatus::getMerchantCode, merchantCode);

        MerchantChannelStatus mcs = channelStatusService.getOne(qWrapper);
        if (mcs == null) {
            return null;
        }

        // 获取outMerchantCode
        JSONObject extra = mcs.getExtra();
        if (extra == null) {
            return null;
        }

        String outMerchantCode = extra.getString(YSConstants.MER_CODE);

        JSONObject bizReqJson = new JSONObject();
        bizReqJson.put("outMerchantNo", outMerchantCode);

        JSONObject auditResult = ysService.requestApiCommon(YsConfig.MER_RESULT, bizReqJson, YsService.TYPE_AUDIT);
        String status = auditResult.getString("status");
        String statusMsg = auditResult.getString("statusMeg");
        String merchantId = auditResult.getString("merchantNo");
        if (StringUtils.isEmpty(outMerchantCode)) {
            log.error("查询进件信息异常, {}", statusMsg);
            return null;
        }

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

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

            mcsService.saveOrUpdate(mcs);

            // 现在操作子商户信息
            String wxMerchantNo = auditResult.getString("wxMerchantNo");
            String zfbMerchantNo = auditResult.getString("zfbMerchantNo");
            if (StringUtils.isNotEmpty(wxMerchantNo)) {
                String[] wxMerchNos = wxMerchantNo.split(",");
                for (String wxMerchNo : wxMerchNos) {
                    try {
                        SubMerchant subMerchant = new SubMerchant();
                        subMerchant.setMerchantId(merchantId);
                        subMerchant.setSubMchId(wxMerchNo);
                        subMerchant.setSubMchType("WX");
                        subMerchant.setRemark(statusMsg);
                        subMerchant.setChannelTypeId("4");
                        smService.save(subMerchant);
                    } catch (DuplicateKeyException e) {
                        log.warn("相同的微信子商户号, 不需要重复保存");
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.warn("保存微信子商户号错误");
                    }
                }
            }

            if (StringUtils.isNotEmpty(zfbMerchantNo)) {
                String[] zfbMerchNos = zfbMerchantNo.split(",");
                for (String zfbMerchNo : zfbMerchNos) {
                    try {
                        SubMerchant subMerchant = new SubMerchant();
                        subMerchant.setMerchantId(merchantId);
                        subMerchant.setSubMchId(zfbMerchNo);
                        subMerchant.setSubMchType("ZFB");
                        subMerchant.setRemark(statusMsg);
                        subMerchant.setChannelTypeId("4");
                        smService.save(subMerchant);
                    } catch (DuplicateKeyException e) {
                        log.warn("相同的支付宝子商户号, 不需要重复保存");
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.warn("保存支付宝子商户号错误");
                    }
                }
            }
        } else {
            mcs.setStatus(MerchantChannelStatus.AUDIT_STATUS_REJECT);
            mcs.setRemark(statusMsg);

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

            LambdaQueryWrapper<UserApp> qWrapper2 = new LambdaQueryWrapper<UserApp>().eq(UserApp::getMerchantCode, merchantCode)
                    .eq(UserApp::getUserType, "promoter");
            UserApp userApp = userAppMapper.selectOne(qWrapper2);
            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(mcs);
        }

        return auditResult;
    }

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

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

    @Override
    public void checkSign(JSONObject receiveData) throws Exception {
        // checkSign由ysService提供
    }
}
