package com.chinaweal.aiccs.aiccs.punishment.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chinaweal.aiccs.aiccs.abnormal.entity.EBaseinfo;
import com.chinaweal.aiccs.aiccs.abnormal.service.EBaseinfoService;
import com.chinaweal.aiccs.aiccs.punishment.entity.EntLock;
import com.chinaweal.aiccs.aiccs.punishment.entity.Personlock;
import com.chinaweal.aiccs.aiccs.punishment.entity.dto.EntDto;
import com.chinaweal.aiccs.aiccs.punishment.mapper.EntlockMapper;
import com.chinaweal.aiccs.aiccs.punishment.mapper.PersonlockMapper;
import com.chinaweal.aiccs.aiccs.punishment.mapper.TaskMapper;
import com.chinaweal.aiccs.aiccs.punishment.service.EntlockService;
import com.chinaweal.aiccs.aiccs.punishment.service.PersonlockService;
import com.chinaweal.aiccs.aiccs.punishment.service.TolockentlistService;
import com.chinaweal.aiccs.aiccs.punishment.service.impl.TsbizPunishUnlockServiceImpl;
import com.chinaweal.aiccs.aiccs.punishment.service.impl.TsbizpunishlockServiceImpl;
import com.chinaweal.aiccs.aiccs.system.entity.TRBaseCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Component("testTask")
@Configuration
public class Task {

    /**
     * key值为惩戒来源清单对应的代码值
     * value值为对应的表名
     */
    private static final Map<String,String> PunishFromMap = new HashMap<>();

    /**
     * key值为惩戒来源清单对应的代码值
     * value值为惩戒来源部门对应
     */
    public static final Map<String,String> PunishFromAndDepartmentMap = new HashMap<>();

    public static final Map<String,String> PunishMap = new HashMap<>();

    @Resource
    private TaskMapper taskMapper;

    @Resource
    private EntlockMapper entLockMapper;

    @Resource
    private PersonlockMapper personlockMapper;


    @Autowired
    private EntlockService entlockService;

    @Autowired
    private PersonlockService personlockService;
    @Autowired
    private TolockentlistService tolockentlistService;

    @Autowired
    private TsbizpunishlockServiceImpl tsbizpunishLockService;

    @Autowired
    private TsbizPunishUnlockServiceImpl tsbizPunishUnlockService;
    @Autowired
    private EBaseinfoService eBaseinfoService;

//    @Autowired
//    private MyAdaptableJobFactory myAdaptableJobFactory;



    static {
        PunishFromAndDepartmentMap.put("1","1");
        PunishFromAndDepartmentMap.put("2","2,3");
        PunishFromAndDepartmentMap.put("3","2,3");
        PunishFromAndDepartmentMap.put("4","4");
        PunishFromAndDepartmentMap.put("5","5");
        PunishFromAndDepartmentMap.put("6","6");
        PunishFromAndDepartmentMap.put("7","7,8");
        PunishFromAndDepartmentMap.put("8","7,8");
        PunishFromAndDepartmentMap.put("9","9,10");
        PunishFromAndDepartmentMap.put("10","9,10");
        PunishFromAndDepartmentMap.put("11","11,12");
        PunishFromAndDepartmentMap.put("12","11,12");
        PunishFromAndDepartmentMap.put("13","13");
        PunishFromAndDepartmentMap.put("14","14");

        PunishFromMap.put("1","ex_xxzx_09_aqschmd_aj"); //安全生产黑名单（安监总局）
        PunishFromMap.put("2","ex_xxzx_10_hggjrzqymd"); //海关高级认证企业名单（海关总署）
        PunishFromMap.put("3","ex_xxzx_11_hgsxrzqymd"); //海关失信认证企业名单（海关总署）
        PunishFromMap.put("4","ex_xxzx_12_2017ndypyz"); //2017年第一批严重违法超限超载运输失信当事人名单（交通运输部
        PunishFromMap.put("5","ex_xxzx_13_tjsyzsxqyh"); //统计上严重失信企业汇总表（国家统计局）
        PunishFromMap.put("6","ex_xxzx_14_scjr_zjh");  //市场禁入（证监会）
        PunishFromMap.put("7","ex_xxzx_14_2016ndcrjj");    //2016年度出入境检验检疫严重失信企业名单（质检总局）
        PunishFromMap.put("8","ex_xxzx_15_yzzlsxqymd"); //严重质量失信企业名单（质检总局）
        PunishFromMap.put("9","ex_xxzx_16_zdsswfajds"); //重大税收违法案件当事人名单（税务总局）
        PunishFromMap.put("10","ex_xxzx_17_10ajnsrmd");    //A级纳税人名单（税务总局）
        PunishFromMap.put("11","ex_xxzx_19_dzswsxwtzx"); //电子商务失信问题专项治理黑名单汇总表（发改委）
        PunishFromMap.put("12","ex_xxzx_20_sjrhmd");     //涉金融黑名单（发改委）
        PunishFromMap.put("13","ex_xxzx_21_2018tqnmggz");    //2018年第一批拖欠农民工工资“黑名单”信息表


        PunishMap.put("1","安监总局"); //安全生产黑名单（安监总局）
        PunishMap.put("2","海关总署"); //海关高级认证企业名单（海关总署）
        PunishMap.put("3","海关总署"); //海关失信认证企业名单（海关总署）
        PunishMap.put("4","交通运输部"); //2017年第一批严重违法超限超载运输失信当事人名单（交通运输部
        PunishMap.put("5","国家统计局"); //统计上严重失信企业汇总表（国家统计局）
        PunishMap.put("6","证监会");  //市场禁入（证监会）
        PunishMap.put("7","质检总局");    //2016年度出入境检验检疫严重失信企业名单（质检总局）
        PunishMap.put("8","质检总局"); //严重质量失信企业名单（质检总局）
        PunishMap.put("9","税务总局"); //重大税收违法案件当事人名单（税务总局）
        PunishMap.put("10","税务总局");    //A级纳税人名单（税务总局）
        PunishMap.put("11","发改委"); //电子商务失信问题专项治理黑名单汇总表（发改委）
        PunishMap.put("12","发改委");     //涉金融黑名单（发改委）
        PunishMap.put("13","");    //2018年第一批拖欠农民工工资“黑名单”信息表
//        initTable();
    }

