package com.dxhy.core.task;

import java.util.HashSet;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxhy.core.dao.BasisSysDeptCfgDao;
import com.dxhy.core.entity.BasisSysDeptCfg;
import com.dxhy.core.job.entity.ScheduleJobEntity;
import com.dxhy.core.job.service.ScheduleJobService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.core.dao.ConfirmDao;
import com.dxhy.core.job.entity.TAcOrg;
import com.dxhy.core.job.pojo.InvoiceHandle;
import com.dxhy.core.job.service.InvoiceInterfaceService;
import com.dxhy.core.job.thread.InvoiceParseHandle;
import com.dxhy.core.job.thread.InvoiceStateHandle;
import com.dxhy.core.job.thread.SelectInvoiceHandle;

import lombok.extern.slf4j.Slf4j;

/**
 * @author fth
 * @date 2018年04月13日 下午10:57:22
 */
@SuppressWarnings({"rawtypes", "DuplicatedCode"})
@Component("invoiceInterfaceTask")
@Slf4j

public class InvoiceInterfaceTask {
    @Value("${jxjk.threadNum}")
    private Integer threadNum;
    @Value("${jxjk.invoiceParam}")
    private String invoiceParam;
    @Resource
    private InvoiceInterfaceService invoiceInterfaceService;
    @Resource
    private ConfirmDao confirmDao;
    @Resource
    private ScheduleJobService scheduleJobService;
    @Resource
    private BasisSysDeptCfgDao basisSysDeptCfgDao;
    /**
     * 核心线程池大小
     */
    private int corePoolSize = 10;
    /**
     * 最大线程池大小
     */

    private int maximumPoolSize = 20;

    /**
     * @throws InterruptedException
     *             异常
     * @Desc 发票获取接口
     */

