package com.tykj.dev.rfid.timeTask;

import com.module.interaction.ReaderHelper;
import com.tykj.dev.device.library.service.DeviceLibraryService;
import com.tykj.dev.device.library.subject.domin.DeviceLibrary;
import com.tykj.dev.device.library.subject.vo.DeviceLibrarySelectVo;
import com.tykj.dev.rfid.entity.domin.LibraryWarningLogDetail;
import com.tykj.dev.rfid.entity.domin.LibraryWarningLog;
import com.tykj.dev.rfid.repository.LibraryWarningLogDetailDao;
import com.tykj.dev.rfid.service.LibraryWarningLogService;
import com.tykj.dev.rfid.service.RfidChangeBillService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author HuangXiahao
 * @version V1.0
 * @class Inventory
 * @packageName com.tykj.dev.rfid.timeTask
 **/
@Slf4j
@Component
public class InventoryScheduled {

//    private String cron = "0 0/1 * * * ? ";
    private String cron = "0 0 1 * * ?";

    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    final RfidChangeBillService rfidChangeBillService;

    final LibraryWarningLogService libraryWarningLogService;

    final LibraryWarningLogDetailDao libraryWarningLogDetailDao;

    @Resource
    DeviceLibraryService deviceLibraryService;

    public InventoryScheduled(RfidChangeBillService rfidChangeBillService, LibraryWarningLogService libraryWarningLogService, LibraryWarningLogDetailDao libraryWarningLogDetailDao) {

        this.rfidChangeBillService = rfidChangeBillService;
        this.libraryWarningLogService = libraryWarningLogService;
        this.libraryWarningLogDetailDao = libraryWarningLogDetailDao;
        threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.initialize();
        threadPoolTaskScheduler.schedule(new Inventory(), triggerContext -> new CronTrigger(cron).nextExecutionTime(triggerContext));
    }

    InventoryThread inventoryThread = new InventoryThread();

    public class Inventory implements Runnable {

