package com.dxhy.core.task;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxhy.api.model.config.CollectionControlModel;
import com.dxhy.api.model.config.sys.SysEnterpriseConfigEntity;
import com.dxhy.api.model.config.sys.SysGroupConfigEntity;
import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.core.dao.CoreConfirmDao;
import com.dxhy.core.dao.CoreSysEnterpriseConfigCoreDao;
import com.dxhy.core.job.entity.ScheduleJobEntity;
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.service.ScheduleJobService;
import com.dxhy.core.job.thread.*;
import com.dxhy.jxpt.baseService.config.dao.SysGroupConfigDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

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

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

public class InvoiceInterfaceTask {
    @Resource
    private InvoiceInterfaceService invoiceInterfaceService;
    @Resource
    private CoreConfirmDao coreConfirmDao;
    @Resource
    private ScheduleJobService scheduleJobService;

    @Resource
    private CoreSysEnterpriseConfigCoreDao coreSysEnterpriseConfigCoreDao;

    @Resource
    private SysGroupConfigDao sysGroupConfigDao;

    /**
     * 数据类型01进项增值税发票归集 02 销项增值税发票归集
     */
    private static List<String> sjlx = new ArrayList<>();

    static {
        sjlx.add("01");
        sjlx.add("02");
    }

    /**
     * 核心线程池大小
     */
    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");

                    set.add("161");
                    set.add("183");
                    set.add("185");
                    set.add("283");