    /**
     * 表数据初始化
     */
    public void initTable()  {
        log.info("tolockentlist表初始化开始================");
        Long start = System.currentTimeMillis();
        obtainList();
        log.info("tolockentlist表初始化结束================耗时:{} ms" + (System.currentTimeMillis()-start));
    }

    /**
     * 定时更新tolockentlist表
     */
    @Scheduled(cron = "${scheduling.cron.updateTolockentlist}")
    public void updateTolockentlist()  {
        log.info(new Date()+"定时更新联合惩戒数据表");
        log.info("开始更新tolockentlist表"+new Date());
        Long start = System.currentTimeMillis();
        obtainList();
        Long end = System.currentTimeMillis();
        log.info("更新tolockentlist表结束，耗时{} ms",end-start);
        start = System.currentTimeMillis();
        log.info("开始更新Enlock表"+new Date());
        //
        automaticUnEntLock();
        end = System.currentTimeMillis();
        log.info("更新Enlock表结束，耗时{} ms",end - start);
    }

    /**
     * tolockentlist 比对入库
     */
    @Transactional
    public void obtainList() {
//        List<Tolockentlist> list = taskMapper.queryAll();
//        for(Tolockentlist tolockentlist : list){
//            String entName = tolockentlist.getEntName();
//            List<EntLock> entLocks = entlockService.selectLockEntity("广州市皓睿电子有限公司");
//            EntLock e=new EntLock();
//            if(entLocks!=null&&entLocks.size()!=0){
//                 e=entLocks.get(0);
//            }
//
//            if(e.getState()==null||" ".equals(e.getState())){//新表中的数据旧表中没有
//                EntLock entLock=new EntLock();
//                entLock.setPripid(tolockentlist.getPripid());
//                entLock.setUniscid(tolockentlist.getUniscid());
//                entLock.setEntname(tolockentlist.getEntName());
//                entLock.setRegno(tolockentlist.getRegno());
//                entLock.setLockusername("自动锁定");
//                entLock.setPunishFrom(tolockentlist.getPunishFrom());
//                entLock.setRegorg(tolockentlist.getRegorg());
//                entLock.setDepartment(tolockentlist.getDepartment());
//                entLock.setLaupTime(tolockentlist.getLaupTime());
//                entLock.setLockTime(LocalDateTime.now());
//                entLock.setLocktype("001");
//                entLock.setState("0");
//                //entLock.setRepresentative(tolockentlist.get);
//                entLock.setInputdate(LocalDateTime.now());
//                entLock.setLockstate("1");
//                entlockService.insert(entLock);
//            }else if(e.getState().equals("3")){//新表中的数据旧表中也有但是是解锁状态
//
//                SchedulerFactoryBean factoryBean=new SchedulerFactoryBean();
//                SchedulerFactory factory=new StdSchedulerFactory();
                //factoryBean.setJobFactory(myAdaptableJobFactory);
//                Scheduler scheduler=factory.getScheduler();
//                scheduler.setJobFactory(myAdaptableJobFactory);//解决任务类job中不能注入spring实例的问题
//                scheduler.clear();
//                LocalDateTime d=e.getUnlockTime();
//                JobDetail jobDetail = JobBuilder.newJob(AutoUnlock.class)
//                        .usingJobData("entName",entName)
//                        .withIdentity("job1", "group1").build();
//                String cronExpression;
//                if(d.getMonthValue()+2>12){
//                   cronExpression = new String(d.getSecond()+" "+d.getMinute()+" "+d.getHour()+" "+
//                            d.getDayOfMonth()+" "+(d.getMonthValue()-12)+" "+"*"+" "+(d.getDayOfYear()+1));
//                }else{
//                   cronExpression = new String(d.getSecond()+" "+d.getMinute()+" "+d.getHour()+" "+
//                            d.getDayOfMonth()+" "+(d.getMonthValue()+2)
//                           +" "+"*"+" "+d.getDayOfYear());
//                }
////                cronExpression = "0 7 17 12 6 ? 2022";
//                CronTrigger cronTrigger= TriggerBuilder.newTrigger().withIdentity("trigger","triggerGroup")
//                        .usingJobData("entName",entName)
//                        .startNow()
//                        .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
//                        .build();
//                scheduler.scheduleJob(jobDetail,cronTrigger);
//                scheduler.start();
//
//            }

//            //判断是否存在entlock并且状态不是已经解锁
//            List<EntLock> entLocks =entlockService.queryByState(tolockentlist.getPripid(),tolockentlist.getPunishFrom());
//            if(entLocks.size() == 0){
//                /**
//                 * 判断是否存在拟锁定表且状态不为 3 办结
//                 * 判断是否存在锁定业务表且状态为 ('9','1') 受理中，审批中
//                 */
//                List<String> pripids = taskMapper.queryByTolockentlistAndTsbizPunishLock(tolockentlist.getPripid(),tolockentlist.getPunishFrom());
//                if(pripids.size() == 0){ //保存到拟锁定表
//                    //设置来源部门
//                    tolockentlist.setDepartment(PunishFromAndDepartmentMap.get(tolockentlist.getPunishFrom()));
//                    tolockentlist.setTolockId(UUID.randomUUID().toString());
//                    tolockentlist.setState("0");
//                    tolockentlist.setInsertTime(LocalDateTime.now());
//                    tolockentlist.setLaupTime(LocalDateTime.now());
//                    tolockentlistService.save(tolockentlist);
//
//
//                }
//            }
//        }
        List<EntLock> entLocks = entLockMapper.queryAll();
        List<Personlock> personlocks = personlockMapper.queryAll();
        if(entLocks!=null&&entLocks.size()!=0) {
            for (EntLock entLock : entLocks) {
                LocalDateTime now=LocalDateTime.now();
            //EntLock entLock = entLocks.get(0);
            entLock.setElid(UUID.randomUUID().toString());
            entLock.setLockusername("信用风险监管处");
            entLock.setLockstate("1");
            entLock.setIsdelete("0");
            entLock.setState("0");
            if(null!=entLock.getPunishFrom()){
                entLock.setLockreason("1、"+PunishMap.get(entLock.getPunishFrom())+"联合惩戒要求进行限制；2、根据《失信企业协同监管和联合惩戒合作备忘录》（发改财金〔2015〕2045号）《广州市人民政府关于印发" +
                        "广州市建立完善守信联合激励和失信联合惩戒机制实施方案的通知》" +
                        "（穗府〔2019〕1号）。 （可办理：一、企业因地址原因列入经营异常名录办理的地址变更，二、企业办理清算小组备案，办理注销）");
                if("3".equals(entLock.getPunishFrom())){
                    entLock.setLockreason("根据国家38部委关于《失信企业协同监管和联合惩戒合作备忘录》（发改财金[2015]2045号）及《广州市人民政府关于印发广州市建立完善守信联合激励和失信联合惩戒机制实施方案的通知》(穗府[2019]1号)的要求，我局从公共信用信息平台获取到海关部门联合惩戒相关数据，你公司被海关部门列为海关失信认证企业名单，要求进行联合惩戒，我局在注册登记系统进行警示限制。（如企业没有违反《中华人民共和国海关企业信用管理暂行办法》，可以申请解除联合惩戒警示）（如有疑问咨询85592417）");

                }
                if("1".equals(entLock.getPunishFrom())){
                    entLock.setLockreason("根据国家38部委关于《失信企业协同监管和联合惩戒合作备忘录》（发改财金[2015]2045号）及《广州市人民政府关于印发广州市建立完善守信联合激励和失信联合惩戒机制实施方案的通知》(穗府[2019]1号)的要求，我局从公共信用信息平台获取到安监部门联合惩戒相关数据，你公司被安监部门列为安全生产黑名单，要求进行联合惩戒，我局在注册登记系统进行警示限制。（如企业已完成安监部门的整改要求或未有违反《生产经营单位安全生产不良记录“黑名单”管理暂行规定》提出异议的可申请解除联合惩戒警示）（如有疑问咨询85592417）");

                }
                if("6".equals(entLock.getPunishFrom())){
                    entLock.setLockreason("1、"+PunishMap.get(entLock.getPunishFrom())+"联合惩戒要求进行限制；2、根据《失信企业协同监管和联合惩戒合作备忘录》（发改财金〔2015〕2045号）《广州市人民政府关于印发" +
                            "广州市建立完善守信联合激励和失信联合惩戒机制实施方案的通知》" +
                            "（穗府〔2019〕1号）。 （可办理：一、企业因地址原因列入经营异常名录办理的地址变更，二、企业办理清算小组备案）");
                }
            }


            entLock.setLockstartdate(now);
            entLock.setLockTime(now);
            entLock.setDepartment(PunishFromAndDepartmentMap.get(entLock.getPunishFrom()));
            entLock.setLaupTime(now);
            entLock.setInputdate(now);
            entlockService.save(entLock);
            Long start = System.currentTimeMillis();
//                String tflockid = tsbizpunishLockService.sendEntLock(entLock);
//                log.info("推送锁定数据id：{},推送解锁数据耗时: {}ms", tflockid, System.currentTimeMillis() - start);
//                if(com.chinaweal.aiccs.common.util.StringUtils.isNotBlank(tflockid)){
//                    entLock.setTflockid(tflockid);
//                    entlockService.updateById(entLock);
//                } else {
//                    throw new BusinessException("推送锁定数据失败");
//                }
            }
        }

        if(personlocks!=null&&personlocks.size()!=0) {
            for (Personlock personlock : personlocks) {
            //Personlock personlock = personlocks.get(0);
            personlock.setPlid(UUID.randomUUID().toString());
              //personlock.setLockstate("1");
                personlock.setLockstartdate(LocalDateTime.now());
                personlock.setInputdate(LocalDateTime.now());
                personlockService.save(personlock);
                Long start = System.currentTimeMillis();
//                String tflockid = tsbizpunishLockService.sendPersonlock(personlock);
//                log.info("推送锁定数据id：{},推送解锁数据耗时: {}ms", tflockid, System.currentTimeMillis() - start);
//                if(com.chinaweal.aiccs.common.util.StringUtils.isNotBlank(tflockid)){
////                    personlock.setTflockid(tflockid);
////                    entlockService.updateById(personlock);
//                } else {
//                    throw new BusinessException("推送锁定数据失败");
//                }
            }
        }
        List<EntLock> query = entLockMapper.unlocked();//新表中有旧表中也有但是是解锁状态的数据

        if(query!=null&&query.size()!=0){
            for (EntLock entLock : query) {
            //EntLock entLock = query.get(0);
            String entName = entLock.getEntname();

//            SchedulerFactory factory=new StdSchedulerFactory();
//            //factoryBean.setJobFactory(myAdaptableJobFactory);
//            Scheduler scheduler=factory.getScheduler();
//            scheduler.setJobFactory(myAdaptableJobFactory);//解决任务类job中不能注入spring实例的问题
//            scheduler.clear();
//            LocalDateTime d=entLock.getUnlockTime();
//            JobDetail jobDetail = JobBuilder.newJob(AutoUnlock.class)
//                    .usingJobData("entName",entName)
//                    .withIdentity("job1", "group1").build();
//            String cronExpression;
//            if(d.getMonthValue()+2>12){
//                cronExpression = new String(d.getSecond()+" "+d.getMinute()+" "+d.getHour()+" "+
//                        d.getDayOfMonth()+" "+(d.getMonthValue()-12)+" "+"*"+" "+(d.getDayOfYear()+1));
//            }else{
//                cronExpression = new String(d.getSecond()+" "+d.getMinute()+" "+d.getHour()+" "+
//                        d.getDayOfMonth()+" "+(d.getMonthValue()+2)
//                        +" "+"*"+" "+d.getDayOfYear());
//            }
////                cronExpression = "0 7 17 12 6 ? 2022";
//            CronTrigger cronTrigger= TriggerBuilder.newTrigger().withIdentity("trigger","triggerGroup")
//                    .usingJobData("entName",entName)
//                    .startNow()
//                    .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
//                    .build();
//            scheduler.scheduleJob(jobDetail,cronTrigger);
//            scheduler.start();

                LocalDateTime now = LocalDateTime.now();

                LambdaQueryWrapper<EntLock> entLockLambdaQueryWrapper=new LambdaQueryWrapper<>();
                entLockLambdaQueryWrapper.eq(EntLock::getEntname,entName)
                        .orderByDesc(EntLock::getLaupTime)
                        .last("limit 0,1");
                EntLock e = entlockService.getOne(entLockLambdaQueryWrapper);
                //EntLock e = taskMapper.query(entName);
                //LocalDateTime unlockTime = entLock.getUnlockTime();
                LocalDateTime unlockTime = e.getUnlockTime();
                LocalDateTime of = LocalDateTime.of(unlockTime.getYear(), 12, 31, 0, 0);
//            if((unlockMonth+2>12&&nowMonth>=(12-unlockMonth+2))||(unlockMonth+2<=12&&nowMonth>=(unlockMonth+2))){
            //if((entLock.getUnlockTime().plusDays(60).getYear()==entLock.getUnlockTime().getYear()&&LocalDateTime.now().getDayOfYear()>=entLock.getUnlockTime().plusDays(60).getDayOfYear()+60)||)
            //if((entLock.getUnlockTime().plusDays(60).getYear()>entLock.getUnlockTime().getYear()&&now.getYear()>entLock.getUnlockTime().getYear()?now.getDayOfYear()+ of.getDayOfYear()>entLock.getUnlockTime().plusDays(60).getDayOfYear()+of.getDayOfYear():false)
                  //  ||(entLock.getUnlockTime().plusDays(60).getYear()==entLock.getUnlockTime().getYear()&&now.getDayOfYear()>=entLock.getUnlockTime().plusDays(60).getDayOfYear())) {
                //if(LocalDateTime.now().getDayOfYear()>entLock.getUnlockTime().plusDays(60).getDayOfYear()+of.getDayOfYear()||LocalDateTime.now().getDayOfYear()>=entLock.getUnlockTime().plusDays(60).getDayOfYear()){
                if((e.getUnlockTime().plusDays(60).getYear()>e.getUnlockTime().getYear()&&now.getYear()>e.getUnlockTime().getYear()?now.getDayOfYear()+ of.getDayOfYear()>e.getUnlockTime().plusDays(60).getDayOfYear()+of.getDayOfYear():false)
                        ||(e.getUnlockTime().plusDays(60).getYear()==e.getUnlockTime().getYear()&&now.getDayOfYear()>=e.getUnlockTime().plusDays(60).getDayOfYear())) {
                EntLock ent = new EntLock();
                ent.setElid(UUID.randomUUID().toString());
                ent.setIsdelete("0");
                ent.setState("0");
                ent.setLockstate("1");
                ent.setLocktype("001");
                //ent.setPunishFrom(e.getPunishFrom());
                ent.setPunishFrom(entLock.getPunishFrom());
                ent.setRegno(e.getRegno());
                ent.setPripid(e.getPripid());
                ent.setUniscid(e.getUniscid());
                ent.setEntname(entName);
                ent.setLockusername("信用风险监管处");
                if(null!=e.getPunishFrom()){
                    ent.setLockreason("1、"+PunishMap.get(entLock.getPunishFrom())+"联合惩戒要求进行限制；2、根据《失信企业协同监管和联合惩戒合作备忘录》（发改财金〔2015〕2045号）《广州市人民政府关于印发" +
                            "广州市建立完善守信联合激励和失信联合惩戒机制实施方案的通知》" +
                            "（穗府〔2019〕1号）。 （可办理：一、企业因地址原因列入经营异常名录办理的地址变更，二、企业办理清算小组备案，办理注销）");
                    if("3".equals(entLock.getPunishFrom())){
                        ent.setLockreason("根据国家38部委关于《失信企业协同监管和联合惩戒合作备忘录》（发改财金[2015]2045号）及《广州市人民政府关于印发广州市建立完善守信联合激励和失信联合惩戒机制实施方案的通知》(穗府[2019]1号)的要求，我局从公共信用信息平台获取到海关部门联合惩戒相关数据，你公司被海关部门列为海关失信认证企业名单，要求进行联合惩戒，我局在注册登记系统进行警示限制。（如企业没有违反《中华人民共和国海关企业信用管理暂行办法》，可以申请解除联合惩戒警示）（如有疑问咨询85592417）");

                    }
                    if("1".equals(entLock.getPunishFrom())){
                        ent.setLockreason("根据国家38部委关于《失信企业协同监管和联合惩戒合作备忘录》（发改财金[2015]2045号）及《广州市人民政府关于印发广州市建立完善守信联合激励和失信联合惩戒机制实施方案的通知》(穗府[2019]1号)的要求，我局从公共信用信息平台获取到安监部门联合惩戒相关数据，你公司被安监部门列为安全生产黑名单，要求进行联合惩戒，我局在注册登记系统进行警示限制。（如企业已完成安监部门的整改要求或未有违反《生产经营单位安全生产不良记录“黑名单”管理暂行规定》提出异议的可申请解除联合惩戒警示）（如有疑问咨询85592417）");

                    }
                    if("6".equals(entLock.getPunishFrom())){
                        ent.setLockreason("1、"+PunishMap.get(e.getPunishFrom())+"联合惩戒要求进行限制；2、根据《失信企业协同监管和联合惩戒合作备忘录》（发改财金〔2015〕2045号）《广州市人民政府关于印发" +
                                "广州市建立完善守信联合激励和失信联合惩戒机制实施方案的通知》" +
                                "（穗府〔2019〕1号）。 （可办理：一、企业因地址原因列入经营异常名录办理的地址变更，二、企业办理清算小组备案）");
                    }
                }
                ent.setDepartment(PunishFromAndDepartmentMap.get(entLock.getPunishFrom()));
                ent.setLockstartdate(now);
                ent.setLockTime(now);
                ent.setRegorg(e.getRegorg());
                ent.setRepresentative(e.getRepresentative());
                ent.setInputdate(now);
                ent.setCertype(e.getCertype());
                ent.setCerno(e.getCerno());
                entLock.setLaupTime(now);
                entlockService.save(ent);
                Long start = System.currentTimeMillis();
//                String tflockid = tsbizpunishLockService.sendEntLock(ent);
//                log.info("推送锁定数据id：{},推送解锁数据耗时: {}ms", tflockid, System.currentTimeMillis() - start);
//                if(com.chinaweal.aiccs.common.util.StringUtils.isNotBlank(tflockid)){
//                    entLock.setTflockid(tflockid);
//                    entlockService.updateById(ent);
//                } else {
//                    throw new BusinessException("推送锁定数据失败");
//                }
              }
            }
        }

        List<Personlock> querypersonlock = personlockMapper.unlocked();//新表中有旧表中也有但是是解锁状态的数据

        if(querypersonlock!=null&&querypersonlock.size()!=0){
            for (Personlock personlock : querypersonlock) {

            //Personlock personlock = querypersonlock.get(0);
            String lerep = personlock.getPername();
            String entname = personlock.getEntname();
//            SchedulerFactory factory=new StdSchedulerFactory();
//            //factoryBean.setJobFactory(myAdaptableJobFactory);
//            Scheduler scheduler=factory.getScheduler();
//            scheduler.setJobFactory(myAdaptableJobFactory);//解决任务类job中不能注入spring实例的问题
//            scheduler.clear();
//            LocalDateTime d=personlock.getLockenddate();
//            JobDetail jobDetail = JobBuilder.newJob(AutoPersonUnlock.class)
//                    .usingJobData("pername",pername)
//                    .withIdentity("job1", "group1").build();
//            String cronExpression;
//            if(d.getMonthValue()+2>12){
//                cronExpression = new String(d.getSecond()+" "+d.getMinute()+" "+d.getHour()+" "+
//                        d.getDayOfMonth()+" "+(d.getMonthValue()-12)+" "+"*"+" "+(d.getDayOfYear()+1));
//            }else{
//                cronExpression = new String(d.getSecond()+" "+d.getMinute()+" "+d.getHour()+" "+
//                        d.getDayOfMonth()+" "+(d.getMonthValue()+2)
//                        +" "+"*"+" "+d.getDayOfYear());
//            }
////                cronExpression = "0 7 17 12 6 ? 2022";
//            CronTrigger cronTrigger= TriggerBuilder.newTrigger().withIdentity("trigger","triggerGroup")
//                    .usingJobData("pername",pername)
//                    .startNow()
//                    .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
//                    .build();
//            scheduler.scheduleJob(jobDetail,cronTrigger);
//            scheduler.start();
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime lockenddate = personlock.getLockenddate();
            LocalDateTime of = LocalDateTime.of(lockenddate.getYear(), 12, 31, 0, 0);
            if((lockenddate.plusDays(60).getYear()>lockenddate.getYear()&&now.getDayOfYear()>lockenddate.getYear()?now.getDayOfYear()+ of.getDayOfYear()>lockenddate.plusDays(60).getDayOfYear()+of.getDayOfYear():false)
                    ||(lockenddate.plusDays(60).getYear()==lockenddate.getYear()&&now.getDayOfYear()>=lockenddate.plusDays(60).getDayOfYear())) {
                Personlock person = taskMapper.querypersonlock(lerep,entname);
                Personlock p = new Personlock();
                p.setPlid(UUID.randomUUID().toString());
                p.setIdcardno(person.getIdcardno());
                p.setPername(person.getPername());
                p.setEntname(person.getEntname());
                p.setRegno(person.getRegno());
                p.setLockreason("1、"+"联合惩戒要求进行限制；2、根据《失信企业协同监管和联合惩戒合作备忘录》（发改财金〔2015〕2045号）《广州市人民政府关于印发" +
                        "广州市建立完善守信联合激励和失信联合惩戒机制实施方案的通知》" +
                        "（穗府〔2019〕1号）。 （可办理：一、企业因地址原因列入经营异常名录办理的地址变更，二、企业办理清算小组备案，办理注销）");
                p.setLockstate("1");
                p.setLockstartdate(now);
                p.setLockusername("信用风险监管处");
                p.setInputdate(now);
                personlockService.save(p);
                Long start = System.currentTimeMillis();
//                String tflockid = tsbizpunishLockService.sendPersonlock(personlock);
//                log.info("推送锁定数据id：{},推送解锁数据耗时: {}ms", tflockid, System.currentTimeMillis() - start);
//                if(com.chinaweal.aiccs.common.util.StringUtils.isNotBlank(tflockid)){
////                    personlock.setTflockid(tflockid);
////                    entlockService.updateById(personlock);
//                } else {
//                    throw new BusinessException("推送锁定数据失败");
//                }
            }
            }
        }
    }


