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.entity.TAcOrg;
import com.dxhy.core.job.service.ExportInterfaceService;
import com.dxhy.core.job.service.ScheduleJobService;
import com.dxhy.core.job.thread.ExportCustomsHandle;
import com.dxhy.core.job.thread.ExportInvoiceHandle;
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 陈刚扬
 * @date 2020/10/30
 */
@Component("exportInterfaceTask")
@Slf4j

public class ExportInterfaceTask {

    @Resource
    private CoreConfirmDao coreConfirmDao;

    @Resource
    private ExportInterfaceService exportInterfaceService;
    @Resource
    private ScheduleJobService scheduleJobService;

    @Resource
    private CoreSysEnterpriseConfigCoreDao coreSysEnterpriseConfigCoreDao;

    public void getExportCustoms() throws InterruptedException {
        log.info("获取出口转内销海关缴款书开始！--");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity =
            scheduleJobService.queryByBeanName("exportInterfaceTask", "getExportCustoms");
        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> taxnoList = coreConfirmDao.getTaxno();
                ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 15, 5, TimeUnit.SECONDS,
                    new LinkedBlockingQueue<>(taxnoList.size()), new ThreadPoolExecutor.CallerRunsPolicy());
                for (TAcOrg org : taxnoList) {
                    DynamicContextHolder.push(DbConstant.BASICS_READ);
                    //判断是否为大企业税号
                    SysEnterpriseConfigEntity sysEnterpriseConfigEntity = coreSysEnterpriseConfigCoreDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", org.getTaxno()));
                    if (ObjectUtil.isNotEmpty(sysEnterpriseConfigEntity)&&"1".equals(sysEnterpriseConfigEntity.getJrfs())) {
                        continue;
                    }
                    if (!threadPoolExecutor.isShutdown()) {
                        String taxno = org.getTaxno();
                        String db = org.getDbName();
                        String aceId = org.getAceId();
                        String aceKey = org.getAceKey();
                        String company = org.getCompany();
                        String taxName = org.getTaxname();

                        threadPoolExecutor.execute(new ExportCustomsHandle(taxno, db, aceId, aceKey, company, taxName));
                    }
                }
                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);
            }
        }

    }

    public void customsLtgalizeResult() {
        log.info("出口转内销缴款书认证结果获取定时任务启动--");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity =
            scheduleJobService.queryByBeanName("exportInterfaceTask", "customsLtgalizeResult");
        if (scheduleJobEntity != null && "0".equals(scheduleJobEntity.getJobStatus())) {
            try {
                scheduleJobEntity.setJobStatus("1");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
                exportInterfaceService.getExportCustomsLtgalizeResult();
                log.info("出口转内销缴款书认证结果获取定时任务结束--");
            } catch (Exception e) {
               log.info("业务处理异常：{}", e);
            } finally {
                log.info("出口转内销缴款书认证结果获取--重置执行状态");
                scheduleJobEntity.setJobStatus("0");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
            }
        }
    }

    public void applyCustomsLtgalize() {
        log.info("出口转内销缴款书申请认证定时任务启动--");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity =
            scheduleJobService.queryByBeanName("exportInterfaceTask", "applyCustomsLtgalize");
        if (scheduleJobEntity != null && "0".equals(scheduleJobEntity.getJobStatus())) {
            try {
                scheduleJobEntity.setJobStatus("1");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
                exportInterfaceService.exportCustomsLegalize();
                log.info("出口转内销缴款书申请认证定时任务结束--");
            } catch (Exception e) {
               log.info("业务处理异常：{}", e);
            } finally {
                log.info("出口转内销缴款书申请认证--重置执行状态");
                scheduleJobEntity.setJobStatus("0");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
            }
        }
    }

    public void getExportInvoice() throws InterruptedException {
        log.info("获取出口转内销发票开始！--");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity =
            scheduleJobService.queryByBeanName("exportInterfaceTask", "getExportInvoice");
        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> taxnoList = coreConfirmDao.getTaxno();
                ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 15, 5, TimeUnit.SECONDS,
                    new LinkedBlockingQueue<>(taxnoList.size()), new ThreadPoolExecutor.CallerRunsPolicy());
                for (TAcOrg org : taxnoList) {
                    DynamicContextHolder.push(DbConstant.BASICS_READ);
                    //判断是否为大企业税号
                    SysEnterpriseConfigEntity sysEnterpriseConfigEntity = coreSysEnterpriseConfigCoreDao.selectOne(new QueryWrapper<SysEnterpriseConfigEntity>().eq("nsrsbh", org.getTaxno()));
                    if (ObjectUtil.isNotEmpty(sysEnterpriseConfigEntity)&&"1".equals(sysEnterpriseConfigEntity.getJrfs())) {
                        continue;
                    }
                    if (!threadPoolExecutor.isShutdown()) {
                        String taxno = org.getTaxno();
                        String db = org.getDbName();
                        String aceId = org.getAceId();
                        String aceKey = org.getAceKey();
                        String company = org.getCompany();
                        String taxName = org.getTaxname();
                        threadPoolExecutor.execute(new ExportInvoiceHandle(taxno, db, aceId, aceKey, company, taxName));
                    }
                }
                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);
            }
        }
    }

    public void ltgalizeResult() {
        log.info("出口转内销发票认证结果获取定时任务启动--");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity =
            scheduleJobService.queryByBeanName("exportInterfaceTask", "ltgalizeResult");
        if (scheduleJobEntity != null && "0".equals(scheduleJobEntity.getJobStatus())) {
            try {
                scheduleJobEntity.setJobStatus("1");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
                exportInterfaceService.getExportInvoieLtgalizeResult();
                log.info("出口转内销发票认证结果获取定时任务结束--");
            } catch (Exception e) {
               log.info("业务处理异常：{}", e);
            } finally {
                log.info("出口转内销发票认证结果获取--重置执行状态");
                scheduleJobEntity.setJobStatus("0");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
            }
        }
    }

    public void applyInvoiceLtgalize() {
        log.info("出口转内发票申请认证定时任务启动--");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity =
            scheduleJobService.queryByBeanName("exportInterfaceTask", "applyInvoiceLtgalize");
        if (scheduleJobEntity != null && "0".equals(scheduleJobEntity.getJobStatus())) {
            try {
                scheduleJobEntity.setJobStatus("1");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
                exportInterfaceService.exportInvoiceLegalize();
                log.info("出口转内销发票申请认证定时任务结束--");
            } catch (Exception e) {
               log.info("业务处理异常：{}", e);
            } finally {
                log.info("出口转内销发票申请认证--重置执行状态");
                scheduleJobEntity.setJobStatus("0");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
            }
        }
    }
}
