package cn.pluss.platform.job;

import cn.pluss.platform.SubMerchantApplyOrderService;
import cn.pluss.platform.channel.MerchantCertService;
import cn.pluss.platform.entity.MerchantChannelStatus;
import cn.pluss.platform.entity.MerchantPlugin;
import cn.pluss.platform.entity.SubMerchantApplyOrder;
import cn.pluss.platform.exception.BackDataErrorException;
import cn.pluss.platform.mapper.MerchantChannelStatusMapper;
import cn.pluss.platform.mapper.MerchantPluginMapper;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.service.UnknownExceptionService;
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.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * 定时任务放到后台管理进程，减轻app后台服务的压力
 * 微信认证工单状态等信息查询
 *
 * @author DJH
 */
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "scheduling", name = "enabled", havingValue = "true")
public class CheckWxCertStatusJob {


    @Setter(onMethod_ = {@Autowired})
    private MerchantCertService sxfCertService;

    @Setter(onMethod_ = {@Autowired})
    private MerchantCertService ryxCertService;

    @Setter(onMethod_ = {@Autowired})
    private MerchantCertService ysCertService;

    @Setter(onMethod_ = {@Autowired})
    private MerchantCertService ysCertV2Service;

    @Setter(onMethod_ = {@Autowired})
    private MerchantChannelStatusMapper merchantChannelStatusMapper;

    @Setter(onMethod_ = {@Autowired})
    private MerchantPluginMapper merchantPluginMapper;

    @Setter(onMethod_ = {@Autowired})
    private SubMerchantApplyOrderService subMerchantApplyOrderService;

    @Setter(onMethod_ = {@Autowired})
    private UnknownExceptionService unknownExceptionService;

    @Autowired
    private MerchantChannelStatusService mcsService;

    /**
     * 3分钟跑一次定时任务
     */
    @Scheduled(fixedDelay = 3 * 60 * 1000)
    public void checkWxCert() {
        checkSxfCertStatus();
//
        checkRyxCertStatus();

        checkRyxPluginCertStatus();
//
        checkYsCertStatus();

        checkNoCertMerchant();

    }

    /**
     * 3分钟跑一次定时任务
     */
    @Scheduled(fixedDelay = 3 * 60 * 1000)
    public void checkWxAuthStatusRecent() {
        log.info("=====查询最近一百条商户微信授权状态开始=====");
        MerchantChannelStatus mcs = new MerchantChannelStatus();
        mcs.setAuthorizationStatus(MerchantChannelStatus.AUTHORIZATION_STATUS_UNAUTHORIZED);
        mcs.setStatus(MerchantChannelStatus.AUDIT_STATUS_SUCCESS);

        QueryWrapper<MerchantChannelStatus> qWrapper = new QueryWrapper<>(mcs).orderByDesc("createTime");
        qWrapper.isNotNull("applicationId").last("limit 100");
        List<MerchantChannelStatus> mcsList = merchantChannelStatusMapper.selectList(qWrapper);

        for (MerchantChannelStatus item: mcsList) {
            try {
                mcsService.verifyWxAuthStatus(item);
            } catch (Exception ignored) {}

        }

        log.info("=====查询最近一百条商户微信授权状态结束=====");
    }

    /**
     * 3分钟跑一次定时任务
     */
    @Scheduled(fixedDelay = 3 * 60 * 1000)
    public void checkWxAuthStatus() {
        log.info("=====查询商户微信授权状态开始=====");
        MerchantChannelStatus mcs = new MerchantChannelStatus();
        mcs.setAuthorizationStatus(MerchantChannelStatus.AUTHORIZATION_STATUS_UNAUTHORIZED);
        mcs.setStatus(MerchantChannelStatus.AUDIT_STATUS_SUCCESS);

        QueryWrapper<MerchantChannelStatus> qWrapper = new QueryWrapper<>(mcs).orderByDesc("createTime");
        qWrapper.isNotNull("applicationId");
        List<MerchantChannelStatus> mcsList = merchantChannelStatusMapper.selectList(qWrapper);

        for (MerchantChannelStatus item: mcsList) {
            try {
                mcsService.verifyWxAuthStatus(item);
            } catch (Exception ignored) {}

        }

        log.info("=====查询商户微信授权状态结束=====");
    }

    private void checkSxfCertStatus() {
        log.info("=====查询随行付商户微信认证状态结果开始=====");
        // step 1、查询状态为待处理的工单
        SubMerchantApplyOrder condition = new SubMerchantApplyOrder()
                .setStatus("0")
                .setChannelId(1)
                .setSubMchType("WX");
        List<SubMerchantApplyOrder> orderList = subMerchantApplyOrderService.list(
                new QueryWrapper<>(condition).isNotNull("applyNo")
                        .ne("applyNo", ""));
        if (orderList == null || orderList.isEmpty()) {
            log.info("=====没有需要处理的微信工单=====");
            log.info("=====查询随行付商户微信认证状态结果结束=====");
            return;
        }

        List<String> merchantCodeList = new ArrayList<>();
        for (SubMerchantApplyOrder subMerchantApplyOrder : orderList) {
            merchantCodeList.add(subMerchantApplyOrder.getMerchantCode());
        }

        // 查询对应商户进件信息列表
        QueryWrapper<MerchantChannelStatus> queryWrapper = new QueryWrapper<MerchantChannelStatus>().eq("channel", 1);
        queryWrapper.in("merchantCode", merchantCodeList);
        List<MerchantChannelStatus> merchantChannelStatusList = merchantChannelStatusMapper.selectList(queryWrapper);

        // step 2、查询对应工单的结果
        for (SubMerchantApplyOrder subMerchantApplyOrder : orderList) {
            String wxApplyNo = subMerchantApplyOrder.getApplyNo();
            String merchantCode = subMerchantApplyOrder.getMerchantCode();

            Iterator<MerchantChannelStatus> iterator = merchantChannelStatusList.iterator();
            MerchantChannelStatus merchantChannelStatus = null;
            // 获取对应商户进件信息
            while (iterator.hasNext()) {
                MerchantChannelStatus next = iterator.next();
                if (next.getMerchantCode().equals(merchantCode)) {
                    merchantChannelStatus = next;
                    iterator.remove();
                    break;
                }
            }

            if (merchantChannelStatus == null) {
                BackDataErrorException dataErrorException = new BackDataErrorException("商户实名工单无对应的微信进件信息");
                unknownExceptionService.save(dataErrorException);
                continue;
            }

            sxfCertService.wxCertResult(merchantChannelStatus.getMerchantId(), wxApplyNo);
        }

        log.info("=====查询随行付商户微信认证状态结果结束=====");
    }

