package com.dxhy.core.task;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxhy.api.model.config.sys.SysEnterpriseConfigEntity;
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.pojo.CheckNoDetailInvoice;
import com.dxhy.core.job.service.CheckTaskService;
import com.dxhy.core.job.service.ScheduleJobService;
import com.dxhy.core.thread.CheckThread;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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 hp
 **/
@Component("checkTask")
@Slf4j

public class CheckTask {

    @Resource
    private CheckTaskService checkTaskService;
    @Resource
    private CoreConfirmDao coreConfirmDao;
    @Resource
    private ScheduleJobService scheduleJobService;
    @Resource
    private CoreSysEnterpriseConfigCoreDao coreSysEnterpriseConfigCoreDao;

    public void checkInvoice() {
        log.info("发票查验执行开始--");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity = scheduleJobService.queryByBeanName("checkTask","checkInvoice");
        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<String> dbList = coreConfirmDao.getDbSource();
                for (String db : dbList) {
                    DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                    List<CheckNoDetailInvoice> list = checkTaskService.getNoDetailInvoice();
                    if (list!=null && list.size()>0){
                        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 20, 60, TimeUnit.SECONDS,
                                new LinkedBlockingQueue<>(list.size()), new ThreadPoolExecutor.CallerRunsPolicy());
                        for (CheckNoDetailInvoice checkNoDetailInvoice : list) {
                            if ("14".equals(checkNoDetailInvoice.getInvoiceType())
                                    && StringUtils.isBlank(checkNoDetailInvoice.getCheckCode())) {
                                continue;
                            }
                            DynamicContextHolder.push(DbConstant.BASICS_READ);
                            //判断是否为大企业税号
                            SysEnterpriseConfigEntity sysEnterpriseConfigEntity = coreSysEnterpriseConfigCoreDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", checkNoDetailInvoice.getBuyerTaxNo()));
                            if (ObjectUtil.isNotEmpty(sysEnterpriseConfigEntity)&&"1".equals(sysEnterpriseConfigEntity.getJrfs())) {
                                continue;
                            }
                            Thread thread = new CheckThread(checkTaskService, db, checkNoDetailInvoice);
                            // 将线程放入池中进行执行

                            if (!threadPoolExecutor.isShutdown()) {
                                threadPoolExecutor.execute(thread);
                            }
                        }
                        threadPoolExecutor.shutdown();
                        threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS);
                    }
                }
                log.info("发票查验执行结束--");
            } catch (Exception e) {
               log.info("业务处理异常：{}", e);
                log.error("定时验证失败:{}", e.getMessage());
            }finally {
                log.info("发票查验--重置执行状态");
                scheduleJobEntity.setJobStatus("0");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
            }
        }
    }

    public void checkInvoiceOld() {
        log.info("历史发票查验执行开始--");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity = scheduleJobService.queryByBeanName("checkTask","checkInvoiceOld");
        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<String> dbList = coreConfirmDao.getDbSource();
                for (String db : dbList) {
                    DynamicContextHolder.push(db + DbConstant.BUSINESS_READ);
                    List<CheckNoDetailInvoice> list = checkTaskService.getNoDetailInvoiceOld();
                    if (list!=null && list.size()>0){
                        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 20, 60, TimeUnit.SECONDS,
                                new LinkedBlockingQueue<>(list.size()), new ThreadPoolExecutor.CallerRunsPolicy());
                        for (CheckNoDetailInvoice checkNoDetailInvoice : list) {
                            if ("14".equals(checkNoDetailInvoice.getInvoiceType())
                                    && StringUtils.isBlank(checkNoDetailInvoice.getCheckCode())) {
                                continue;
                            }
                            DynamicContextHolder.push(DbConstant.BASICS_READ);
                            //判断是否为大企业税号
                            SysEnterpriseConfigEntity sysEnterpriseConfigEntity = coreSysEnterpriseConfigCoreDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", checkNoDetailInvoice.getBuyerTaxNo()));
                            if (ObjectUtil.isNotEmpty(sysEnterpriseConfigEntity)&&"1".equals(sysEnterpriseConfigEntity.getJrfs())) {
                                continue;
                            }
                            Thread thread = new CheckThread(checkTaskService, db, checkNoDetailInvoice);
                            // 将线程放入池中进行执行
                            if (!threadPoolExecutor.isShutdown()) {
                                threadPoolExecutor.execute(thread);
                            }
                        }
                        threadPoolExecutor.shutdown();
                        threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS);
                    }
                }
                log.info("历史发票查验执行结束--");
            } catch (Exception e) {
               log.info("业务处理异常：{}", e);
                log.error("历史发票查验:{}", e.getMessage());
            }finally {
                log.info("历史发票查验--重置执行状态");
                scheduleJobEntity.setJobStatus("0");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
            }
        }
        log.info("历史发票查验执行结束-");
    }

}