        @Transactional(rollbackOn = Exception.class)
        @Override
        public void run(){
            log.info("定时器执行了");
            //将上一个线程设为停止
            inventoryThread.setRunFlag(false);
            //等待上一个线程彻底停止
            try {
                inventoryThread.join();
                inventoryThread.interrupt();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //从线程中取出连接对象
            ReaderHelper readerHelper = inventoryThread.getmReaderHelper();
            if (readerHelper==null){
                //如果连接对象为空则本次盘存无效  报警没有连接到盘点机
                log.error("没有连接到天线");
            }else {            //已经确认在库的装备

                //否则从线程中取出本次盘存的数据，用这些数据分析
                ArrayList<String> strTids = inventoryThread.getStrTidArray();
                //已经确认不在库的装备
                ArrayList<LibraryWarningLogDetail> detailEntitiesOut = new ArrayList<>();
                //已经确认正常的装备
                ArrayList<LibraryWarningLogDetail> detailEntitiesIn = new ArrayList<>();
                //已经确认多出来的装备
                ArrayList<LibraryWarningLogDetail> detailEntitiesMore = new ArrayList<>();
                //执行数据库操作
                DeviceLibrarySelectVo deviceLibrarySelectVo = new DeviceLibrarySelectVo();
                deviceLibrarySelectVo.setLifeStatus(Arrays.asList(2));
                deviceLibrarySelectVo.setLocationUnit("省机要局");
                deviceLibrarySelectVo.setUnitId(1);

                List<DeviceLibrary> list = deviceLibraryService.getListWithoutParent(deviceLibrarySelectVo);
                //遍历判断结果
                LibraryWarningLog libraryWarningLog = new LibraryWarningLog();
                libraryWarningLog.setUnit("省机要局");
                libraryWarningLog.setStatus("0");
                libraryWarningLog.setWarningType(2);
                libraryWarningLog.setWarningHandle(0);
                libraryWarningLog.setDueQuantity(list.size()+"");
                libraryWarningLog = libraryWarningLogService.addEntity(libraryWarningLog);
                for (int i = 0; i < list.size(); i++) {
                    DeviceLibrary deviceLibraryEntity = list.get(i);
                    //如果装备列表中装备没有被盘存到，则说明这件装备缺失了
                    if (!strTids.contains(deviceLibraryEntity.getRfidCardId())){
                        LibraryWarningLogDetail libraryWarningLogDetail = new LibraryWarningLogDetail();
                        libraryWarningLogDetail.setLibraryWarningLogId(libraryWarningLog.getId());
                        libraryWarningLogDetail.setDeviceId(deviceLibraryEntity.getId());
                        libraryWarningLogDetail.setStatus(1);
                        libraryWarningLogDetail.setWarningHandle(0);
                        libraryWarningLogDetail.setInventoryResults("缺失");
                        detailEntitiesOut.add(libraryWarningLogDetailDao.save(libraryWarningLogDetail));
                    }else {
                        //如果装备列表中装备被盘存到，则说明这件装备状态正常
                        LibraryWarningLogDetail libraryWarningLogDetail = new LibraryWarningLogDetail();
                        libraryWarningLogDetail.setLibraryWarningLogId(libraryWarningLog.getId());
                        libraryWarningLogDetail.setDeviceId(deviceLibraryEntity.getId());
                        libraryWarningLogDetail.setStatus(1);
                        libraryWarningLogDetail.setWarningHandle(0);
                        libraryWarningLogDetail.setInventoryResults("正常");
                        detailEntitiesIn.add(libraryWarningLogDetailDao.save(libraryWarningLogDetail));
                        //从盘存的列表中删除这一件装备
                        int i1 = strTids.indexOf(deviceLibraryEntity.getRfidCardId());
                        strTids.remove(i1);
                    }
                }
                //盘存列表里多出来的装备就时多出来的
                if (strTids.size()>0){
                    for (int i = 0; i <strTids.size() ; i++) {
                        DeviceLibrarySelectVo deviceLibrarySelectVo2 = new DeviceLibrarySelectVo();
                        deviceLibrarySelectVo2.setUnitId(1);
                        deviceLibrarySelectVo2.setRfidCardId(strTids.get(i));
                        List<DeviceLibrary> list2 = deviceLibraryService.getListWithoutParent(deviceLibrarySelectVo2);
                        LibraryWarningLogDetail libraryWarningLogDetail = new LibraryWarningLogDetail();
                        libraryWarningLogDetail.setLibraryWarningLogId(libraryWarningLog.getId());
                        libraryWarningLogDetail.setStatus(1);
                        libraryWarningLogDetail.setWarningHandle(0);
                        if (list2.size()>0){
                            log.info("新增了一台未知设备");
                            libraryWarningLogDetail.setDeviceId(list2.get(0).getId());
                            libraryWarningLogDetail.setInventoryResults("新增一台未知设备");
                        }else {
                            libraryWarningLogDetail.setInventoryResults("新增");
                        }
                        detailEntitiesMore.add(libraryWarningLogDetailDao.save(libraryWarningLogDetail));
                    }
                }
                log.info("缺失ｓｉｚｅ＂"+detailEntitiesOut.size());
                log.info("新增ｓｉｚｅ＂"+detailEntitiesMore.size());
                if (detailEntitiesOut.size()>0||detailEntitiesMore.size()>0){
                    String inventoryResult = "";
                    if (detailEntitiesOut.size()>0){
                        inventoryResult += "缺失"+detailEntitiesOut.size()+"台";
                    }
                    if (detailEntitiesMore.size()>0){
                        inventoryResult += "新增"+detailEntitiesOut.size()+"台";
                    }

                    libraryWarningLog.setInventoryResults(inventoryResult);
                    libraryWarningLog.setStatus("1");
                    libraryWarningLog.setCreateTime(new Date());
                }else {
                    libraryWarningLog.setCreateTime(new Date());
                    libraryWarningLog.setInventoryResults("正常");
                }
                libraryWarningLog.setActualQuantity(detailEntitiesMore.size()+detailEntitiesIn.size()+detailEntitiesIn.size()+"");
                libraryWarningLogService.addEntity(libraryWarningLog);
            }
            if (inventoryThread.getmConnector()!=null){
                inventoryThread.getmConnector().disConnect();
            }
            //重新开启线程
            inventoryThread = new InventoryThread();
            inventoryThread.run();

        }
    }

    public String getCron() {
        return cron;
    }

    public void setCron(String cron) {
        this.cron = cron;
    }

    public static void main(String[] args) {
        InventoryThread inventoryThread = new InventoryThread();
        inventoryThread.run();
    }
}