    public void getInvoices() throws InterruptedException {
        log.info("发票获取接口执行开始-");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity = scheduleJobService.queryByBeanName("invoiceInterfaceTask", "getInvoices");
        if (scheduleJobEntity != null && "0".equals(scheduleJobEntity.getJobStatus())) {
            try {
                scheduleJobEntity.setJobStatus("1");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
                // 准备请求参数
                // 需判断 设置不认证状态
                List<TAcOrg> list = invoiceInterfaceService.getTaxnoForQpm();
                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()));
                    HashSet<String> set = new HashSet();
                    set.add("01");
                    set.add("03");
                    set.add("14");
                    set.add("08");
                    set.add("31");
                    for (TAcOrg org : list) {
                        for (String type : set) {
                            String taxno = org.getTaxno();
                            String db = org.getDbName();
                            String aceId = org.getAceId();
                            String aceKey = org.getAceKey();
                            String company = org.getCompany();
                            DynamicContextHolder.push(DbConstant.BASICS_READ);
                            //判断是否为大企业税号
                            BasisSysDeptCfg baseSysDeptCfg = basisSysDeptCfgDao.selectOne(new QueryWrapper<BasisSysDeptCfg>().eq("nsrsbh", taxno));
                            if (baseSysDeptCfg == null) {
                                if (!threadPoolExecutor.isShutdown()) {
                                    threadPoolExecutor.execute(new InvoiceHandle(type, taxno, db, aceId, aceKey, company));
                                }
                            }
                        }
                    }
                    threadPoolExecutor.shutdown();
                    threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS);
                }
                log.info("发票获取接口执行结束--");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                log.info("发票获取接口--重置执行状态");
                scheduleJobEntity.setJobStatus("0");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
            }
        }
    }

    /**
     * @throws InterruptedException
     *             异常
     * @Desc 发票状态获取接口
     */
    public void getStateInvoice() throws InterruptedException {
        log.info("发票状态获取接口执行开始-");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity =
            scheduleJobService.queryByBeanName("invoiceInterfaceTask", "getStateInvoice");
        if (scheduleJobEntity != null && "0".equals(scheduleJobEntity.getJobStatus())) {
            try {
                scheduleJobEntity.setJobStatus("1");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
                // 准备请求参数
                List<TAcOrg> list = invoiceInterfaceService.getOrgTaxno();

                ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 15, 5, TimeUnit.SECONDS,
                    new LinkedBlockingQueue<>(list.size()), new ThreadPoolExecutor.CallerRunsPolicy());
                for (TAcOrg org : list) {
                    if (!threadPoolExecutor.isShutdown()) {
                        String taxno = org.getTaxno();
                        String db = org.getDbName();
                        String aceId = org.getAceId();
                        String aceKey = org.getAceKey();
                        DynamicContextHolder.push(DbConstant.BASICS_READ);
                        //判断是否为大企业税号
                        BasisSysDeptCfg baseSysDeptCfg = basisSysDeptCfgDao.selectOne(new QueryWrapper<BasisSysDeptCfg>().eq("nsrsbh", taxno));
                        if (baseSysDeptCfg == null) {
                            threadPoolExecutor.execute(new InvoiceStateHandle(taxno, db, aceId, aceKey));
                        }
                    }

                }
                threadPoolExecutor.shutdown();
                threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS);

                log.info("--发票状态获取接口执行结束-");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                log.info("发票状态获取--重置执行状态");
                scheduleJobEntity.setJobStatus("0");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
            }
        }
    }

    /**
     * 勾选发票获取接口
     *
     * @throws InterruptedException
     *             异常
     */
    public void getSelectInvoice() throws InterruptedException {
        log.info("勾选发票获取接口执行开始-");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity =
            scheduleJobService.queryByBeanName("invoiceInterfaceTask", "getSelectInvoice");
        if (scheduleJobEntity != null && "0".equals(scheduleJobEntity.getJobStatus())) {
            try {
                scheduleJobEntity.setJobStatus("1");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
                // 准备请求参数
                DynamicContextHolder.push(DbConstant.BASICS_READ);
                List<TAcOrg> list = invoiceInterfaceService.getOrgTaxno();
                ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 15, 5, TimeUnit.SECONDS,
                    new LinkedBlockingQueue<>(list.size()), new ThreadPoolExecutor.CallerRunsPolicy());
                for (TAcOrg org : list) {
                    if (!threadPoolExecutor.isShutdown()) {
                        String taxno = org.getTaxno();
                        String db = org.getDbName();
                        String aceId = org.getAceId();
                        String aceKey = org.getAceKey();
                        DynamicContextHolder.push(DbConstant.BASICS_READ);
                        //判断是否为大企业税号
                        BasisSysDeptCfg baseSysDeptCfg = basisSysDeptCfgDao.selectOne(new QueryWrapper<BasisSysDeptCfg>().eq("nsrsbh", taxno));
                        if (baseSysDeptCfg == null) {
                            threadPoolExecutor.execute(new SelectInvoiceHandle(taxno, db, aceId, aceKey));
                        }
                    }
                }
                threadPoolExecutor.shutdown();
                threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS);
                log.info("--勾选发票获取接口执行结束-");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                log.info("勾选发票获取--重置执行状态");
                scheduleJobEntity.setJobStatus("0");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
            }
        }
    }

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

    public void parseInvoices() throws InterruptedException {
        log.info("发票解析任务执行开始-");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity =
            scheduleJobService.queryByBeanName("invoiceInterfaceTask", "parseInvoices");
        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 = confirmDao.getDbSource();
                for (String db : dbList) {
                    DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                    List<String> taxnos = invoiceInterfaceService.getNotParseTaxnos("01");
                    if (taxnos != null && taxnos.size() > 0) {
                        for (String taxno : taxnos) {
                            DynamicContextHolder.push(DbConstant.BASICS_READ);
                            //判断是否为大企业税号
                            BasisSysDeptCfg baseSysDeptCfg = basisSysDeptCfgDao.selectOne(new QueryWrapper<BasisSysDeptCfg>().eq("nsrsbh", taxno));
                            if (baseSysDeptCfg == null) {
                                if (!threadPoolExecutor.isShutdown()) {
                                    threadPoolExecutor.execute(new InvoiceParseHandle(taxno, db));
                                }
                            }
                        }
                    }
                }
                threadPoolExecutor.shutdown();
                threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS);
                log.info("发票解析任务执行结束--");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                log.info("发票解析--重置执行状态");
                scheduleJobEntity.setJobStatus("0");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
            }
        }
    }

}