                    set.add("383");//数电票（机动车销售统一发票）
                    set.add("187");//数电纸票（机动车销售统一发票）
                    log.info("支持票种：{}",set);

                    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);
                            //判断是否为大企业税号
                            SysEnterpriseConfigEntity sysEnterpriseConfigEntity = coreSysEnterpriseConfigCoreDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", org.getTaxno()));
                            if (ObjectUtil.isNotEmpty(sysEnterpriseConfigEntity)&&"0".equals(sysEnterpriseConfigEntity.getJrfs())) {
                                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) {
               log.info("业务处理异常：{}", e);
            } 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);
                        //判断是否为大企业税号
                        SysEnterpriseConfigEntity sysEnterpriseConfigEntity = coreSysEnterpriseConfigCoreDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", org.getTaxno()));
                        if (ObjectUtil.isNotEmpty(sysEnterpriseConfigEntity)&&"0".equals(sysEnterpriseConfigEntity.getJrfs())) {
                            threadPoolExecutor.execute(new InvoiceStateHandle(taxno, db, aceId, aceKey));
                        }
                    }

                }
                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);
            }
        }
    }

    /**
     * 勾选发票获取接口
     *
     * @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();
                if (!CollectionUtils.isEmpty(list)) {
                    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);
                            //判断是否为大企业税号
                            SysEnterpriseConfigEntity sysEnterpriseConfigEntity = coreSysEnterpriseConfigCoreDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", org.getTaxno()));
                            if (ObjectUtil.isNotEmpty(sysEnterpriseConfigEntity) && "0".equals(sysEnterpriseConfigEntity.getJrfs())) {
                                threadPoolExecutor.execute(new SelectInvoiceHandle(taxno, db, aceId, aceKey));
                            }
                        }
                    }
                    threadPoolExecutor.shutdown();
                    threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS);
                } else {
                    log.info("未查询到税号");
                }

                log.info("--勾选发票获取接口执行结束-");
            } catch (Exception e) {
               log.info("业务处理异常：{}", e);
            } 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 = coreConfirmDao.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);
                            //判断是否为大企业税号
                            SysEnterpriseConfigEntity sysEnterpriseConfigEntity = coreSysEnterpriseConfigCoreDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", taxno));
                            if (ObjectUtil.isNotEmpty(sysEnterpriseConfigEntity)&&"0".equals(sysEnterpriseConfigEntity.getJrfs())) {
                                if (!threadPoolExecutor.isShutdown()) {
                                    threadPoolExecutor.execute(new InvoiceParseHandle(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);
            }
        }
    }


    /**
     * 数电发票源文件获取定时任务-进项
     * 武汉地区不支持
     * @throws
     */
    public void getSdpYwjTask() throws Exception {
        log.info("数电(进项)发票源文件获取定时任务执行开始-");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity = scheduleJobService.queryByBeanName("invoiceInterfaceTask", "getSdpYwjTask");
        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()));

                    for (TAcOrg org : list) {
                            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);

                            /*//判断是否为大企业税号
                            SysEnterpriseConfigEntity sysEnterpriseConfigEntity = coreSysEnterpriseConfigCoreDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", org.getTaxno()));
                            if (ObjectUtil.isNotEmpty(sysEnterpriseConfigEntity)&&"0".equals(sysEnterpriseConfigEntity.getJrfs())) {

                            }*/

                            //判断集团是否开启源文件采集
                            boolean openDownLoadSourceFile = isOpenDownLoadSourceFile(org.getTaxno());
                            if(!openDownLoadSourceFile){
                                log.info("税号{}所属集团未开启源文件采集",org.getTaxno());
                                continue;
                            }

                            if (!threadPoolExecutor.isShutdown()) {
                                //jxxxType 01 进项  02 销项
                                threadPoolExecutor.execute(new SdpYwjHandle(taxno, db, aceId, aceKey, company,"01"));
                            }
                    }
                    threadPoolExecutor.shutdown();
                    threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS);
                }
                log.info("数电(进项)发票源文件获取定时任务执行结束--");
            } catch (Exception e) {
                log.debug("数电(进项)发票源文件获取定时任务执行异常：{}", e);
            } finally {
                log.info("数电(进项)发票源文件获取定时任务执行完成--重置执行状态");
                scheduleJobEntity.setJobStatus("0");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
            }
        }
    }


    /**
    * @Description 数电发票源文件获取定时任务 --销项
     * 武汉地区不支持
    * @param
    * @Author wangruwei
    * @Date 2024/4/20 13:50
    **/
    public void getXxSdpYwjTask() throws Exception {
        log.info("数电(销项)发票源文件获取定时任务执行开始-");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity = scheduleJobService.queryByBeanName("invoiceInterfaceTask", "getXxSdpYwjTask");
        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()));

                    for (TAcOrg org : list) {
                        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);

                            /*//判断是否为大企业税号
                            SysEnterpriseConfigEntity sysEnterpriseConfigEntity = coreSysEnterpriseConfigCoreDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", org.getTaxno()));
                            if (ObjectUtil.isNotEmpty(sysEnterpriseConfigEntity)&&"0".equals(sysEnterpriseConfigEntity.getJrfs())) {

                            }*/
                        //判断集团是否开启源文件采集
                        boolean openDownLoadSourceFile = isOpenDownLoadSourceFile(org.getTaxno());
                        if(!openDownLoadSourceFile){
                            log.info("税号{}所属集团未开启源文件采集",org.getTaxno());
                            continue;
                        }


                        if (!threadPoolExecutor.isShutdown()) {
                            //jxxxType 01 进项  02 销项
                            threadPoolExecutor.execute(new SdpYwjHandle(taxno, db, aceId, aceKey, company,"02"));
                        }
                    }
                    threadPoolExecutor.shutdown();
                    threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS);
                }
                log.info("数电(销项)发票源文件获取定时任务执行结束--");
            } catch (Exception e) {
                log.debug("数电(销项)发票源文件获取定时任务执行异常：{}", e);
            } finally {
                log.info("数电(销项)发票源文件获取定时任务执行完成--重置执行状态");
                scheduleJobEntity.setJobStatus("0");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
            }
        }
    }



    /**
     * 进项增值税普票归集任务
     * @throws
     */
    public void jxZzsfpgjTask() throws Exception {
        log.info("进项增值税普票归集任务执行开始-");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity = scheduleJobService.queryByBeanName("invoiceInterfaceTask", "jxZzsfpgjTask");
        if (scheduleJobEntity != null && "0".equals(scheduleJobEntity.getJobStatus())) {
            try {
                scheduleJobEntity.setJobStatus("1");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);

                // 准备请求参数
                // 需判断 设置不认证状态
                List<CollectionControlModel> list = coreSysEnterpriseConfigCoreDao.getDqyTaxNo();
                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()));

                    list.stream().forEach(ccm->{
                        if (!threadPoolExecutor.isShutdown()) {
                            //type 1-进项数据 2-销项数据
                            threadPoolExecutor.execute(new ZzsfpgjHandle(ccm,"1"));
                        }
                    });
                    threadPoolExecutor.shutdown();
                    threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS);
                }
                log.info("进项增值税普票归集任务任务执行结束--");
            } catch (Exception e) {
                log.debug("进项增值税普票归集任务任务执行异常：{}", e);
            } finally {
                log.info("进项增值税普票归集任务执行完成--重置执行状态");
                scheduleJobEntity.setJobStatus("0");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
            }
        }
    }

    /**
     * 销项增值税普票归集任务
     * @throws
     */
    public void xxZzsfpgjTask() throws Exception {
        log.info("销项增值税普票归集任务执行开始-");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity = scheduleJobService.queryByBeanName("invoiceInterfaceTask", "xxZzsfpgjTask");
        if (scheduleJobEntity != null && "0".equals(scheduleJobEntity.getJobStatus())) {
            try {
                scheduleJobEntity.setJobStatus("1");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);

                // 准备请求参数
                // 需判断 设置不认证状态
                List<CollectionControlModel> list = coreSysEnterpriseConfigCoreDao.getDqyTaxNo();
                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()));

                    list.stream().forEach(ccm->{
                        if (!threadPoolExecutor.isShutdown()) {
                            //type 1-进项数据 2-销项数据
                            threadPoolExecutor.execute(new ZzsfpgjHandle(ccm,"2"));
                        }
                    });
                    threadPoolExecutor.shutdown();
                    threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS);
                }
                log.info("销项增值税普票归集任务任务执行结束--");
            } catch (Exception e) {
                log.debug("销项增值税普票归集任务任务执行异常：{}", e);
            } finally {
                log.info("销项增值税普票归集任务执行完成--重置执行状态");
                scheduleJobEntity.setJobStatus("0");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
            }
        }
    }



    /**
     * 增值税普票归集结果解析
     * @throws
     */
    public void jxZzsfpgjjgjxTask() throws Exception {
        log.info("增值税普票归集结果解析任务执行开始-");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity = scheduleJobService.queryByBeanName("invoiceInterfaceTask", "jxZzsfpgjjgjxTask");
        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()));

                    for (TAcOrg org : list) {
                        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);
                        //判断是否为大企业税号
                        SysEnterpriseConfigEntity sysEnterpriseConfigEntity = coreSysEnterpriseConfigCoreDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", org.getTaxno()));
                        if (ObjectUtil.isNotEmpty(sysEnterpriseConfigEntity)&&"0".equals(sysEnterpriseConfigEntity.getJrfs())) {
                            if (!threadPoolExecutor.isShutdown()) {
                                // 01 进项增值税发票归集 02 销项增值税发票归集
                                sjlx.stream().forEach(sjlx->{
                                    threadPoolExecutor.execute(new ZzsfpgjjgjxHandle(sjlx,taxno, db, aceId, aceKey, company));
                                });
                            }
                        }
                    }
                    threadPoolExecutor.shutdown();
                    threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS);
                }
                log.info("增值税普票归集结果解析任务执行结束--");
            } catch (Exception e) {
                log.debug("增值税普票归集结果解析任务执行异常：{}", e);
            } finally {
                log.info("增值税普票归集结果解析任务执行完成--重置执行状态");
                scheduleJobEntity.setJobStatus("0");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
            }
        }
    }


    /**
     * @Description 数电发票源文件获取定时任务 新版 --进项
     * @param
     * @Author wangruwei
     * @Date 2024/4/20 13:50
     **/
    public void getJxSdpYwjNewTask() throws Exception {
        log.info("数电(进项)发票源文件获取-新版-定时任务执行开始-");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity = scheduleJobService.queryByBeanName("invoiceInterfaceTask", "getJxSdpYwjNewTask");
        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()));

                    for (TAcOrg org : list) {
                        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);

                        //判断集团是否开启源文件采集
                        boolean openDownLoadSourceFile = isOpenDownLoadSourceFile(org.getTaxno());
                        if(!openDownLoadSourceFile){
                            log.info("税号{}所属集团未开启源文件采集",org.getTaxno());
                            continue;
                        }

                        if (!threadPoolExecutor.isShutdown()) {
                            //jxxxType 01 进项  02 销项
                            threadPoolExecutor.execute(new SdpYwjNewHandle(taxno, db, aceId, aceKey, company,"01"));
                        }
                    }
                    threadPoolExecutor.shutdown();
                    threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS);
                }
                log.info("数电(进项)发票源文件获取-新版-定时任务执行结束--");
            } catch (Exception e) {
                log.debug("数电(进项)发票源文件获取-新版-定时任务执行异常：{}", e);
            } finally {
                log.info("数电(进项)发票源文件获取-新版-定时任务执行完成--重置执行状态");
                scheduleJobEntity.setJobStatus("0");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
            }
        }
    }

    /**
     * @Description 数电发票源文件获取定时任务 新版 --销项
     * @param
     * @Author wangruwei
     * @Date 2024/4/20 13:50
     **/
    public void getJxSdpYwjXxNewTask() throws Exception {
        log.info("数电(销项)发票源文件获取-新版-定时任务执行开始-");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity = scheduleJobService.queryByBeanName("invoiceInterfaceTask", "getJxSdpYwjXxNewTask");
        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()));

                    for (TAcOrg org : list) {
                        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);

                        //判断集团是否开启源文件采集
                        boolean openDownLoadSourceFile = isOpenDownLoadSourceFile(org.getTaxno());
                        if(!openDownLoadSourceFile){
                            log.info("税号{}所属集团未开启源文件采集",org.getTaxno());
                            continue;
                        }

                        if (!threadPoolExecutor.isShutdown()) {
                            //jxxxType 01 进项  02 销项
                            threadPoolExecutor.execute(new SdpYwjNewHandle(taxno, db, aceId, aceKey, company,"02"));
                        }
                    }
                    threadPoolExecutor.shutdown();
                    threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS);
                }
                log.info("数电(销项)发票源文件获取-新版-定时任务执行结束--");
            } catch (Exception e) {
                log.debug("数电(销项)发票源文件获取-新版-定时任务执行异常：{}", e);
            } finally {
                log.info("数电(销项)发票源文件获取-新版-定时任务执行完成--重置执行状态");
                scheduleJobEntity.setJobStatus("0");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
            }
        }
    }


    /**
    * @Description 判断是否开启源文件采集---true已开启    false未开启
    * @param taxno
    * @Return void
    * @Author wangruwei
    * @Date 2024/6/12 15:27
    **/
    private boolean isOpenDownLoadSourceFile(String taxno) {
        SysEnterpriseConfigEntity sysEnterpriseConfigEntity = coreSysEnterpriseConfigCoreDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", taxno));
        SysGroupConfigEntity sysGroupConfigEntity = sysGroupConfigDao.selectOne(new LambdaQueryWrapper<SysGroupConfigEntity>().eq(SysGroupConfigEntity::getCompany, sysEnterpriseConfigEntity.getCompany()));
        if (ObjectUtil.isNotEmpty(sysGroupConfigEntity)&&"0".equals(sysGroupConfigEntity.getSfxzywj())) {
            return false;
        }
        return true;
    }

}
