package com.dxhy.core.task;

import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.core.dao.CoreConfirmDao;
import com.dxhy.core.job.entity.ScheduleJobEntity;
import com.dxhy.core.job.entity.TAcOrg;
import com.dxhy.core.job.service.InvoiceDownService;
import com.dxhy.core.job.service.InvoiceInterfaceService;
import com.dxhy.core.job.service.ScheduleJobService;
import com.dxhy.core.job.thread.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author fth
 * @date 2021年01月28日 下午10:57:22
 */
@SuppressWarnings({"rawtypes", "DuplicatedCode"})
@Component("invoiceDownTask")
@Slf4j
public class InvoiceDownTask {
    @Value("${jxjk.jxInvoiceDownType}")
    private String jxInvoiceDownType;
    @Value("${jxjk.xxInvoiceDownType}")
    private String xxInvoiceDownType;
    @Resource
    private InvoiceInterfaceService invoiceInterfaceService;
    @Resource
    private ScheduleJobService scheduleJobService;
    @Resource
    private CoreConfirmDao coreConfirmDao;
    @Resource
    private InvoiceDownService invoiceDownService;
    /**
     * 核心线程池大小
     */
    private int corePoolSize = 10;
    /**
     * 最大线程池大小
     */

    private int maximumPoolSize = 20;

    /**
     * @throws InterruptedException
     *             异常
     * @Desc 发票获取接口
     */
    public void getDownXxInvoice() throws InterruptedException {
        log.info("发票下载销项获取接口执行开始-");
        List<TAcOrg> list = invoiceInterfaceService.getTaxnoForDown();
        if (list != null && list.size() > 0) {
            ThreadPoolExecutor threadPoolExecutor =
                new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 60L, TimeUnit.SECONDS,
                    new LinkedBlockingQueue<Runnable>(list.size() * 4), r -> new Thread(r, "发票下载获取接口-" + r.hashCode()));

            for (TAcOrg org : list) {
                threadPoolExecutor.execute(new InvoiceDownHandle(org.getTaxno(), org.getDbName(), org.getAceId(),
                    org.getAceKey(), xxInvoiceDownType, org.getCompany(), "2"));
            }
            threadPoolExecutor.shutdown();
            threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS);
        }
        log.info("发票下载销项获取接口执行结束--");

    }

    /**
     * @throws InterruptedException
     *             异常
     * @Desc 发票获取接口
     */
    public void getDownJxInvoice() throws InterruptedException {
        log.info("发票下载进项获取接口执行开始-");
        List<TAcOrg> list = invoiceInterfaceService.getTaxnoForDown();
        if (list != null && list.size() > 0) {
            ThreadPoolExecutor threadPoolExecutor =
                new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 60L, TimeUnit.SECONDS,
                    new LinkedBlockingQueue<Runnable>(list.size() * 4), r -> new Thread(r, "发票下载获取接口-" + r.hashCode()));

            for (TAcOrg org : list) {
                threadPoolExecutor.execute(new InvoiceDownHandle(org.getTaxno(), org.getDbName(), org.getAceId(),
                    org.getAceKey(), jxInvoiceDownType, org.getCompany(), "1"));
            }
            threadPoolExecutor.shutdown();
            threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS);
        }
        log.info("发票下载进项获取接口执行结束--");

    }

    /**
     * @throws InterruptedException
     *             异常
     * @Desc 发票下载获取--解析定时任务
     */

    public void parseDownInvoices() throws InterruptedException {
        log.info("发票解析任务执行开始-");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity =
            scheduleJobService.queryByBeanName("invoiceDownTask", "parseDownInvoices");
        if (scheduleJobEntity != null && "0".equals(scheduleJobEntity.getJobStatus())) {
            try {
                scheduleJobEntity.setJobStatus("1");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
                // 准备请求参数
                ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 15, 5, TimeUnit.SECONDS,
                    new LinkedBlockingQueue<>(30), new ThreadPoolExecutor.CallerRunsPolicy());
                // 查询数据库 遍历数据源
                DynamicContextHolder.push(DbConstant.BASICS_READ);
                List<String> dbList = coreConfirmDao.getDbSource();
                for (String db : dbList) {
                    DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                    List<String> taxnos = invoiceDownService.getNoParse();
                    if (taxnos != null && taxnos.size() > 0) {
                        for (String taxno : taxnos) {
                            if (!threadPoolExecutor.isShutdown()) {
                                threadPoolExecutor.execute(new InvoiceDownParseHandle(taxno, db));
                            }
                        }

                    }
                }
                threadPoolExecutor.shutdown();
                threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS);
                log.info("发票解析任务执行结束--");
            } catch (Exception e) {
               log.info("业务处理异常：{}", e);
            } finally {
                log.info("发票解析--重置执行状态");
                scheduleJobEntity.setJobStatus("0");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
            }
        }
    }
}
