package org.jeecg.module.custom.ocr.api.thread;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import org.apache.commons.lang.time.DateFormatUtils;
import org.jeecg.module.custom.ocr.api.PrevailCloudApi;
import org.jeecg.module.custom.ocr.api.entity.FormRecord;
import org.jeecg.module.custom.ocr.api.entity.PictureSourceAllPullMsg;
import org.jeecg.module.custom.ocr.api.entity.PictureSourceParameter;
import org.jeecg.module.custom.ocr.common.entity.ApiPage;
import org.jeecg.module.custom.ocr.config.ApiConfig;
import org.jeecg.module.custom.ocr.service.OcrPrevailCloudLogService;
import org.jeecg.module.custom.ocr.utils.SpringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Instant;
import java.util.Date;

/**
 * 拉取无量云全量任务数据线程
 *
 * @author hugh(shuli.yao) 1397940314@qq.com
 * @version 1.0
 * @date 2024/5/17 16:56
 */
public class PullAllPictureSourceThread implements Runnable{

    protected Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 租户id
     */
    private Long tenantNo;
    /**
     * 业务主体id
     */
    private Long accountNo;
    /**
     * 开始时间
     */
    private DateTime startDate;
    /**
     * 结束时间
     */
    private DateTime endDate;
    /**
     * 执行记录对象
     */
    private PictureSourceAllPullMsg pictureSourceAllPullMsg;

    /**
     * api
     */
    private PrevailCloudApi prevailCloudApi;

    /**
     * api配置类
     */
    private ApiConfig apiConfig;

    /**
     * 初始化方法
     * @param tenantNo
     * @param accountNo
     * @param startDate
     * @param endDate
     * @param pictureSourceAllPullMsg
     */
    public PullAllPictureSourceThread(Long tenantNo, Long accountNo,
                                      DateTime startDate, DateTime endDate,
                                      PictureSourceAllPullMsg pictureSourceAllPullMsg,
                                      PrevailCloudApi prevailCloudApi,
                                      ApiConfig apiConfig) {
        this.tenantNo = tenantNo;
        this.accountNo = accountNo;
        this.startDate = startDate;
        this.endDate = endDate;
        this.pictureSourceAllPullMsg = pictureSourceAllPullMsg;
        this.prevailCloudApi = prevailCloudApi;
        this.apiConfig = apiConfig;
    }

    @Override
    public void run() {
        OcrPrevailCloudLogService ocrPrevailCloudLogService = SpringUtils.getBean("ocrPrevailCloudLogService");

        //记录执行参数
        pictureSourceAllPullMsg.setBeginDateTime(startDate);
        pictureSourceAllPullMsg.setEndDateTime(endDate);
        pictureSourceAllPullMsg.setLock(true);
        pictureSourceAllPullMsg.setAccountNo(accountNo);
        pictureSourceAllPullMsg.setTenantNo(tenantNo);
        //组装固定查询参数
        PictureSourceParameter pictureSourceParameter = new PictureSourceParameter();
        pictureSourceParameter.setTenantNo(tenantNo);
        pictureSourceParameter.setAccountNo(accountNo);

        //1.循环执行
        while(startDate.isBefore(endDate) || startDate.compareTo(endDate) == 0) {
            //初始化页码
            Integer pageNo  = 1;
            Integer pageSize = 200;
            boolean hasNextPage = true;

            //从开始时间,依次递增一天拉取
            Instant startInstant = startDate.toInstant();
            Instant endInstant = startDate.offsetNew(DateField.DAY_OF_YEAR, 1).toInstant();
            pictureSourceParameter.setStartTime(Date.from(startInstant));
            pictureSourceParameter.setEndTime(Date.from(endInstant));

            //记录当前拉取日期
            pictureSourceAllPullMsg.setTimeStr(DateFormatUtils.format(startDate,"yyyy-MM-dd"));
            while (hasNextPage) {
                //组装分页参数
                pictureSourceParameter.setPageNo(pageNo);
                pictureSourceParameter.setPageSize(pageSize);
                //记录当前页码
                pictureSourceAllPullMsg.setPage(pageNo);

                try {
                    //调用无量云api,全量查询方法
                    ApiPage<FormRecord> apiPage = prevailCloudApi.pullPictureSourceAll(pictureSourceParameter);
                    if(apiPage==null){
                        logger.error("批量拉取无量云数据错误,参数:"+pictureSourceParameter);
                        break;
                    }
                    if(apiPage.getRecords()==null || apiPage.getTotal()==0 || apiPage.getTotal()==null){
                        break;
                    }
                    //记录执行日志，总拉取任务数，当前时间区间内任务数
                    pictureSourceAllPullMsg.setPullTaskCount(pictureSourceAllPullMsg.getPullTaskCount()+apiPage.getRecords().size());
                    pictureSourceAllPullMsg.setTimeTaskCount(apiPage.getTotal());
                    //将结果加入队列中。
                    for (FormRecord formRecord : apiPage.getRecords()) {
                        int retryCount = 0;
                        boolean addedToQueue = false;
                        // 将数据放入队列，最多重试5次
                        while (!addedToQueue && retryCount < 5) {
                            addedToQueue = TaskQueue.pictureDisposePushData(formRecord, ocrPrevailCloudLogService);
                            if (!addedToQueue) {
                                Thread.sleep(60000);
                                retryCount++;
                            }
                        }
                    }
                    //翻页
                    hasNextPage = pageNo<Math.ceil((double)apiPage.getTotal()/pageSize);
                    pageNo++;

                    logger.debug("全量拉取中...当前日期:{},页码:{},总数:{}", DateFormatUtils.format(startDate,"yyyy-MM-dd"),pageNo,apiPage.getTotal());
                } catch (Exception e) {
                    logger.error("无量云全量拉取返回错误,error:",e.getMessage());
                    continue;
                }

            }
            //执行下一天数据
            startDate = startDate.offsetNew(DateField.DAY_OF_YEAR, 1);
        }

        //2.执行完毕放开执行锁
        pictureSourceAllPullMsg.reset();
    }
}