    private void checkRyxCertStatus() {
        log.info("=====查询瑞银信商户微信认证状态结果开始=====");
        List<MerchantChannelStatus> noCertMerchantList = merchantChannelStatusMapper.getRyxNoCertMerchant();

        for (MerchantChannelStatus noCertMerchant : noCertMerchantList) {
            try {
                ryxCertService.wxCertResult(noCertMerchant.getMerchantId(), null);
            } catch (Exception e) {
                log.error("=====商户【" + noCertMerchant.getMerchantCode() + "】获取微信认证信息错误=====");
                e.printStackTrace();
            }
        }

        log.info("=====查询瑞银信商户微信认证状态结果结束=====");
    }

    private void checkRyxPluginCertStatus() {
        log.info("=====查询瑞银信-商服宝商户微信认证状态结果开始=====");
        List<MerchantPlugin> noCertPluginList = merchantPluginMapper.getRyxNoCertMerchant();

        for (MerchantPlugin noCertMerchant : noCertPluginList) {
            try {
                ryxCertService.wxCertResult(noCertMerchant.getPluginId(), null);
            } catch (Exception e) {
                log.error("=====商户【" + noCertMerchant.getUserId() + "】获取微信认证信息错误=====");
                e.printStackTrace();
            }
        }

        log.info("=====查询瑞银信-商服宝商户微信认证状态结果结束=====");
    }

    private void checkYsCertStatus() {
        log.info("=====查询银盛商户微信认证状态结果开始=====");
        // step 1、查询状态为待处理的工单
        SubMerchantApplyOrder condition = new SubMerchantApplyOrder().setStatus("0").setChannelId(4).setSubMchType("WX");
        List<SubMerchantApplyOrder> orderList = subMerchantApplyOrderService.list(
                new QueryWrapper<>(condition).isNotNull("applyNo")
                        .ne("applyNo", ""));
        if (orderList == null || orderList.isEmpty()) {
            log.info("=====没有需要处理的微信工单=====");
            log.info("=====查询银盛商户微信认证状态结果结束=====");
            return;
        }

        // step 2、查询对应工单的结果
        for (SubMerchantApplyOrder subMerchantApplyOrder : orderList) {
            String wxApplyNo = subMerchantApplyOrder.getApplyNo();

            try {
                ysCertService.wxCertResult(null, wxApplyNo);
            } catch (Exception e) {
                log.error("=====银盛通道微信工单【" + wxApplyNo + "】获取微信认证信息错误=====");
            }
        }

        // step 2、查询微信认证状态为未认证的商户信息
        LambdaQueryWrapper<MerchantChannelStatus> qWrapper = Wrappers.lambdaQuery();
        qWrapper.eq(MerchantChannelStatus::getChannel, 4)
                .eq(MerchantChannelStatus::getStatus, MerchantChannelStatus.AUDIT_STATUS_SUCCESS)
                .eq(MerchantChannelStatus::getAuthorizationStatus, MerchantChannelStatus.AUTHORIZATION_STATUS_UNAUTHORIZED);

        List<MerchantChannelStatus> mcsList = merchantChannelStatusMapper.selectList(qWrapper);
        for (MerchantChannelStatus mcs : mcsList) {
            if (StringUtils.isNotEmpty(mcs.getApplicationId())) {
                ysCertV2Service.wxCertAuthStatus(mcs.getMerchantId());
            }
        }

        log.info("=====查询银盛商户微信认证状态结果结束=====");
    }

    /**
     * 检查没有微信认证记录的商户
     */
    private void checkNoCertMerchant() {
        log.info("=====查询未进行过实名认证的商户开始=====");
        for (int i = 0; i < 6; i++) {
            List<SubMerchantApplyOrder> applyOrderList = subMerchantApplyOrderService.listNoCertData();
            if (applyOrderList == null || applyOrderList.isEmpty()) {
                break;
            }

            for (SubMerchantApplyOrder applyOrder : applyOrderList) {
                try {
                    if (Objects.equals(applyOrder.getChannelId(), 1)) {
                        sxfCertService.wxCert(applyOrder.getMerchantId(), applyOrder.getMerchantCode());
                    }

                    if (Objects.equals(applyOrder.getChannelId(), 4)) {
                        if (StringUtils.isBlank(applyOrder.getApplyNo())) {
                            ysCertService.wxCert(applyOrder.getMerchantId(), applyOrder.getMerchantCode());
                        } else {
                            ysCertV2Service.wxCert(applyOrder.getMerchantId(), applyOrder.getMerchantCode());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("发起微信实名认证错误, {}", e.getMessage());
                }
            }
        }
        log.info("=====查询未进行过实名认证的商户结束=====");
    }
}