    /**
     * 自动解锁
     */
    @Transactional
    public void automaticUnEntLock() {

        List<TRBaseCode> trBaseCodes = taskMapper.queryRegState();
        Map<String,String> map = new HashMap<>();
        for(TRBaseCode trBaseCode : trBaseCodes) {
            map.put(trBaseCode.getCode(),trBaseCode.getName());
        }
        //List<EntLock> entLocks = entlockService.list(new LambdaQueryWrapper<EntLock>().eq(EntLock::getState, "0")); //锁定状态
        List<EntLock> entLocks = entLockMapper.lockList();//需要查找最新一条的锁定数据
        //EntLock entLock=entLocks.get(0);
        if(entLocks!=null&&entLocks.size()!=0) {
            for (EntLock entLock : entLocks) {
                String tableName = PunishFromMap.get(entLock.getPunishFrom());
                tableName = "crgs." + tableName;
                String reason = "根据国家38部委关于《失信企业协同监管和联合惩戒合作备忘录》（发改财金[2015]2045号）" +
                        "及《广州市人民政府关于印发广州市建立完善守信联合激励和失信联合惩戒机制实施方案的通知》(穗府[2019]1号)的要求，" +
                        "我局从市公共信用信息系统获取" + PunishMap.get(entLock.getPunishFrom()) + "联合惩戒相关数据，" +
                        "你公司已不在" + PunishMap.get(entLock.getPunishFrom()) + "失信名单（或已办理注销或已吊销），根据上述规定现移出联合惩戒";
                int check = taskMapper.checkEntLock(tableName, entLock.getEntname());
                if (check == 0) { // 解锁
                    entLock.setState("3");
                    entLock.setLockenddate(LocalDateTime.now());
                    entLock.setUnlockreason(reason);
                    entLock.setULockSpecificReason("因联合惩戒源无数据移除锁定");
                    entLock.setUnlockTime(LocalDateTime.now());
                    entLock.setUnlusername("信用风险监管处");
                    entLock.setUlunitid(entLock.getLockuserunitid());
                    entLock.setLaupTime(LocalDateTime.now());
                    entlockService.updateById(entLock);
                    // 解锁推送
//                Boolean success = tsbizPunishUnlockService.sendUnEntLock(entLock);
//                if(!success) throw new BusinessException("推送解锁数据失败");
//                log.info("自动解锁推送企业：{}，结果：{}",entLock.getEntname(), success? "成功" : "失败");
                } else {
                    EBaseinfo eBaseinfo = eBaseinfoService.getOne(new LambdaQueryWrapper<EBaseinfo>().eq(EBaseinfo::getPripid, entLock.getPripid()));
                    // 非在营自动解锁
                    if (!eBaseinfo.getRegstate().equals("1") && !eBaseinfo.getRegstate().equals("003") && !eBaseinfo.getRegstate().equals("003001")) {
                        entLock.setState("3");
                        String unlockreason = StringUtils.isNotBlank(map.get(eBaseinfo.getRegstate())) ? map.get(eBaseinfo.getRegstate()) : "为非营业状态";
                        entLock.setUnlockreason("企业" + unlockreason);
                        entLock.setUnlockTime(LocalDateTime.now());
                        entLock.setUnlusername("信用风险监管处");
                        entLock.setULockSpecificReason("因注吊撤销或迁出移除锁定");
                        entLock.setUlunitid(entLock.getLockuserunitid());
                        entLock.setLaupTime(LocalDateTime.now());
                        entlockService.updateById(entLock);
                        // 解锁推送
//                    Boolean success = tsbizPunishUnlockService.sendUnEntLock(entLock);
//                    if(!success) throw new BusinessException("推送解锁数据失败");
//                    log.info("自动解锁推送企业：{}，结果：{}",entLock.getEntname(), success? "成功" : "失败");
                    }
                }
            }
        }
        //List<Personlock> list = personlockService.list(new LambdaQueryWrapper<Personlock>().eq(Personlock::getLockstate, "1"));
        List<Personlock> list = personlockMapper.lockList();

        if (list != null && list.size() > 0) {
//        Personlock personlock = list.get(0);
                for (Personlock personlock : list) {

                    Personlock querypersonlock = taskMapper.querypersonlock(personlock.getPername(), personlock.getEntname());
                    if (null == querypersonlock) {
                        personlock.setLockstate("0");
                        personlock.setUlockseason("因联合惩戒源无数据移除锁定");
                        personlock.setUnlockusername("信用风险监管处");
                        personlock.setUnldate(LocalDateTime.now());
                        personlock.setLockenddate(LocalDateTime.now());
                        personlockService.updateById(personlock);
//                Boolean success = tsbizPunishUnlockService.sendUnPersonLock(querypersonlock);
//                if(!success) throw new BusinessException("推送解锁数据失败");
//                log.info("自动解锁推送法人：{}，结果：{}",querypersonlock.getPername(), success? "成功" : "失败");
                    } else {
                        EBaseinfo eBaseinfo = eBaseinfoService.getOne(new LambdaQueryWrapper<EBaseinfo>().eq(EBaseinfo::getEntname, querypersonlock.getEntname()));
                        if (!"1".equals(eBaseinfo.getRegstate()) && !"003".equals(eBaseinfo.getRegstate()) && !"003001".equals(eBaseinfo.getRegstate())) {
                            personlock.setLockstate("0");
                            personlock.setUlockseason("因注吊撤销或迁出移除锁定");
                            personlock.setUnlockusername("信用风险监管处");
                            personlock.setUnldate(LocalDateTime.now());
                            personlock.setLockenddate(LocalDateTime.now());
                            personlockService.updateById(personlock);
//                    Boolean success = tsbizPunishUnlockService.sendUnPersonLock(querypersonlock);
//                    if(!success) throw new BusinessException("推送解锁数据失败");
//                    log.info("自动解锁推送法人：{}，结果：{}",querypersonlock.getPername(), success? "成功" : "失败");
                        }
                    }
                }

            }
        }
    /**
     * 更新Enlock表 （弃用）
     */
    public void updateEntlockbak(){
        List<String> pripids = taskMapper.queryEntLock();
        if(pripids.size()>0){
            taskMapper.updateEntLock(pripids);
        }else{
            log.info("比对结果无需更新Enlock表");
        }
    }

