package jtznyj.engineer.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jtznyj.common.api.ICommonApi;
import jtznyj.common.api.vo.AFocusWarn;
import jtznyj.engineer.common.FileUtil;
import jtznyj.engineer.entity.AFocusWarnSection;
import jtznyj.engineer.mapper.AFoucusWarnSectionMapper;
import jtznyj.engineer.service.IAFoucusWarnSectionService;
import jtznyj.engineer.service.IWellDataDiagnosticService;
import jtznyj.engineer.service.dataDiagnosticService.data.AlarmPoint;
import jtznyj.engineer.service.dataDiagnosticService.data.MonitorAlarmRange;
import jtznyj.engineer.service.dataDiagnosticService.data.MonitorAlarmRanges;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class AFoucusWarnSectionImpl extends ServiceImpl<AFoucusWarnSectionMapper, AFocusWarnSection> implements IAFoucusWarnSectionService {

    @Resource
    AFoucusWarnSectionMapper foucusWarnSectionMapper;
    @Autowired
    IWellDataDiagnosticService wellDataDiagnosticService;
    @Autowired
    ICommonApi iCommonApi;

    /**
     * 预警模板脚本
     *
     * @param jh
     * @param res
     */
    @Override
    public void savaWarnMessage(String jh, Map<String, MonitorAlarmRanges> res) {
        Map<String, Object> timeMap = new HashMap<>();

        ArrayList<AFocusWarn> saveList = new ArrayList<>();

        for (String modelName : res.keySet()) {

            AFocusWarn aFocusWarn = this.getLastAfoucusWarn(jh, modelName);
            //获取预警区间
            ArrayList<MonitorAlarmRange> rangeArrayList = res.get(modelName).children;
            if (rangeArrayList == null || rangeArrayList.size() == 0) {
                continue;
            }

            //获取(数据库)最新一条的数据
            AFocusWarnSection newWarnSection = this.getNewWarnSection(jh, modelName);

            for (MonitorAlarmRange range : rangeArrayList) {
                if (newWarnSection != null &&
                        (range.startDate.getTime() == newWarnSection.getStartTime().getTime() && range.endDate.getTime() > newWarnSection.getEndTime().getTime())) {
                    //合并时间
                    newWarnSection.setEndTime(range.endDate);
                    this.updateById(newWarnSection);

                } else if (newWarnSection == null || (range.startDate.getTime() > newWarnSection.getEndTime().getTime())) {
                    AFocusWarnSection aFocusWarnSection = this.setAfoucsSection(jh, modelName, range);
                    this.save(aFocusWarnSection);
                }

                //循环所有点
                ArrayList<AlarmPoint> points = range.details;
                for (AlarmPoint point : points) {

                    //是否判断KEY
                    String key = Double.toString(point.depth) + point.name + Double.toString(point.depth);
                    if (aFocusWarn != null && aFocusWarn.getKey().equals(key)) {
                        continue;
                    }
                    if (aFocusWarn != null && aFocusWarn.getWarnTime().getTime() > point.alarmDate.getTime()) {
                        continue;
                    }

                    if (timeMap.get(point.alarmDate.toString()) == null) {
                        AFocusWarn aFocusWarn1 = this.setFocusWarn(point, modelName, jh);
                        saveList.add(aFocusWarn1);
                    } else {
                        int warnKey = saveList.size() - 1;
                        AFocusWarn warn = saveList.get(warnKey);
                        warn.setBjnr(timeMap.get(point.alarmDate.toString()) + "\n" + point.des);
                        saveList.remove(warnKey);
                        saveList.add(warn);
                    }
                    timeMap.put(point.alarmDate.toString(), point.des);
                }
            }
//            System.out.println(saveList);
            //todo 保存方法到最后要打开
            for (AFocusWarn w : saveList) {
                iCommonApi.saveOneAFocusWarn(w);
            }

            saveList.clear();
            timeMap.clear();
        }
    }

    private AFocusWarnSection setAfoucsSection(String jh, String modelName, MonitorAlarmRange range) {
        AFocusWarnSection aFocusWarnSection = new AFocusWarnSection();
        aFocusWarnSection.setJh(jh);
        aFocusWarnSection.setCatogary(modelName);
        aFocusWarnSection.setStartTime(range.startDate);
        aFocusWarnSection.setEndTime(range.endDate);
        aFocusWarnSection.setDes(range.description);
        aFocusWarnSection.setCreated(new Date());
        return aFocusWarnSection;
    }

    private AFocusWarnSection getNewWarnSection(String JH, String modelName) {
        String sql = " select rownum a,t.* from (  select * from A_FOCUS_WARN_SECTION where JH = '" + JH + "' and CATOGARY  =  '" + modelName + "' order by END_TIME desc ) t where rownum<= 1 ";
        return foucusWarnSectionMapper.queryOneBySql(sql);
    }

    private AFocusWarn getLastAfoucusWarn(String jh, String catogary) {
        String warnHisSql = " select rownum a,t.* from (  select * from A_FOCUS_WARN where JH='%s' and SOURCE='工程预警' and CATOGARY ='%s' order by WARN_TIME desc ) t where rownum<= 1";
        warnHisSql = String.format(warnHisSql, jh, catogary);
        return iCommonApi.queryOneAFocusWarnWithSql(warnHisSql);
    }

    private AFocusWarn setFocusWarn(AlarmPoint point, String modelName, String jh) {
        String key = Double.toString(point.depth) + point.name + Double.toString(point.depth);
        AFocusWarn aFocusWarn = new AFocusWarn();
        aFocusWarn.setWarnTime(point.alarmDate);
        aFocusWarn.setCatogary(modelName);
        aFocusWarn.setSource("工程预警");
        aFocusWarn.setJh(jh);
        aFocusWarn.setBjnr(point.des);
        aFocusWarn.setKey(key);
        return aFocusWarn;
    }

    public List<MonitorAlarmRanges> getGcyjList(String jh, String time) {
        List<MonitorAlarmRanges> res = new ArrayList<>();
        List<AFocusWarnSection> sectionList = this.getSectionList(jh, time, true, "");
        if (sectionList == null || sectionList.size() == 0) {
            return new ArrayList<>();
        }

        for (AFocusWarnSection warnSection : sectionList) {
            MonitorAlarmRanges monitorAlarmRanges = new MonitorAlarmRanges(warnSection.getCatogary());
            List<AFocusWarnSection> sections = this.getSectionList(jh, time, false, warnSection.getCatogary());
            for (AFocusWarnSection w : sections) {
                MonitorAlarmRange range = new MonitorAlarmRange(w.getStartTime(), w.getEndTime());
                range.description = w.getDes();
                monitorAlarmRanges.modelColor = this.getModelColor(monitorAlarmRanges.groupName);
                monitorAlarmRanges.children.add(range);
            }
            res.add(monitorAlarmRanges);
        }
        return res;
    }
    public List<MonitorAlarmRanges> getGcyjList(String jh, String time1, String time2) {
        List<MonitorAlarmRanges> res = new ArrayList<>();
        List<AFocusWarnSection> sectionList = this.getSectionList(jh, time1,time2, true, "");
        if (sectionList == null || sectionList.size() == 0) {
            return new ArrayList<>();
        }

        for (AFocusWarnSection warnSection : sectionList) {
            MonitorAlarmRanges monitorAlarmRanges = new MonitorAlarmRanges(warnSection.getCatogary());
            List<AFocusWarnSection> sections = this.getSectionList(jh, time1,time2, false, warnSection.getCatogary());
            for (AFocusWarnSection w : sections) {
                MonitorAlarmRange range = new MonitorAlarmRange(w.getStartTime(), w.getEndTime());
                range.description = w.getDes();
                monitorAlarmRanges.modelColor = this.getModelColor(monitorAlarmRanges.groupName);
                monitorAlarmRanges.children.add(range);
            }
            res.add(monitorAlarmRanges);
        }
        return res;
    }

    public List<MonitorAlarmRanges> getGcyjResetList(String jh, String startTime, int min) {
        Date date = new Date();
        try {
            date = org.jeecg.common.util.DateUtils.parseDate(startTime, "yyyy-MM-dd");
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.DATE, 1);
            date = cal.getTime();

        } catch (Exception e) {
        }
        Map<String, MonitorAlarmRanges> monitorAlarmRangeMap = wellDataDiagnosticService.test(jh, date, min, true);
        List<MonitorAlarmRanges> res = new ArrayList<>();
        for (Map.Entry entry : monitorAlarmRangeMap.entrySet()) {
            MonitorAlarmRanges monitorAlarmRanges = monitorAlarmRangeMap.get(entry.getKey());
            monitorAlarmRanges.modelColor = this.getModelColor(monitorAlarmRanges.groupName);
            res.add(monitorAlarmRanges);
        }
        return res;
    }

    private List<AFocusWarnSection> getSectionList(String jh, String time, Boolean groupBy, String catogary) {
        String field = "*";
        if (groupBy) {
            field = "CATOGARY";
        }
        String sql = "select " + field + " from A_FOCUS_WARN_SECTION where jh='" + jh + "' ";
        String startTime = time + " 00:00:00";
        String endTime = time + " 23:59:59";
        sql += " and START_TIME>to_date('" + startTime + "', 'yyyy-MM-dd hh24:mi:ss')";
        sql += " and START_TIME<to_date('" + endTime + "', 'yyyy-MM-dd hh24:mi:ss')  ";
        if (!"".equals(catogary)) {
            sql += " and CATOGARY = '" + catogary + "' ";
        }
        if (groupBy) {
            sql += " group by CATOGARY ";
        } else {
            sql += " order by START_TIME ASC ";
        }
        return foucusWarnSectionMapper.getListBySql(sql);
    }
    private List<AFocusWarnSection> getSectionList(String jh, String time1,String time2, Boolean groupBy, String catogary) {
        String field = "*";
        if (groupBy) {
            field = "CATOGARY";
        }
        String sql = "select " + field + " from A_FOCUS_WARN_SECTION where jh='" + jh + "' ";
        String startTime =time1;
        String endTime = time2;
        sql += " and START_TIME>to_date('" + startTime + "', 'yyyy-MM-dd hh24:mi:ss')";
        sql += " and START_TIME<to_date('" + endTime + "', 'yyyy-MM-dd hh24:mi:ss')  ";
        if (!"".equals(catogary)) {
            sql += " and CATOGARY = '" + catogary + "' ";
        }
        if (groupBy) {
            sql += " group by CATOGARY ";
        } else {
            sql += " order by START_TIME ASC ";
        }
        return foucusWarnSectionMapper.getListBySql(sql);
    }

    private String getModelColor(String groupName) {
        try {
            Map FileMap = JSON.parseObject(FileUtil.read());
            return FileMap.get(groupName) == null ? "#e2534d" : FileMap.get(groupName).toString();

        } catch (Exception e) {

        }

        return "#e2534d";
    }
    //70  21

}
