package com.mvc.service.taizhang;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mvc.constant.DeviceAlarmType;
import com.mvc.dao.DeviceAlarmMapper;
import com.mvc.dao.StationAccMapper;
import com.mvc.dao.TAireadMapper;
import com.mvc.dao.TaskReviewMapper;
import com.mvc.entity.*;
import com.mvc.model.DeviceAlarmModel;
import com.mvc.model.TAffiliatedunitModel;
import com.mvc.service.TAffiliatedunitService;
import com.mvc.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
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.*;

@Service
@Transactional
public class DeviceAlarmService {

    @Resource
    private DeviceAlarmMapper deviceAlarmMapper;

    @Resource
    private StationAccMapper StationAccMapper;

    @Resource
    private TAireadMapper tAireadMapper;

    @Resource
    private TaskReviewMapper taskReviewMapper;

    @Resource
    private StationAccService stationAccService;

    @Resource
    private TAffiliatedunitService tAffiliatedunitService;

    public static HashMap<String, String> alarmMap = new HashMap<>();

    {
        alarmMap.put("1", "连续3天没有收到数据");
        alarmMap.put("2", "当天没收到数据");
        alarmMap.put("3", "当天不够三条,有16点");
        alarmMap.put("4", "当天不够三条,没有16点");
        alarmMap.put("5", "数据识别3个值不一致");
    }