    /**
     * 更新Enlock表（弃用）已没有拟解锁概念
     */
    @Transactional
    public void updateEntlock(){
        /**
         * 锁定表entlock中状态为0，未解锁 及在e_baseinfo表中登记状态不为 1：营业
         */

        List<TRBaseCode> trBaseCodes = taskMapper.queryRegState();
        Map<String,String> map = new HashMap<>();
        for(TRBaseCode trBaseCode : trBaseCodes) {
            map.put(trBaseCode.getCode(),trBaseCode.getName());
        }
        List<EntDto> entDtos = taskMapper.queryEntDto();
        for(EntDto entDto : entDtos) {
            EntLock entLock = entlockService.getById(entDto.getElid());
            String uLockSpecificReason = "企业已" + map.get(entDto.getRegstate());
            entLock.setULockSpecificReason(uLockSpecificReason);
            entLock.setULSRCode(entDto.getRegstate());
            entLock.setState("1"); //设置为拟解锁
            entlockService.updateById(entLock);
        }
        /**
         * 存在entlock不存在来源表的数据
         */
        List<EntLock> entLocks = taskMapper.queryAllEntFromPF();
        for(EntLock entLock : entLocks){
            entLock.setState("1"); //设置为拟解锁
            entLock.setULockSpecificReason("未在惩戒名单中");
            entLock.setULSRCode("0");
        }
        if(entLocks.size()>0){
            for(EntLock entLock : entLocks) {
                entlockService.updateById(entLock);
            }
//            entlockService.updateBatchById(entLocks); //批量更新
        }
    }


}
