package com.mvc.service.copy;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mvc.constant.BaseConstant;
import com.mvc.constant.DeviceState;
import com.mvc.dao.TCheckMapper;
import com.mvc.entity.*;
import com.mvc.model.*;
import com.mvc.service.dic.DicChkplatCellService;
import com.mvc.service.dic.DicChkplatService;
import com.mvc.service.taizhang.BatteryAccService;
import com.mvc.service.taizhang.DeviceAccService;
import com.mvc.service.taizhang.TaskBatchRemoteService;
import com.mvc.utils.DateUtil;
import com.mvc.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

//拷机服务类
@Service
@Transactional
public class TCheckService {
    private final static Logger log = LoggerFactory.getLogger(com.mvc.service.copy.TCheckService.class);

    @Resource
    private TCheckMapper tCheckMapper;

    @Resource
    private DicChkplatService dicChkplatService;

    @Resource
    private DicChkplatCellService dicChkplatCellService;

    @Resource
    private TCheckDetailService tCheckDetailService;

    @Resource
    private DeviceAccService deviceAccService;

    @Resource
    private TAireadService tAireadService;

    @Resource
    private TChkrptService tChkrptService;

    @Resource
    private TaskBatchRemoteService taskBatchRemoteService;

    //@Resource
    //private TTaskDownService tTaskDownService;

    @Resource
    private TServerReadService tServerReadService;

    @Resource
    private BatteryAccService batteryAccService;

    @Resource
    private TServerReadService serverReadService;

    public Map<String, Object> findAllTCheck(TCheckModel queryModel) {
        Map<String, Object> resMap = new HashMap<>();
        TCheckExample example = new TCheckExample();
        TCheckExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(queryModel.getCheckName())) {
            criteria.andCheckNameLike("%" + queryModel.getCheckName() + "%");
        }
        if (queryModel.getHideFinished() != null && queryModel.getHideFinished() == 1) {
            criteria.andEndTimeIsNull();
        }

        //添加限制,非管理员控制只看自己的 2022-11-04 guozhao
        if (StringUtils.isNotEmpty(queryModel.getCreateMan())) {
            criteria.andCreateManEqualTo(queryModel.getCreateMan());
        }
        Page<Object> pageObject = PageHelper.startPage(queryModel.getPage(), queryModel.getRows());
        example.setOrderByClause("CREATE_TIME DESC");
        List<TCheck> TChecks = tCheckMapper.selectByExample(example);
        List<TCheckModel> resList = new ArrayList<>();

