package org.well.well.manager;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.well.well.AlarmEnumDTO.TempHumiAlarmEnum;
import org.well.well.AlarmEnumDTO.WasteGasAlarmEnum;
import org.well.well.base.DeviceTypeEnum;
import org.well.well.core.hibernate.HibernateEntityDao;
import org.well.well.core.util.DateUtils;
import org.well.well.core.util.StringUtils;
import org.well.well.core.util.ThreadUtil;
import org.well.well.domain.*;
import org.well.well.util.PushList;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TempHumiManager extends HibernateEntityDao<TempHumi> {

    @Resource
    private AlarmRecordManager alarmRecordManager;
    @Resource
    private AlarmRuleManager alarmRuleManager;
    @Resource
    private DeviceManager deviceManager;
    @Resource
    private BusWellManager busWellManager;
    @Resource
    private AlarmJobManager alarmJobManager;
    @Resource
    private UserManager userManager;

    private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    private static String[] nameArr = {"温度", "湿度"};

    public Map<String, Object> saveData(String devCode,  String wellCode,String upTime,
                                        String temperature, String humidity, String cell) {

        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            TempHumi tempHumi = new TempHumi(devCode,  wellCode,
                    DateUtils.sdf4.parse(DateUtils.DateFormat(upTime)),

                    temperature, humidity, cell);
            save(tempHumi);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    public void processNormalData(JSONObject jsonObject, String devCode) {
        JSONArray jsonArray = (JSONArray) jsonObject.get("datas");
        String cell = jsonObject.get("cell").toString();
        BusWell busWell = busWellManager.getWellByDevCode(devCode);
        for (int i = 0; i < jsonArray.size(); i++) {
            try {
                String temperature = null != ((JSONObject) jsonArray.get(i)).get("temperature") ?
                        (String.format("%.2f", Double.valueOf(((JSONObject) jsonArray.get(i)).get("temperature").toString()))) : "";

                String humidity = null != ((JSONObject) jsonArray.get(i)).get("humidity") ?
                        (String.format("%.2f", Double.valueOf(((JSONObject) jsonArray.get(i)).get("humidity").toString()))) : "";
                String upTime = ((JSONObject) jsonArray.get(i)).get("uptime").toString();
                //1.清离线
                deviceManager.clearOffline(devCode);
                //2.清除设备告警
                alarmRecordManager.clearAlarmByNormalData(devCode, "2");
                //3.存数据
                saveData(devCode, busWell == null ? "" : busWell.getWellCode(), upTime,
                        temperature, humidity, cell);
                //4.有无超限处理流程（判断最后一条数据）
                if (i < jsonArray.size() - 1) continue;
                if (busWell != null) {//获取不到相关联的井，就无法获取告警规则，故不存库
                    String alarmContent = "", alarmValue = "",isAlarm="1",isJob="1";
                    Integer alarmLevel = 10;
                    List<Object[]> ruleRankList = alarmRuleManager.getRuleRank(devCode, busWell.getDeptid());
                    if (ruleRankList.size() > 0) {
                        isAlarm = ((Object[]) ruleRankList.get(ruleRankList.size() - 1))[4].toString();
                        isJob = ((Object[]) ruleRankList.get(ruleRankList.size() - 1))[5].toString();
                    }
                    //获取温度告警等级
                    for (int j = 0; j < ruleRankList.size(); j++) {
                        Object rankLowValue = ((Object[]) ruleRankList.get(j))[1];
                        Object rankHighValue = ((Object[]) ruleRankList.get(j))[2];
                        Object gasName = ((Object[]) ruleRankList.get(j))[3];
                        if (gasName != null && nameArr[0].equals(gasName.toString())) {
                            if ((StringUtils.isNotBlank(temperature) && null != rankHighValue &&
                                    Float.parseFloat(temperature) >= Float.parseFloat(rankHighValue.toString())) ||
                                    (StringUtils.isNotBlank(temperature) && null != rankLowValue &&
                                            Float.parseFloat(temperature) <= Float.parseFloat(rankLowValue.toString()))) {
//                                TempHumiAlarmEnum tempHumiAlarmEnum = TempHumiAlarmEnum.getByIndex(
//                                        String.valueOf(Long.valueOf(((Object[]) ruleRankList.get(j))[0].toString()) + 8));
//                                alarmContent += (tempHumiAlarmEnum == null ? TempHumiAlarmEnum.Temp_OVER_THRESH.getName() :
//                                        tempHumiAlarmEnum.getName()) + ",";
                                alarmContent += TempHumiAlarmEnum.Temp_OVER_THRESH.getName() + ",";
                                alarmValue += "温度:" + temperature + "℃,";
                                alarmLevel = Integer.valueOf(((Object[]) ruleRankList.get(j))[0].toString());
                                break;
                            }
                        }
                    }
                    //获取湿度告警等级
                    for (int j = 0; j < ruleRankList.size(); j++) {
                        Object rankLowValue = ((Object[]) ruleRankList.get(j))[1];
                        Object rankHighValue = ((Object[]) ruleRankList.get(j))[2];
                        Object gasName = ((Object[]) ruleRankList.get(j))[3];
                        if (gasName != null && nameArr[1].equals(gasName.toString())) {
                            if ((StringUtils.isNotBlank(humidity) && null != rankHighValue &&
                                    Float.parseFloat(humidity) >= Float.parseFloat(rankHighValue.toString())) ||
                                    (StringUtils.isNotBlank(humidity) && null != rankLowValue &&
                                            Float.parseFloat(humidity) <= Float.parseFloat(rankLowValue.toString()))) {
//                                TempHumiAlarmEnum tempHumiAlarmEnum = TempHumiAlarmEnum.getByIndex(
//                                        String.valueOf(Long.valueOf(((Object[]) ruleRankList.get(j))[0].toString()) + 11));
//                                alarmContent += (tempHumiAlarmEnum == null ? TempHumiAlarmEnum.Humi_OVER_THRESH.getName() :
//                                        tempHumiAlarmEnum.getName()) + ",";
                                alarmContent += TempHumiAlarmEnum.Humi_OVER_THRESH.getName() + ",";
                                alarmValue += "湿度:" + humidity + "%RH,";
                                alarmLevel = alarmLevel > Integer.valueOf(((Object[]) ruleRankList.get(j))[0].toString()) ?
                                        Integer.valueOf(((Object[]) ruleRankList.get(j))[0].toString()) : alarmLevel;
                                break;
                            }
                        }
                    }

                    if (StringUtils.isNotBlank(alarmContent)&&"1".equals(isAlarm)) {
                        AlarmRecord alarmRecord = alarmRecordManager.getThresholdAlarm(devCode);
                        if (null != alarmRecord) {//已存在报警
                            //1.清除上一条告警记录
                            alarmRecordManager.clearAlarm(devCode, "1", "");
                            //2.写入新的告警记录,更新工单号为上一条告警记录的工单号,若以前没开启工单，现在补提工单
                            Long jobID = alarmRecord.getJobId();
                            if ("1".equals(isJob) && null == jobID) {
                                //生成新的工单
                                AlarmJob alarmJob = alarmJobManager.saveData(devCode, alarmRecord.getWellCode(),
                                        DeviceTypeEnum.TempHumi.toString(), "1");
                                jobID=alarmJob.getId();
                                ThreadUtil.excuteMsg(jobID, "",busWell.getWellCode());
                            }else if("0".equals(isJob)){//不需要产生工单时
                                jobID=null;
                            }
                            alarmRecordManager.saveData(jobID, "1", alarmLevel,
                                    TempHumiAlarmEnum.OVER_THRESH.getName(),
                                    alarmValue.substring(0, alarmValue.length() - 1), alarmRecord.getDevice(), devCode,
                                    alarmRecord.getWellCode(), upTime,
                                    alarmContent.substring(0, alarmContent.length() - 1));
                        } else {//不存在上一条报警时
                            Device device = deviceManager.getDeviceByDevCode(devCode);
                            if (device == null) return;//未注册设备舍弃
                            AlarmJob alarmJob =null;
                            if("1".equals(isJob)){
                                //1.若开启工单，生成新的工单
                                 alarmJob = alarmJobManager.saveData(devCode,
                                        busWell.getWellCode(), DeviceTypeEnum.TempHumi.toString(),"1");
                            }

                            //2.写入新的告警
                            alarmRecordManager.saveData(alarmJob!=null?alarmJob.getId():null, "1", alarmLevel,
                                    TempHumiAlarmEnum.OVER_THRESH.getName(),
                                    alarmValue.substring(0, alarmValue.length() - 1), device,
                                    devCode, busWell.getWellCode(), upTime,
                                    alarmContent.substring(0, alarmContent.length() - 1));
//                        //3.toDo:向app推送报警消息
//                        List<String> cids = userManager.getClients(busWell);
//                        if (cids.size() > 0)
//                            PushList.pushToUser(cids, "液位超限", "报警啦，快来处理");
                            ThreadUtil.excuteMsg(alarmJob!=null?alarmJob.getId():null, TempHumiAlarmEnum.OVER_THRESH.getName(),
                                    busWell.getWellCode());
                        }
                    } else {//未超限
                        //1.清除之前的报警
                        alarmRecordManager.clearAlarmByNormalData(devCode, "1");
                        //2.结束之前的工单
                        alarmJobManager.updateAlarmJobByDevCode(devCode, "数据正常，系统自动结束工单");
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("--------ERROR:设备编号：" + devCode + "，存储数据：" + jsonArray.get(i).toString() + "失败-------");
            }
        }
    }

    public void processAlarmData(JSONObject jsonObject, String devCode) {
        JSONArray jsonArray = (JSONArray) jsonObject.get("eventType");
        String logTime = (jsonObject.get("logTime")).toString();
        for (int i = 0; i < jsonArray.size(); i++) {
            try {
                Device device = deviceManager.getDeviceByDevCode(devCode);
                if (null == device) return;//没注册设备舍弃
                //1.清除离线
                deviceManager.clearOffline(devCode);
                //2.清除同类型的报警信息
                alarmRecordManager.clearAlarm(devCode, "2",
                        String.valueOf(TempHumiAlarmEnum.valueOf(jsonArray.get(i).toString()).getIndex()));

                BusWell busWell = busWellManager.getWellByDevCode(devCode);
                //3.若无工单写入新的工单
                AlarmJob alarmJob = alarmJobManager.getByDevAndType(devCode,"0");
                if (null == alarmJob) {
                    alarmJob = alarmJobManager.saveData(devCode, busWell != null ?
                                    busWell.getWellCode() : "", DeviceTypeEnum.TempHumi.toString(),"0");
                }
                //4.写入新的报警
                alarmRecordManager.saveData(alarmJob.getId(), "2", null,
                        TempHumiAlarmEnum.valueOf(jsonArray.get(i).toString()).getName(),
                        String.valueOf(TempHumiAlarmEnum.valueOf(jsonArray.get(i).toString()).getIndex()),
                        device, devCode, null != busWell ? busWell.getWellCode() : "", logTime,
                        TempHumiAlarmEnum.valueOf(jsonArray.get(i).toString()).getName());

            } catch (IOException e) {
                e.printStackTrace();
                logger.error("--------ERROR:设备编号：" + devCode + "，存储报警数据：" + jsonArray.get(i).toString() + "失败-------");
            }
        }
    }
}