    public Map<String, Object> findAllDeviceAlarm(DeviceAlarmModel model) {
        Integer page = model.getPage();
        Integer rows = model.getRows();
        Map<String, Object> resMap = new HashMap<>();
        DeviceAlarmExample example = new DeviceAlarmExample();
        DeviceAlarmExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(model.getAlarmType())) {
            criteria.andAlarmTypeEqualTo(model.getAlarmType());
        }
        if (StringUtils.isNotEmpty(model.getAlarmTime())) {
            criteria.andAlarmTimeEqualTo(model.getAlarmTime());
        }
        //根据参数的单位代码,过滤能看到的数据 2022-09-30 guozhao
        if (StringUtils.isNotEmpty(model.getUnitCode())) {
            List<TAffiliatedunitModel> tAffiliatedunitModels = stationAccService.findTAffiliatedunitsByUnitCode(model.getUnitCode());
            if (tAffiliatedunitModels != null && tAffiliatedunitModels.size() > 0) {
                List<String> unitCodes = new ArrayList<>();
                tAffiliatedunitModels.forEach(s -> unitCodes.add(s.getUnitCode()));
                criteria.andUnitCodeIn(unitCodes);
            }
        }
        example.setOrderByClause("ALARM_TYPE");
        Page<Object> pageObject = PageHelper.startPage(page, rows);
        List<DeviceAlarm> DeviceAlarms = deviceAlarmMapper.selectByExample(example);
        List<DeviceAlarmModel> resList = new ArrayList<>();
        for (DeviceAlarm DeviceAlarm : DeviceAlarms) {
            DeviceAlarmModel resmodel = new DeviceAlarmModel();
            BeanUtils.copyProperties(DeviceAlarm, resmodel);
            resmodel.setAlarmType(DeviceAlarmType.findDeviceAlarmByflag(resmodel.getAlarmType()).getDesc());

            TAffiliatedunitModel affiliatedunitModel = tAffiliatedunitService.findTAffiliatedunit(resmodel.getUnitCode());
            if(affiliatedunitModel!=null){
                resmodel.setUnitName(affiliatedunitModel.getUnitName());
            }
            resList.add(resmodel);
        }
        resMap.put("total", pageObject.getTotal());
        resMap.put("list", resList);
        return resMap;
    }

    public DeviceAlarmModel saveDeviceAlarm(DeviceAlarmModel model) {
        DeviceAlarm DeviceAlarm = new DeviceAlarm();
        BeanUtils.copyProperties(model, DeviceAlarm);
        int insert = deviceAlarmMapper.insert(DeviceAlarm);
        model.setId(DeviceAlarm.getId());
        return model;
    }

    public DeviceAlarmModel updateDeviceAlarm(DeviceAlarmModel model) {
        DeviceAlarm DeviceAlarm = deviceAlarmMapper.selectByPrimaryKey(model.getId());
        BeanUtils.copyProperties(model, DeviceAlarm);
        int i = deviceAlarmMapper.updateByPrimaryKey(DeviceAlarm);
        return model;
    }

    public int deleteDeviceAlarm(int id) {
        int i = deviceAlarmMapper.deleteByPrimaryKey(id);
        return i;
    }

    //根据日期和设备sn判断 判断前2天有无数据
    //将devsn改为stationCode 2023-11-24 guozhao
    public boolean judgeHasDateByCon(Date date, String stationCode) {
        Date beforeDate = DateUtil.getOtherDateByCurrentDate(date, -1);
        Date beforetwoDate = DateUtil.getOtherDateByCurrentDate(date, -2);

        DeviceAlarmExample example1 = new DeviceAlarmExample();
        DeviceAlarmExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andAlarmTimeEqualTo(DateUtil.formateDate(beforeDate, "yyyy-MM-dd"));
        //criteria1.andDeviceSnEqualTo(devsn);
        criteria1.andStationCodeEqualTo(stationCode);
        criteria1.andAlarmTypeEqualTo("2");
        List<DeviceAlarm> list1 = deviceAlarmMapper.selectByExample(example1);

        DeviceAlarmExample example2 = new DeviceAlarmExample();
        DeviceAlarmExample.Criteria criteria2 = example2.createCriteria();
        criteria2.andAlarmTimeEqualTo(DateUtil.formateDate(beforetwoDate, "yyyy-MM-dd"));
        //criteria2.andDeviceSnEqualTo(devsn);
        criteria2.andStationCodeEqualTo(stationCode);
        criteria2.andAlarmTypeEqualTo("2");
        deviceAlarmMapper.selectByExample(example2);
        List<DeviceAlarm> list2 = deviceAlarmMapper.selectByExample(example2);
        if (list1.size() > 0 && list2.size() > 0) {
            return true;
        } else {
            return false;
        }
    }


    public void generateDeviceAlarmByTime() {
        List<DeviceAlarmModel> alarmModelList = new ArrayList<DeviceAlarmModel>();
        Map<String, DeviceAlarmModel> map = new HashMap<>();
        Date nowdate = DateUtil.parseTimeStr(DateUtil.formateDate(new Date(), "yyyy-MM-dd"), "yyyy-MM-dd");
        DeviceAlarmExample alarmExample = new DeviceAlarmExample();
        DeviceAlarmExample.Criteria alarmCriteria1 = alarmExample.createCriteria();
        alarmCriteria1.andAlarmTimeEqualTo(DateUtil.formateDate(nowdate, "yyyy-MM-dd"));
        List<DeviceAlarm> deviceAlarms = deviceAlarmMapper.selectByExample(alarmExample);
        if (deviceAlarms.size() > 0) {
            return;
        }
        StationAccExample accExample = new StationAccExample();
        StationAccExample.Criteria acccriteria = accExample.createCriteria();
        //acccriteria.andDeviceSnIsNotNull();
        //acccriteria.andDeviceSnNotEqualTo("");//去掉SN与遥测站的绑定关联(维护起来较为麻烦) 2023-11-24 guozhao
        acccriteria.andUseFlagEqualTo("1");//设备在用的 2022-09-30 guozhao
        acccriteria.andDeviceSetupFlagEqualTo("1");//设备已经安装的
        List<StationAcc> stationAccs = StationAccMapper.selectByExample(accExample);
        StringBuffer devsns = new StringBuffer();
        for (StationAcc acc : stationAccs) {
            devsns.append(acc.getDeviceSn()).append(",");
            DeviceAlarmModel model = new DeviceAlarmModel();
            model.setStationCode(acc.getStationCode());
            model.setStationName(acc.getStationName());
            model.setDeviceSn(acc.getDeviceSn());//此时SN中并没有值(遥测站台账不再记录了) 2023-11-24 guozhao
            model.setAlarmTime(DateUtil.formateDate(nowdate, "yyyy-MM-dd"));
            model.setUnitCode(acc.getUnitCode());//2022-09-30 guozhao
            alarmModelList.add(model);
            map.put(model.getStationCode(), model);
        }

        TAireadExample aireadExample = new TAireadExample();
        TAireadExample.Criteria airedcriteria = aireadExample.createCriteria();
        airedcriteria.andSampleTimeGreaterThanOrEqualTo(nowdate);
        airedcriteria.andSampleTimeLessThan(DateUtil.getOtherDateByCurrentDate(nowdate, 1));
        List<TAiread> tAireads = tAireadMapper.selectByExample(aireadExample);
        //查询数据审核表，判断三个值是否相等
        TaskReviewExample taskReviewExample = new TaskReviewExample();
        TaskReviewExample.Criteria criteria = taskReviewExample.createCriteria();
        criteria.andSampleTimeGreaterThanOrEqualTo(nowdate);
        criteria.andSampleTimeLessThan(DateUtil.getOtherDateByCurrentDate(nowdate, 1));
        List<TaskReview> taskReviews = taskReviewMapper.selectByExample(taskReviewExample);

        //循环判断三个值是否相等
        for (int i = 0; i < taskReviews.size(); i++) {
            try {
                TaskReview taskReview = taskReviews.get(i);
                DeviceAlarmModel alarmModel = map.get(taskReview.getStationCode());
                if (alarmModel != null && taskReview.getServerValue() != null && taskReview.getReviewValue() != null && taskReview.getRawValue() != null) {
                    if (!(taskReview.getServerValue().doubleValue() == taskReview.getReviewValue().doubleValue()
                            && taskReview.getServerValue().doubleValue() == taskReview.getRawValue().doubleValue())) {//三个值不相等
                        alarmModel.getAlarmids().add(taskReview.getAireadId());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Map<String, DeviceAlarm> lowVolMap = new HashMap<>();//存储电压<=3.5的站点 2022-11-05 guozhao
        //循环数据，判断设备收到数据完整性，及16点数据完整性
        for (int i = 0; i < tAireads.size(); i++) {
            TAiread airead = tAireads.get(i);
            if (StringUtils.isNotEmpty(airead.getStationCode())) {
                DeviceAlarmModel alarmModel = map.get(airead.getStationCode());
                if (alarmModel != null) {
                    alarmModel.setRevnum(alarmModel.getRevnum() + 1);
                    Date sampleTime = airead.getSampleTime();
                    if (sampleTime.getHours() == 16) {
                        alarmModel.setSixteennum(1);
                    }

                    //找出电压不高于3.5的站点
                    if (!lowVolMap.containsKey(airead.getStationCode())) {
                        if (airead.getVoltage() != null && airead.getVoltage().compareTo(new BigDecimal(3.5)) < 1) {
                            DeviceAlarm temp = new DeviceAlarm();
                            BeanUtils.copyProperties(alarmModel, temp);
                            temp.setAlarmType(DeviceAlarmType.Low_voltage.getFlag());
                            lowVolMap.put(airead.getStationCode(), temp);
                        }
                    }
                    alarmModel.setDeviceSn(airead.getDeviceSn());//因为站点台账中没有SN了,从读数中获取一下 2023-11-24 guozhao
                }
                //判断跟遥测站设备sn是否一致，不一致，说明有多个设备
                if (alarmModel != null && airead.getDeviceSn() != null && alarmModel.getDeviceSn() != null) {
                    if (!airead.getDeviceSn().equals(alarmModel.getDeviceSn())) {
                        if (!alarmModel.getMapping_sn().contains(airead.getDeviceSn())) {
                            alarmModel.getMapping_sn().add(airead.getDeviceSn());
                        }
                    }
                }
            }
        }

        //报警信息入库
        for (int i = 0; i < alarmModelList.size(); i++) {
            DeviceAlarmModel model = alarmModelList.get(i);
            DeviceAlarm alarm = new DeviceAlarm();
            if (model.getRevnum() == 0) {//当天没有收到数据
                model.setAlarmType(DeviceAlarmType.NoData_today.getFlag());
                BeanUtils.copyProperties(model, alarm);
                deviceAlarmMapper.insert(alarm);
                //判断最近三天有没有收到数据
                //boolean flag = judgeHasDateByCon(nowdate, model.getDeviceSn());
                boolean flag = judgeHasDateByCon(nowdate, model.getStationCode());
                if (flag) {//最近三天没有收到数据
                    DeviceAlarm alarm5 = new DeviceAlarm();
                    BeanUtils.copyProperties(model, alarm5);
                    alarm5.setAlarmType(DeviceAlarmType.NoData_3days.getFlag());
                    deviceAlarmMapper.insert(alarm5);
                }
            } /*else if (model.getRevnum() < 3) {//当天数据不够三条
                if (model.getSixteennum() > 0) {//当天不够3条但有16点数据
                    model.setAlarmType(DeviceAlarmType.NoData_num3.getFlag());
                    BeanUtils.copyProperties(model, alarm);
                    deviceAlarmMapper.insert(alarm);
                } else {//当天数据不够三条也没有16点数据
                    model.setAlarmType(DeviceAlarmType.NoData_16hour.getFlag());
                    BeanUtils.copyProperties(model, alarm);
                    deviceAlarmMapper.insert(alarm);
                }
            }*/
            //添加三个值不一致数据
            List<String> alarmids = model.getAlarmids();
            for (int j = 0; j < alarmids.size(); j++) {
                String id = alarmids.get(j);
                DeviceAlarm saveEntity = new DeviceAlarm();
                BeanUtils.copyProperties(model, saveEntity);
                saveEntity.setAlarmType(DeviceAlarmType.NoEqual_three.getFlag());
                saveEntity.setAireadId(id);
                deviceAlarmMapper.insert(saveEntity);
            }
            //添加一个遥测站对应多个设备sn 预警
            if (model.getMapping_sn().size() == 1) {
                //不存在此类型错误了,站点台账不绑定SN了 2023-11-24 guozhao
                /*DeviceAlarm multiEntity = new DeviceAlarm();
                model.setAlarmType(DeviceAlarmType.error_mapping.getFlag());
                BeanUtils.copyProperties(model, multiEntity);
                deviceAlarmMapper.insert(multiEntity);*/
            } else if (model.getMapping_sn().size() > 1) {
                DeviceAlarm multiEntity = new DeviceAlarm();
                model.setAlarmType(DeviceAlarmType.Multi_Sns.getFlag());
                BeanUtils.copyProperties(model, multiEntity);
                deviceAlarmMapper.insert(multiEntity);
            }
        }
        //定义工作时间预警信息model
        List<DeviceAlarmModel> alarm_timeout = new ArrayList<>();
        //判断工作时长预警
        TAireadExample timeoutExample = new TAireadExample();
        TAireadExample.Criteria timeoutcriteria = timeoutExample.createCriteria();
        Date beforeDate = DateUtil.getOtherDateByCurrentDate(nowdate, -1);
        timeoutcriteria.andSampleTimeGreaterThanOrEqualTo(beforeDate);
        timeoutcriteria.andSampleTimeLessThan(nowdate);
        List<TAiread> judjeimeoutAireads = tAireadMapper.selectByExample(timeoutExample);
        for (int i = 0; i < judjeimeoutAireads.size(); i++) {
            TAiread airead = judjeimeoutAireads.get(i);
            DeviceAlarmModel alarmModel = null;
            if (airead.getStationCode() != null) {
                alarmModel = map.get(airead.getStationCode());
            }
            //判断设备工作时长是否超时间
            if (alarmModel != null && airead.getIntervalMinutes() != null) {
                if (airead.getIntervalMinutes() > 30) {
                    DeviceAlarmModel model = new DeviceAlarmModel();
                    BeanUtils.copyProperties(alarmModel, model);
                    model.setAireadId(airead.getAireadId());
                    model.setAlarmType(DeviceAlarmType.Time_out30.getFlag());
                    model.setAlarmTime(DateUtil.formateDate(beforeDate, "yyyy-MM-dd"));
                    alarm_timeout.add(model);
                } else if (airead.getIntervalMinutes() > 45) {
                    DeviceAlarmModel model = new DeviceAlarmModel();
                    BeanUtils.copyProperties(alarmModel, model);
                    model.setAireadId(airead.getAireadId());
                    model.setAlarmType(DeviceAlarmType.Time_out45.getFlag());
                    model.setAlarmTime(DateUtil.formateDate(beforeDate, "yyyy-MM-dd"));
                    alarm_timeout.add(model);
                } else if (airead.getIntervalMinutes() > 60) {
                    DeviceAlarmModel model = new DeviceAlarmModel();
                    BeanUtils.copyProperties(alarmModel, model);
                    model.setAireadId(airead.getAireadId());
                    model.setAlarmType(DeviceAlarmType.Time_out60.getFlag());
                    model.setAlarmTime(DateUtil.formateDate(beforeDate, "yyyy-MM-dd"));
                    alarm_timeout.add(model);
                }
            }
        }
        //设备工作时长超时入库
        for (int i = 0; i < alarm_timeout.size(); i++) {
            DeviceAlarmModel model = alarm_timeout.get(i);
            DeviceAlarm alarm = new DeviceAlarm();
            BeanUtils.copyProperties(model, alarm);
            deviceAlarmMapper.insert(alarm);
        }

        //低电压的数据入库 2022-11-05 guozhao
        for(String key :lowVolMap.keySet()){
            deviceAlarmMapper.insert(lowVolMap.get(key));
        }
    }
}