        for (TCheck TCheck : TChecks) {
            TCheckModel model = new TCheckModel();
            BeanUtils.copyProperties(TCheck, model);

            if (StringUtils.isNotEmpty(model.getTaskBatchId())) {
                TaskBatchRemoteModel remoteModel = taskBatchRemoteService.findTaskBatchRemoteByTaskBatchId(model.getTaskBatchId());
                model.setTaskBatchRemoteModel(remoteModel);
            }

            model.setPlanEndInfo("");
            //推算计划结束时间2022-10-29 guozhao
            if (model.getStartTime() != null) {
                if (model.getEndTime() == null) {
                    Date startTime = model.getStartTime();
                    Date endTime = DateUtil.getOtherDateByCurrentDate(startTime, model.getCheckDays());
                    model.setPlanEndTime(endTime);
                    model.setPlanEndInfo(calculateDuration(endTime));
                    //计算距离结束时间的间隔(n天n时n分钟)
                } else {
                    model.setPlanEndTime(model.getEndTime());
/*                    if (StringUtils.isEmpty(model.getTaskBatchId())) {//未创建远程任务
                        model.setPlanEndInfo("[提醒]未创建批量任务");
                    }*/
                }
            }

            resList.add(model);
        }
        resMap.put("total", pageObject.getTotal());
        resMap.put("list", resList);
        return resMap;
    }

    public TCheckModel saveTCheck(TCheckModel model) {
        model.setCheckId(StringUtil.getUuid());
        model.setCreateTime(new Date());
        if (StringUtils.isEmpty(model.getBatFlag())) {//默认非电池供电
            model.setBatFlag("0");
        }
        if (StringUtils.isEmpty(model.getAutoBatchFlag())) {
            model.setAutoBatchFlag("0");
        } else if (model.getAutoBatchFlag().equals("0")) {//不启用自动配置,则清空自动配置的天线类型
            model.setAutoBatchAntennaType("");
        }
        if (StringUtils.isEmpty(model.getDelaySwitchTaskFlag())) {
            model.setDelaySwitchTaskFlag("0");
        }
        TCheck TCheck = new TCheck();
        BeanUtils.copyProperties(model, TCheck);
        int insert = tCheckMapper.insert(TCheck);
        model.setId(TCheck.getId());
        return model;
    }

    public TCheckModel updateTCheck(TCheckModel model) {
        if (StringUtils.isNotEmpty(model.getAutoBatchFlag())) {
            if (!model.getAutoBatchFlag().equals("1")) {//不启用自动配置,则清空自动配置的天线类型
                model.setAutoBatchAntennaType("");
            }
        } else {
            model.setAutoBatchFlag("0");//兼容历史数据
            model.setAutoBatchAntennaType("");
        }

        TCheck TCheck = tCheckMapper.selectByPrimaryKey(model.getId());
        BeanUtils.copyProperties(model, TCheck);
        int i = tCheckMapper.updateByPrimaryKey(TCheck);
        return model;
    }

    public int deleteTCheck(int id) {
        int i = tCheckMapper.deleteByPrimaryKey(id);
        return i;
    }

    /**
     * 开始拷机
     *
     * @param id
     * @param isAutoCfg 是否自动配置(自动创建拷机间隔的批量任务)
     * @return
     */
    public TCheckModel startStressTesting(int id, boolean isAutoCfg) {
        TCheckModel resModel = new TCheckModel();
        Date nowdate = new Date();
        TCheck tCheck = tCheckMapper.selectByPrimaryKey(id);
        tCheck.setStartTime(nowdate);

        String chkptId = "";
        List<String> chkptNames = new ArrayList<>();
        //更新明细开始时间
        List<TCheckDetailModel> detailsModelList = tCheckDetailService.findDetailsByCheckId(tCheck.getCheckId());
        for (TCheckDetailModel detailModel : detailsModelList) {
            if (!chkptId.equals(detailModel.getChkpaltId())) {
                chkptId = detailModel.getChkpaltId();
                DicChkplatModel chkplatModel = dicChkplatService.findDicChkplatByPlatId(chkptId);
                if (chkplatModel != null) {
                    chkptNames.add(chkplatModel.getPlatName());
                }
            }
            detailModel.setStartTime(tCheck.getStartTime());
            //设置应收总量
            int checkDays = detailModel.getCheckDays();
            int checkIntverl = detailModel.getCheckIntverl();
            int revallNum = checkDays * 24 * 60 / checkIntverl;
            detailModel.setRevAllNum(revallNum);
            tCheckDetailService.updateTCheckDetail(detailModel);
            //更新设备状态
            DeviceAccModel deviceAccModel = deviceAccService.findDeviceAccBysn(detailModel.getDeviceSn());
            if (deviceAccModel != null) {
                deviceAccModel.setCurStateType(DeviceState.Kaoji.getFlag());
                deviceAccService.updateDeviceAcc(deviceAccModel);
                batteryAccService.updateBatteryStatus(deviceAccModel.getBatCode(), DeviceState.Kaoji.getFlag());//更新电池状态
            }
        }

        if (chkptNames.size() > 0) {
            tCheck.setPlatName(String.join(",", chkptNames));
        }
        tCheckMapper.updateByPrimaryKey(tCheck);
        BeanUtils.copyProperties(tCheck, resModel);

        if (isAutoCfg) {
            batchConfigureDevicesBeforeStressTest(tCheck, detailsModelList);
        }

        //开始拷机后,自动生成召测任务 2022-12-26 guozhao
        //注释了,现在在根据IMEI配置SN时已经下发过配置ID的任务,因此不再需要召测了 2025-01-21 guozhao
        //tTaskDownService.generateTaskDownByCheckDetails(detailsModelList);
        return resModel;
    }

    /**
     * 在拷机任务开始之前，批量配置设备
     *
     * @param tCheck
     * @param detailModels
     */
    private void batchConfigureDevicesBeforeStressTest(TCheck tCheck, List<TCheckDetailModel> detailModels) {
        //处理设备明细
        List<TaskBatchRemoteDetailModel> batchRemoteDetailModels = new ArrayList<>();
        for (TCheckDetailModel checkDetailModel : detailModels) {
            TaskBatchRemoteDetailModel taskBatchRemoteDetailModel = new TaskBatchRemoteDetailModel();
            taskBatchRemoteDetailModel.setDeviceSn(checkDetailModel.getDeviceSn());
            batchRemoteDetailModels.add(taskBatchRemoteDetailModel);
        }

        TaskBatchRemoteModel batchRemoteModel = new TaskBatchRemoteModel();
        batchRemoteModel.setTaskType("1");
        batchRemoteModel.setTaskDescribe("[开始拷机]" + tCheck.getCheckName());
        //处理配置项(配置设备采样间隔为拷机中的间隔)
        TaskRemoteCfgModel cfgModel = new TaskRemoteCfgModel();
        cfgModel.setSampleInterval(tCheck.getCheckIntverl());

        batchRemoteModel.setCreateMan(tCheck.getCreateMan());
        batchRemoteModel.setDetailModels(batchRemoteDetailModels);
        batchRemoteModel.setTaskRemoteCfgModel(cfgModel);
        batchRemoteModel.setMemo("系统托管创建");
        batchRemoteModel.setExecutionTime(new Date());
        batchRemoteModel.setSourceTaskId(tCheck.getCheckId());

        taskBatchRemoteService.saveTaskBatchRemote(batchRemoteModel);
    }

    //结束拷机方法
    public TCheckModel endStressTesting(TCheckModel model) {
        TCheck tCheck = tCheckMapper.selectByPrimaryKey(model.getId());
        if (tCheck != null && tCheck.getEndTime() != null) {//已经结束了(防止系统自动结束后,前台未刷新,又点了)
            return model;
        }
        model.setEndTime(new Date());
        updateTCheck(model);
        //更新明细结束时间
        List<TCheckDetailModel> detailsModelList = tCheckDetailService.findDetailsByCheckId(model.getCheckId());
        List<TaskBatchRemoteDetailModel> batchRemoteDetailModels = new ArrayList<>();
        for (int i = 0; i < detailsModelList.size(); i++) {
            TCheckDetailModel detailModel = detailsModelList.get(i);
            detailModel.setEndTime(model.getEndTime());
            //设置应收
            int sencondsbetweenTime = DateUtil.getSencondsbetweenTime(model.getStartTime(), model.getEndTime());
            int nowyinshou = sencondsbetweenTime / 60 / detailModel.getCheckIntverl();
            detailModel.setMustRevNum(nowyinshou);
            //设置实际接收
            int realnum = tAireadService.findtotalnumBySnAndTime(detailModel.getDeviceSn(), model.getStartTime(), model.getEndTime());
            detailModel.setRealRevNum(realnum);
            tCheckDetailService.updateTCheckDetail(detailModel);

            TaskBatchRemoteDetailModel taskBatchRemoteDetailModel = new TaskBatchRemoteDetailModel();
            taskBatchRemoteDetailModel.setDeviceSn(detailModel.getDeviceSn());
            batchRemoteDetailModels.add(taskBatchRemoteDetailModel);
        }
        //生成拷机报告
        tChkrptService.generateTChkrpt(model.getCheckId(), model.getCreateMan(), true);

        //提前结束的,批量修改采样间隔的任务 2025-06-12 guozhao
        if (StringUtils.isNotEmpty(tCheck.getEarlyFlag()) && tCheck.getEarlyFlag().equals("1")) {
            TaskBatchRemoteModel batchRemoteModel = new TaskBatchRemoteModel();
            batchRemoteModel.setTaskType("5");
            batchRemoteModel.setTaskDescribe("[结束拷机]" + tCheck.getCheckName());
            //处理配置项(配置设备采样间隔为拷机中的间隔)
            TaskRemoteCfgModel cfgModel = new TaskRemoteCfgModel();
            cfgModel.setSampleInterval(BaseConstant.MAX_SAMPLE_INTERVAL);

            batchRemoteModel.setCreateMan(tCheck.getCreateMan());
            batchRemoteModel.setDetailModels(batchRemoteDetailModels);
            batchRemoteModel.setTaskRemoteCfgModel(cfgModel);
            batchRemoteModel.setMemo("系统托管创建");
            batchRemoteModel.setExecutionTime(new Date());
            batchRemoteModel.setSourceTaskId(tCheck.getCheckId());

            taskBatchRemoteService.saveTaskBatchRemote(batchRemoteModel);
        }
        return model;
    }

    //快速添加拷机明细调用方法
    public TCheckModel addDetail(int id, String platId, String deviceSns) {
        TCheckModel resModel = new TCheckModel();
        TCheck tCheck = tCheckMapper.selectByPrimaryKey(id);
        List<TCheckDetailModel> detailList = new ArrayList<>();
        DicChkplatModel platModel = dicChkplatService.findDicChkplatByPlatId(platId);
        List<DicChkplatCellModel> cellList = dicChkplatCellService.findAllDicChkplatCell(platId);
        String[] split = deviceSns.split(",");

        Stream<String> stream = Arrays.stream(split);
        List<String> list = stream.distinct().collect(Collectors.toList());

        //SN防重 2022-08-15 guozhao
        List<TCheckDetailModel> recordList = tCheckDetailService.findDetailsByCheckId(tCheck.getCheckId());

        for (int i = 0; i < list.size(); i++) {
            String sn = split[i];

            if (recordList != null && recordList.size() > 0) {
                if (recordList.stream().filter(e -> e.getDeviceSn().equals(sn)).count() > 0) {
                    continue;       //SN 已经存在了
                }
            }
            TCheckDetailModel detailModel = new TCheckDetailModel();
            detailModel.setCheckId(tCheck.getCheckId());
            detailModel.setDetailId(StringUtil.getUuid());
            detailModel.setDeviceSn(split[i]);
            detailModel.setCheckDays(tCheck.getCheckDays());
            detailModel.setCheckIntverl(tCheck.getCheckIntverl());
            detailModel.setChkpaltId(platModel.getPlatId());
            detailModel.setCellId(cellList.get(i).getCellId());
            detailModel.setStdValue(cellList.get(i).getStdValue());
            detailModel.setCellStaticFlag(cellList.get(i).getStaticFlag());
            tCheckDetailService.saveTCheckDetail(detailModel);
            detailList.add(detailModel);
        }
        tCheck.setCheckDeviceNum(detailList.size());
        BeanUtils.copyProperties(tCheck, resModel);
        updateTCheck(resModel);
        resModel.setDetailList(detailList);
        return resModel;
    }

    //快速添加拷机明细调用方法(包含电池) 2023-01-31 guozhao
    public TCheckModel addDetail(TCheckModel tCheckModel) {
        TCheck tCheck = tCheckMapper.selectByPrimaryKey(tCheckModel.getId());//前台只提供了id,因此再查一次
        List<TCheckDetailModel> newDetailList = tCheckModel.getDetailList();
        BeanUtils.copyProperties(tCheck, tCheckModel);

        DicChkplatModel platModel = dicChkplatService.findDicChkplatByPlatId(newDetailList.get(0).getChkpaltId());
        List<DicChkplatCellModel> cellList = dicChkplatCellService.findAllDicChkplatCell(newDetailList.get(0).getChkpaltId());

        for (int i = 0; i < newDetailList.size(); i++) {
            TCheckDetailModel detailModel = newDetailList.get(i);
            detailModel.setCheckId(tCheckModel.getCheckId());
            detailModel.setDetailId(StringUtil.getUuid());
            detailModel.setCheckDays(tCheckModel.getCheckDays());
            detailModel.setCheckIntverl(tCheckModel.getCheckIntverl());
            detailModel.setChkpaltId(platModel.getPlatId());
            detailModel.setCellId(cellList.get(i).getCellId());
            detailModel.setStdValue(cellList.get(i).getStdValue());
            detailModel.setCellStaticFlag(cellList.get(i).getStaticFlag());
            if (tCheckDetailService.saveTCheckDetail(detailModel) != null) {
                DeviceAccModel deviceAcc = deviceAccService.findDeviceAccBysn(detailModel.getDeviceSn());
                if (deviceAcc != null) {//更新电池与设备的绑定关系
                    deviceAcc.setBatCode(detailModel.getBatCode());
                    deviceAccService.updateDeviceAcc(deviceAcc);
                }
            }
        }

        //当前的明细
        List<TCheckDetailModel> curDetailList = tCheckDetailService.findDetailsByCheckId(tCheckModel.getCheckId());
        tCheckModel.setCheckDeviceNum(curDetailList.size());

        updateTCheck(tCheckModel);
        tCheckModel.setDetailList(curDetailList);
        return tCheckModel;
    }

    //根据checkid查找拷机主表
    public TCheckModel findBycheckById(String checkId) {
        TCheckModel resModel = new TCheckModel();
        TCheckExample example = new TCheckExample();
        TCheckExample.Criteria criteria = example.createCriteria();
        TCheckExample.Criteria criteria1 = criteria.andCheckIdEqualTo(checkId);
        List<TCheck> tChecks = tCheckMapper.selectByExample(example);
        if (tChecks == null || tChecks.size() == 0) {//不知为何为空 2022-10-31 guozhao
            return resModel;
        }
        BeanUtils.copyProperties(tChecks.get(0), resModel);
        List<TCheckDetailModel> detailsList = tCheckDetailService.findDetailsByCheckId(checkId);
        //设置当前应收，实际接收数量
        Date nowtime = resModel.getEndTime() == null ? new Date() : resModel.getEndTime();
        if (resModel.getStartTime() != null) {
            Date planEndTime = DateUtil.getOtherDateByCurrentDate(resModel.getStartTime(), resModel.getCheckDays());
            if (nowtime.compareTo(planEndTime) > 0) {
                nowtime = planEndTime;
            }
        }

        for (TCheckDetailModel model : detailsList) {
            if (model.getStartTime() == null) {
                continue;
            }

            //由于后续出货MCU侧125版本未配置前不再识别,因此要使用服务器侧识别了
            Map<String, TServerReadModel> serverReadMap = serverReadService.queryTServerReadModelsByDeviceSnAndTime(model.getDeviceSn(), model.getStartTime(), nowtime);

            if (model.getEndTime() != null) {
                nowtime = model.getEndTime();
            }
            int checkIntverl = model.getCheckIntverl();
            int sencondsbetweenTime = DateUtil.getSencondsbetweenTime(model.getStartTime(), nowtime);
            int nowyinshou = sencondsbetweenTime / 60 / checkIntverl;
            List<TAireadModel> tairedList = tAireadService.findAllTaireadBySnAndTime(model.getDeviceSn(), model.getStartTime(), nowtime);
            //根据采样时间去重,在燃气表测试时,会有重发机制,但不能参与统计 2024-01-12 guozhao
            tairedList = tairedList.stream().collect(Collectors.collectingAndThen(
                    Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TAireadModel::getSampleTime))),
                    ArrayList::new
            ));

            model.setMustRevNum(nowyinshou);
            model.setRealRevNum(tairedList.size());
            //设置完整率
            if (nowyinshou > 0) {
                model.setRevIntegRate(new BigDecimal(tairedList.size()).divide(new BigDecimal(model.getMustRevNum()), 2, BigDecimal.ROUND_HALF_UP));
            } else {
                model.setRevIntegRate(new BigDecimal(0));
            }
            model.setRevIntegRate(model.getRevIntegRate().movePointRight(2));
            int correctnum = 0;
            int originalcorrectnum = 0;//原始数据正确数量
            int xinhaohegenum = 0;
            int voltagenum = 0;

            BigDecimal data_accuracy = null;
            BigDecimal originaldataAccuracy = null;
            BigDecimal xinhaohegelv = null;
            BigDecimal dianyahegelv = null;

            for (int j = 0; j < tairedList.size(); j++) {
                TAireadModel airm = tairedList.get(j);
                //注释:改为使用服务器识别结果判断 2025-07-11 guozhao
                /*if (airm.getRawValue() != null && airm.getRawValue().intValue() == model.getStdValue()) {
                    originalcorrectnum++;
                }*/
                if (serverReadMap.containsKey(airm.getAireadId()) && serverReadMap.get(airm.getAireadId()).getIdentValue() != null) {
                    TServerReadModel serverReadModel = serverReadMap.get(airm.getAireadId());
                    //说明:此处要判断是否是1278,从而排除服务器使用了前值的情况 2025-07-11 guozhao
                    if (serverReadModel.getIdentValue().intValue() == model.getStdValue()) {
                        if (BaseConstant.IDENT_GOOD_FLAG.contains(serverReadModel.getGoodFlag())) {//符合1278
                            originalcorrectnum++;
                        }
                    }
                }

                if (airm.getIdentValue() != null && airm.getIdentValue().intValue() == model.getStdValue()) {
                    correctnum++;
                }
                if (airm.getRsrp() != null && airm.getRsrp().intValue() > 50) {
                    xinhaohegenum++;
                }
                if (airm.getVoltage() != null && airm.getVoltage().doubleValue() >= 3.3 && airm.getVoltage().doubleValue() <= 3.8) {        //3.6改为3.8 2022-08-29 guozhao
                    voltagenum++;
                }
            }
            if (tairedList.size() == 0) {
                data_accuracy = new BigDecimal(0);
                originaldataAccuracy = new BigDecimal(0);
                xinhaohegelv = new BigDecimal(0);
                dianyahegelv = new BigDecimal(0);
            } else {
                data_accuracy = new BigDecimal(correctnum).divide(new BigDecimal(tairedList.size()), 2, BigDecimal.ROUND_HALF_DOWN);
                originaldataAccuracy = new BigDecimal(originalcorrectnum).divide(new BigDecimal(tairedList.size()), 2, BigDecimal.ROUND_HALF_DOWN);
                xinhaohegelv = new BigDecimal(xinhaohegenum).divide(new BigDecimal(tairedList.size()), 2, BigDecimal.ROUND_HALF_DOWN);
                dianyahegelv = new BigDecimal(voltagenum).divide(new BigDecimal(tairedList.size()), 2, BigDecimal.ROUND_HALF_DOWN);

                //计算下一次接收时间 2022-10-31 guozhao
                Date nextDate = DateUtil.getOtherDateByMinute(tairedList.get(tairedList.size() - 1).getSampleTime(), resModel.getCheckIntverl());
                model.setNextRevTime(nextDate);
            }
            //原始识别准确率
            model.setRecogAccuracy(originaldataAccuracy.movePointRight(2));
            //最终准确率
            model.setFinalAccuracy(data_accuracy.movePointRight(2));
            //信号合格率
            model.setRsrpQualRate(xinhaohegelv);
            //电压合格率
            model.setVtQualRate(dianyahegelv);
            tCheckDetailService.updateTCheckDetail(model);
        }

        resModel.setPlanEndInfo("");
        //推算计划结束时间2022-10-29 guozhao
        if (resModel.getStartTime() != null) {
            if (resModel.getEndTime() == null) {
                Date startTime = resModel.getStartTime();
                Date endTime = DateUtil.getOtherDateByCurrentDate(startTime, resModel.getCheckDays());
                resModel.setPlanEndTime(endTime);
                resModel.setPlanEndInfo(calculateDuration(endTime));
                //计算距离结束时间的间隔(n天n时n分钟)
            } else {
                resModel.setPlanEndTime(resModel.getEndTime());
/*                if (StringUtils.isEmpty(resModel.getTaskBatchId())) {//未创建远程任务
                    resModel.setPlanEndInfo("[提醒]未创建批量任务");
                }*/
            }
        }

        resModel.setDetailList(detailsList);
        return resModel;
    }

    //根据checkid查找拷机主表不封装明细
    public TCheckModel findBycheckByIdWithOutMx(String checkId) {
        TCheckModel resModel = new TCheckModel();
        TCheckExample example = new TCheckExample();
        TCheckExample.Criteria criteria = example.createCriteria();
        TCheckExample.Criteria criteria1 = criteria.andCheckIdEqualTo(checkId);
        List<TCheck> tChecks = tCheckMapper.selectByExample(example);
        if (tChecks != null && tChecks.size() > 0) {
            BeanUtils.copyProperties(tChecks.get(0), resModel);
        }

        return resModel;
    }

    /**
     * 删除拷机明细(同时更新拷机表的设备数量)
     *
     * @param detailId
     */
    public Integer deleteDetail(int detailId) {
        TCheckDetail detail = tCheckDetailService.findTCheckDetailById(detailId);
        int delNum = tCheckDetailService.deleteTCheckDetail(detailId);
        if (delNum > 0 && detail != null) {
            TCheckExample example = new TCheckExample();
            TCheckExample.Criteria criteria = example.createCriteria();
            TCheckExample.Criteria criteria1 = criteria.andCheckIdEqualTo(detail.getCheckId());
            List<TCheck> tChecks = tCheckMapper.selectByExample(example);
            if (tChecks != null && tChecks.size() == 1) {
                TCheck tCheck = tChecks.get(0);
                List<TCheckDetailModel> detailModels = tCheckDetailService.findDetailsByCheckId(tCheck.getCheckId());
                tCheck.setCheckDeviceNum(detailModels == null ? 0 : detailModels.size());
                tCheckMapper.updateByPrimaryKey(tCheck);
            }
        }
        return delNum;
    }

    /**
     * 计算距离结束的时间间隔(天时分)
     *
     * @param targetDate
     */
    private String calculateDuration(Date targetDate) {
        Date now = new Date();
        long sc = Math.abs((targetDate.getTime() - now.getTime()) / 1000);
        long days = sc / 60 / 60 / 24;
        sc = sc - days * 60 * 60 * 24;
        long hour = sc / 60 / 60;
        sc = sc - hour * 60 * 60;
        long minute = sc / 60;

        StringBuffer sb = new StringBuffer();
        if (targetDate.compareTo(now) == -1) {
            sb.append("[超时]");
        } else {
            sb.append("[剩余]");
        }
        sb.append(StringUtils.leftPad(days + "", 2, '0'));
        sb.append("天");
        sb.append(StringUtils.leftPad(hour + "", 2, '0'));
        sb.append("时");
        sb.append(StringUtils.leftPad(minute + "", 2, '0'));
        sb.append("分");

        return sb.toString();
    }

    public String checkDataLegitimacy(String deviceSns) {
        if (StringUtils.isEmpty(deviceSns)) {
            return "请先添加设备";
        }
        String[] split = deviceSns.split(",");
        for (String sn : split) {
            DeviceAccModel devAcc = deviceAccService.findDeviceAccBysn(sn);
            if (devAcc == null) {
                return "[" + sn + "]不在设备台账中";
            }
        }
        return null;
    }

    public String checkDataLegitimacy(TCheckModel model) {
        List<TCheckDetailModel> detailList = model.getDetailList();
        if (detailList == null || detailList.size() == 0) {
            return "请先添加设备";
        }
        TCheck tCheck = tCheckMapper.selectByPrimaryKey(model.getId());//前台只提供了id,因此再查一次
        List<TCheckDetailModel> details = tCheckDetailService.findDetailsByCheckId(tCheck.getCheckId());

        List<String> deviceSns = details.stream()
                .map(TCheckDetailModel::getDeviceSn)
                .collect(Collectors.toList());

        for (TCheckDetailModel detail : detailList) {
            DeviceAccModel devAcc = deviceAccService.findDeviceAccBysn(detail.getDeviceSn());
            if (devAcc == null) {
                return "[" + detail.getDeviceSn() + "]不在设备台账中";
            }
            if (StringUtils.isNotEmpty(detail.getBatCode())) {
                BatteryAccModel batAcc = batteryAccService.findBatteryAccByBatCode(detail.getBatCode());
                if (batAcc == null) {
                    return "[" + detail.getDeviceSn() + "]不在电池台账中";
                }
            }

            if (deviceSns.contains(detail.getDeviceSn())) {
                return "[" + detail.getDeviceSn() + "]已存在";
            }
            deviceSns.add(detail.getDeviceSn());
        }
        return "";
    }

    /**
     * 检测未完成的任务,如果超时自动结束
     */
    public void checkUnfinishedPlan() {
        try {
            TCheckExample example = new TCheckExample();
            TCheckExample.Criteria criteria = example.createCriteria();
            criteria.andStartTimeIsNotNull();
            criteria.andEndTimeIsNull();

            List<TCheck> tChecks = tCheckMapper.selectByExample(example);
            Date now = new Date();
            for (TCheck check : tChecks) {
                Date planEndTime = DateUtil.getOtherDateByCurrentDate(check.getStartTime(), check.getCheckDays());
                if (now.compareTo(planEndTime) > 0) {//超时自动结束
                    TCheckModel model = new TCheckModel();
                    BeanUtils.copyProperties(check, model);
                    endStressTesting(model);
                    generateforBatchTaskByTCheck(model, 1);//自动生成批量配置
                    log.info("拷机超时自动结束:" + model.getCheckName());
                }

                //切换天线的任务 2022-11-15 guozhao
                if (check.getDelaySwitchAntenna() != null && check.getDelaySwitchAntenna() > 0 &&
                        StringUtils.isNotEmpty(check.getDelaySwitchAntennaType()) && !check.getDelaySwitchTaskFlag().equals("1")) {
                    Date planSwitch = DateUtil.getOtherDateByHour(check.getStartTime(), check.getDelaySwitchAntenna());
                    if (now.compareTo(planSwitch) > 0) {//到了切换天线的时间
                        TCheckModel model = new TCheckModel();
                        BeanUtils.copyProperties(check, model);
                        String taskId = generateforBatchTaskByTCheck(model, 0);
                        if (StringUtils.isNotEmpty(taskId)) {
                            check.setDelaySwitchBatchId(taskId);
                        }
                        check.setDelaySwitchTaskFlag("1");
                        tCheckMapper.updateByPrimaryKey(check);
                        log.info("自动生成切换天线计划:" + model.getCheckName());
                    }
                }
            }
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
    }

    /**
     * 根据拷机对象获取明细中设备的最新一条数据(在拷机时间范围内的数据)
     *
     * @param model
     * @return
     */
    public Map<String, Object> findCheckDetailLatestAiRead(TCheckModel model) {
        Map<String, Object> resMap = new HashMap<>();
        List<TAireadModel> aireadModels = new ArrayList<>();
        if (model.getStartTime() != null) {
            List<TCheckDetailModel> detailModels = tCheckDetailService.findDetailsByCheckId(model.getCheckId());

            if (detailModels != null && detailModels.size() > 0) {
                for (TCheckDetailModel detail : detailModels) {
                    Date endTime = model.getEndTime() == null ? model.getPlanEndTime() : model.getEndTime();
                    TAireadModel aireadModel = tAireadService.findLatestTAireadModelBySnAndDateRange(detail.getDeviceSn(), model.getStartTime(), endTime);
                    if (aireadModel != null) {
                        List<TServerReadModel> sList = tServerReadService.findTServerReadByAiReadid(aireadModel.getAireadId());
                        if (sList != null && sList.size() > 0) {
                            aireadModel.setServerReadModel(sList.get(0));
                        }
                        aireadModels.add(aireadModel);
                    }
                }
            }
        }

        resMap.put("total", aireadModels.size());
        resMap.put("list", aireadModels);
        return resMap;
    }

    /**
     * 根据拷机计划名称模糊查询相关记录
     *
     * @param checkName
     * @return
     */
    public List<TCheckModel> findTCheckListByCheckName(String checkName) {
        if (StringUtils.isEmpty(checkName)) return null;
        TCheckExample example = new TCheckExample();
        TCheckExample.Criteria criteria = example.createCriteria();
        criteria.andCheckNameLike("%" + checkName + "%");

        List<TCheck> tChecks = tCheckMapper.selectByExample(example);
        List<TCheckModel> resList = new ArrayList<>();
        for (TCheck check : tChecks) {
            TCheckModel model = new TCheckModel();
            BeanUtils.copyProperties(check, model);
            resList.add(model);
        }
        return resList;
    }

    /**
     * 根据拷机对象生成批量任务(拷机结束后,自动配置时间间隔等)
     *
     * @param checkModel
     */
    public String generateforBatchTaskByTCheck(TCheckModel checkModel, int type) {
        if (StringUtils.isEmpty(checkModel.getAutoBatchFlag()) || !checkModel.getAutoBatchFlag().equals("1"))
            return "";

        List<TCheckDetailModel> detailModels = tCheckDetailService.findDetailsByCheckId(checkModel.getCheckId());

        //处理设备明细
        List<TaskBatchRemoteDetailModel> batchRemoteDetailModels = new ArrayList<>();
        for (TCheckDetailModel checkDetailModel : detailModels) {
            TaskBatchRemoteDetailModel taskBatchRemoteDetailModel = new TaskBatchRemoteDetailModel();
            taskBatchRemoteDetailModel.setDeviceSn(checkDetailModel.getDeviceSn());
            batchRemoteDetailModels.add(taskBatchRemoteDetailModel);
        }

        TaskBatchRemoteModel batchRemoteModel = new TaskBatchRemoteModel();
        //处理配置项
        TaskRemoteCfgModel cfgModel = new TaskRemoteCfgModel();
        if (type == 0) {//中途切换天线
            cfgModel.setTianxianType(checkModel.getDelaySwitchAntennaType());
            batchRemoteModel.setTaskType("6");
            batchRemoteModel.setTaskDescribe("[切换天线]" + checkModel.getCheckName());
        } else {//拷机结束后自动配置
            cfgModel.setSampleInterval(BaseConstant.MAX_SAMPLE_INTERVAL);
            cfgModel.setUpInterval(BaseConstant.MAX_SAMPLE_INTERVAL);
            if (StringUtils.isNotEmpty(checkModel.getAutoBatchAntennaType())) {
                cfgModel.setTianxianType(checkModel.getAutoBatchAntennaType());
            }
            batchRemoteModel.setTaskType("5");
            batchRemoteModel.setTaskDescribe("[自动结束]" + checkModel.getCheckName());
        }

        batchRemoteModel.setCreateMan(checkModel.getCreateMan());
        batchRemoteModel.setDetailModels(batchRemoteDetailModels);
        batchRemoteModel.setTaskRemoteCfgModel(cfgModel);
        batchRemoteModel.setMemo("系统托管创建");
        batchRemoteModel.setExecutionTime(new Date());
        batchRemoteModel.setSourceTaskId(checkModel.getCheckId());

        TaskBatchRemoteModel resModel = taskBatchRemoteService.saveTaskBatchRemote(batchRemoteModel);
        return resModel == null ? "" : resModel.getTaskBatchId();
    }
}
