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.CustomsInterfaceService;
import com.dxhy.core.job.service.ScheduleJobService;
import com.dxhy.core.job.thread.CustomsHandle;
import com.dxhy.core.job.thread.CustomsStateHandle;
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("customsInterfaceTasks")
@Slf4j

public class CustomsInterfaceTask {

    @Resource
    private CoreConfirmDao coreConfirmDao;
    @Resource
    private ScheduleJobService scheduleJobService;

    @Resource
    private CustomsInterfaceService customsInterfaceService;

    @Resource
    private CoreSysEnterpriseConfigCoreDao coreSysEnterpriseConfigCoreDao;

    public void getCustoms() throws InterruptedException {
        log.info("获取海关缴款书开始！--");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity = scheduleJobService.queryByBeanName("customsInterfaceTasks", "getCustoms");
        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 CustomsHandle(taxno, db, aceId, aceKey, company, taxName));
                    }
                }
                threadPoolExecutor.shutdown();
                threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS);
            } catch (Exception e) {
               log.info("业务处理异常：{}", e);
            } finally {
                log.info("获取海关缴款书--重置执行状态");
                scheduleJobEntity.setJobStatus("0");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
            }
        }
        log.info("获取海关缴款书结束！--");
    }

    public void getCustomsState() throws InterruptedException {
        log.info("缴款书状态获取接口执行开始-");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity =
            scheduleJobService.queryByBeanName("customsInterfaceTasks", "getCustomsState");
        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 = coreConfirmDao.getTaxno();
                // 准备请求参数
                ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 15, 5, TimeUnit.SECONDS,
                    new LinkedBlockingQueue<>(list.size()), new ThreadPoolExecutor.CallerRunsPolicy());

                for (TAcOrg org : list) {
                    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();
                        threadPoolExecutor.execute(new CustomsStateHandle(taxno, db, aceId, aceKey));
                    }

                }
                threadPoolExecutor.shutdown();
                threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS);
            } catch (Exception e) {
               log.info("业务处理异常：{}", e);
            } finally {
                log.info("缴款书状态获取--重置执行状态");
                scheduleJobEntity.setJobStatus("0");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
            }
        }
        log.info("--缴款书态获取接口执行结束-");
    }

    public void customsLtgalizeResult() {
        log.info("缴款书认证结果获取定时任务启动--");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity =
            scheduleJobService.queryByBeanName("customsInterfaceTasks", "customsLtgalizeResult");
        if (scheduleJobEntity != null && "0".equals(scheduleJobEntity.getJobStatus())) {
            try {
                scheduleJobEntity.setJobStatus("1");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
                customsInterfaceService.getLtgalizeResult();
                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("customsInterfaceTasks", "applyCustomsLtgalize");
        if (scheduleJobEntity != null && "0".equals(scheduleJobEntity.getJobStatus())) {
            try {
                scheduleJobEntity.setJobStatus("1");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
                customsInterfaceService.customsLegalize();
                log.info("缴款书申请认证定时任务结束--");
            } catch (Exception e) {
               log.info("业务处理异常：{}", e);
            } finally {
                log.info("缴款书申请认证--重置执行状态");
                scheduleJobEntity.setJobStatus("0");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
            }
        }

    }

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

    public void customsEntry() {
        log.info("缴款书申请录入定时任务启动--");
        DynamicContextHolder.push(DbConstant.BASICS_READ);
        ScheduleJobEntity scheduleJobEntity =
            scheduleJobService.queryByBeanName("customsInterfaceTasks", "customsEntry");
        if (scheduleJobEntity != null && "0".equals(scheduleJobEntity.getJobStatus())) {
            try {
                scheduleJobEntity.setJobStatus("1");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
                customsInterfaceService.customsEntry();
                log.info("缴款书申请录入定时任务结束--");
            } catch (Exception e) {
               log.info("业务处理异常：{}", e);
            } finally {
                log.info("缴款书申请录入--重置执行状态");
                scheduleJobEntity.setJobStatus("0");
                DynamicContextHolder.push(DbConstant.BASICS_WRITE);
                scheduleJobService.updateById(scheduleJobEntity);
            }
        }
    }
}
