package com.jeequan.jeepay.pay.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeequan.jeepay.components.mq.model.MchAuditMQ;
import com.jeequan.jeepay.components.mq.vender.IMQSender;
import com.jeequan.jeepay.converter.MchInfoConverter;
import com.jeequan.jeepay.core.entity.MchModifyApplyment;
import com.jeequan.jeepay.core.interfaces.paychannel.IIsvmchModifyApplymentService;
import com.jeequan.jeepay.core.utils.JeepayKit;
import com.jeequan.jeepay.core.utils.SpringBeansUtil;
import com.jeequan.jeepay.db.entity.MchApplyment;
import com.jeequan.jeepay.db.entity.MchModifyApplymentEntity;
import com.jeequan.jeepay.service.impl.MchApplymentService;
import com.jeequan.jeepay.service.impl.MchModifyApplymentService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.MutablePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 商户进件变更查询定时任务
 *
 * @author zx
 *
 * @date 2022/2/14 10:47
 */
@Slf4j
@Component
public class MchModifyQueryStateTask {

    private static final int QUERY_PAGE_SIZE = 100; //每次查询数量

    @Autowired
    private MchApplymentService mchApplymentService;

    @Autowired
    private MchModifyApplymentService mchModifyApplymentService;

    @Autowired
    private IMQSender mqSender;

    @Autowired
    private MchInfoConverter mchInfoConverter;

    @XxlJob("mchModifyQueryStateTask")
    public void start() {

        // 当前时间 减去7天
        Date offsetDate = DateUtil.offsetDay(new Date(), -7);

        //查询条件： （审核中、待验证、待签约）& 查询7天内的申请单
        LambdaQueryWrapper<MchModifyApplymentEntity> lambdaQueryWrapper = Wrappers.lambdaQuery(MchModifyApplymentEntity.class)
                .in(MchModifyApplymentEntity::getState, MchApplyment.STATE_AUDITING, MchApplyment.STATE_WAIT_VERIFY, MchApplyment.STATE_WAIT_SIGN)
                .ge(MchModifyApplymentEntity::getCreatedAt, offsetDate);

        int currentPageIndex = 1; //当前页码
        while (true) {

            try {
                IPage<MchModifyApplymentEntity> applyMentIPage = mchModifyApplymentService.page(new Page<>(currentPageIndex, QUERY_PAGE_SIZE), lambdaQueryWrapper);

                if (applyMentIPage == null || applyMentIPage.getRecords().isEmpty()) { //本次查询无结果, 不再继续查询;
                    break;
                }

                for (MchModifyApplymentEntity item : applyMentIPage.getRecords()) {
                    this.queryApplyState(item);
                }

                //已经到达页码最大量，无需再次查询
                if (applyMentIPage.getPages() <= currentPageIndex) {
                    break;
                }
                currentPageIndex++;


            } catch (Exception e) { //出现异常，直接退出，避免死循环。
                log.error("error", e);
                break;
            }

        }

        int currentPageIndex2 = 1; //当前页码
        while (true) {
            try {
                DateTime dateTime = DateUtil.offsetMinute(new Date(), 10);
                Page<MchApplyment> pageData = mchApplymentService.lambdaQuery()
                        .eq(MchApplyment::getState, MchApplyment.STATE_AUDITING_WAIT)
                        .le(MchApplyment::getCreatedAt, dateTime)
                        .page(new Page<>(currentPageIndex2, QUERY_PAGE_SIZE));

                pageData.getRecords().forEach(r -> {
                    mqSender.send(MchAuditMQ.build(r.getApplyId()));
                });

                //已经到达页码最大量，无需再次查询
                if (pageData.getPages() <= currentPageIndex) {
                    break;
                }
                currentPageIndex++;
            } catch (Exception e) {
                log.error("error", e);
                break;
            }
        }
    }


    /**
     * 进件状态查询
     **/
    public void queryApplyState(MchModifyApplymentEntity record) {
        MchApplyment mchApplyment = mchApplymentService.getById(record.getApplyId());

        try {

            IIsvmchModifyApplymentService isvmchModifyApplymentService = SpringBeansUtil.getBean(JeepayKit.getIfCodeOrigin(record.getIfCode()) + "IsvmchModifyApplymentService", IIsvmchModifyApplymentService.class);
            if (isvmchModifyApplymentService == null) {
                return;
            }

            // 调起变更结果查询接口
            MutablePair<MchModifyApplyment, com.jeequan.jeepay.core.entity.MchApplyment> queryModifyResult = isvmchModifyApplymentService.queryModifyResult(new MutablePair<>(mchInfoConverter.toModel(record), mchInfoConverter.toModel(mchApplyment)));
            if (queryModifyResult == null) {
                return;
            }

            if (queryModifyResult.left != null) {
                mchModifyApplymentService.updateById(mchInfoConverter.toDbEntity(queryModifyResult.left));
            }

            if (queryModifyResult.right != null) {
                mchApplymentService.updateById(mchInfoConverter.toDbEntity(queryModifyResult.right));
            }
        } catch (Exception e) {  //继续下一次迭代查询
            log.error("error applyId = {}", record.getApplyId(), e);
        }

    }


}
