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.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 WasteGasManager extends HibernateEntityDao<WasteGas> {

    @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 CO, String O2, String H2S, String CH4, Boolean isOpen) throws IOException {

        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            WasteGas wasteGas = new WasteGas(devCode, wellCode, DateUtils.
                    sdf4.parse(DateUtils.DateFormat(upTime)), CO, O2, H2S, CH4, isOpen);
            save(wasteGas);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }


    //获取告警等级
    public Map<String, Object> getAlarmContent(BusWell busWell, String devCode,
                                               String CO, String O2, String H2S, String CH4) {
        Map<String, Object> alarmMap = new HashMap<String, Object>();
        Integer alarmLevel = 10;
        String alarmContent = "";
        String alarmValue = "";
        String isAlarm = "1";//是否开启报警(1为开启)
        String isJob = "1";//是否开启工单(1为开启)
        if (busWell == null) return alarmMap;
        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 rankHighValue = ((Object[]) ruleRankList.get(j))[2];
            Object gasName = ((Object[]) ruleRankList.get(j))[3];
            if (gasName != null && nameArr[0].equals(gasName.toString())) {
                if (rankHighValue != null && Float.parseFloat(CO) >= Float.valueOf(rankHighValue.toString())) {
//                    WasteGasAlarmEnum wasteGasAlarmEnum = WasteGasAlarmEnum.getByIndex(
//                            String.valueOf(Long.valueOf(((Object[]) ruleRankList.get(j))[0].toString()) + 8));
//                    alarmContent += (wasteGasAlarmEnum == null ? WasteGasAlarmEnum.CO_OVER_THRESH.getName() :
//                            wasteGasAlarmEnum.getName()) + ",";
                    alarmContent += WasteGasAlarmEnum.CO_OVER_THRESH.getName() + ",";
                    alarmLevel = Integer.valueOf(((Object[]) ruleRankList.get(j))[0].toString());
                    alarmValue += "一氧化碳:" + CO + "ppm,";
                    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 (rankHighValue != null && Float.parseFloat(O2) >= Float.valueOf(rankHighValue.toString()) ||
                        rankLowValue != null && Float.parseFloat(O2) <= Float.valueOf(rankLowValue.toString())) {
//                    WasteGasAlarmEnum wasteGasAlarmEnum = WasteGasAlarmEnum.getByIndex(
//                            String.valueOf(Long.valueOf(((Object[]) ruleRankList.get(j))[0].toString()) + 14));
//                    alarmContent += (wasteGasAlarmEnum == null ? WasteGasAlarmEnum.O2_OVER_THRESH.getName() :
//                            wasteGasAlarmEnum.getName()) + ",";
                    alarmContent += WasteGasAlarmEnum.O2_OVER_THRESH.getName() + ",";
                    alarmLevel = alarmLevel > Integer.valueOf(((Object[]) ruleRankList.get(j))[0].toString()) ?
                            Integer.valueOf(((Object[]) ruleRankList.get(j))[0].toString()) : alarmLevel;
                    alarmValue += "氧气:" + O2 + "%VOL,";
                    break;
                }
            }
        }

        //获取甲烷告警等级
        for (int j = 0; j < ruleRankList.size(); j++) {
            Object rankHighValue = ((Object[]) ruleRankList.get(j))[2];
            Object gasName = ((Object[]) ruleRankList.get(j))[3];
            if (gasName != null && nameArr[2].equals(gasName.toString())) {
                if (rankHighValue != null && Float.parseFloat(CH4) >= Float.valueOf(rankHighValue.toString())) {
//                    WasteGasAlarmEnum wasteGasAlarmEnum = WasteGasAlarmEnum.getByIndex(
//                            String.valueOf(Long.valueOf(((Object[]) ruleRankList.get(j))[0].toString()) + 17));
//                    alarmContent += (wasteGasAlarmEnum == null ? WasteGasAlarmEnum.CH4_OVER_THRESH.getName() :
//                            wasteGasAlarmEnum.getName()) + ",";
                    alarmContent += WasteGasAlarmEnum.CH4_OVER_THRESH.getName() + ",";
                    alarmLevel = alarmLevel > Integer.valueOf(((Object[]) ruleRankList.get(j))[0].toString()) ?
                            Integer.valueOf(((Object[]) ruleRankList.get(j))[0].toString()) : alarmLevel;
                    alarmValue += "甲烷:" + CH4 + "%VOL,";
                    break;
                }
            }
        }

        //获取硫化氢告警等级
        for (int j = 0; j < ruleRankList.size(); j++) {
            Object rankHighValue = ((Object[]) ruleRankList.get(j))[2];
            Object gasName = ((Object[]) ruleRankList.get(j))[3];
            if (gasName != null && nameArr[3].equals(gasName.toString())) {
                if (rankHighValue != null && Float.parseFloat(H2S) >= Float.valueOf(rankHighValue.toString())) {
//                    WasteGasAlarmEnum wasteGasAlarmEnum = WasteGasAlarmEnum.getByIndex(
//                            String.valueOf(Long.valueOf(((Object[]) ruleRankList.get(j))[0].toString()) + 11));
//                    alarmContent += (wasteGasAlarmEnum == null ? WasteGasAlarmEnum.H2S_OVER_THRESH.getName() :
//                            wasteGasAlarmEnum.getName()) + ",";
                    alarmContent += WasteGasAlarmEnum.H2S_OVER_THRESH.getName() + ",";
                    alarmLevel = alarmLevel > Integer.valueOf(((Object[]) ruleRankList.get(j))[0].toString()) ?
                            Integer.valueOf(((Object[]) ruleRankList.get(j))[0].toString()) : alarmLevel;
                    alarmValue += "硫化氢:" + H2S + "ppm,";
                    break;
                }
            }
        }
        if (StringUtils.isNotBlank(alarmContent)) {
            alarmMap.put("alarmContent", alarmContent);
            alarmMap.put("alarmLevel", alarmLevel);
            alarmMap.put("alarmValue", alarmValue);
            alarmMap.put("isAlarm", isAlarm);
            alarmMap.put("isJob", isJob);
        }
        return alarmMap;
    }

    public void processNormalData(JSONObject jsonObject, String devCode) {
        JSONArray jsonArray = (JSONArray) jsonObject.get("datas");
        BusWell busWell = busWellManager.getWellByDevCode(devCode);
        for (int i = 0; i < jsonArray.size(); i++) {
            try {
                String CO = ((JSONObject) jsonArray.get(i)).get("CO").toString();
                String O2 = ((JSONObject) jsonArray.get(i)).get("O2").toString();
                String H2S = ((JSONObject) jsonArray.get(i)).get("H2S").toString();
                String CH4 = ((JSONObject) jsonArray.get(i)).get("CH4").toString();
                CO = String.format("%.2f", Double.valueOf(CO));
                O2 = String.format("%.2f", Double.valueOf(O2));
                H2S = String.format("%.2f", Double.valueOf(H2S));
                CH4 = String.format("%.2f", Double.valueOf(CH4));
                String upTime = ((JSONObject) jsonArray.get(i)).get("uptime").toString();
                Boolean isOpen = Boolean.valueOf(((JSONObject) jsonArray.get(i)).get("liquidSwitch").toString());
                //1.清离线
                deviceManager.clearOffline(devCode);
                //2.清除设备告警
                alarmRecordManager.clearAlarmByNormalData(devCode, "2");
                //3.存数据
                saveData(devCode, busWell == null ? "" : busWell.getWellCode(),
                        upTime, CO, O2, H2S, CH4, isOpen);//存采集数据
                //4.有无超限处理流程（判断最后一条数据）
                if (i < jsonArray.size() - 1) continue;
                //获取告警等级
                Map<String, Object> alarmMap = getAlarmContent(busWell, devCode, CO, O2, H2S, CH4);
                if (alarmMap.size() > 0) {
                    AlarmRecord alarmRecord = alarmRecordManager.getThresholdAlarm(devCode);
                    String alarmContent = alarmMap.get("alarmContent").toString();
                    Integer alarmLevel = Integer.valueOf(alarmMap.get("alarmLevel").toString());
                    String alarmValue = alarmMap.get("alarmValue").toString();
                    String isAlarm = alarmMap.get("isAlarm").toString();
                    String isJob = alarmMap.get("isJob").toString();
                    if (null != alarmRecord && "1".equals(isAlarm)) {//已存在报警
                        //1.清除上一条告警记录
                        alarmRecordManager.clearAlarm(devCode, "1", "");
                        //2.写入新的告警记录,更新工单号为上一条告警记录的工单号,若以前没开启工单，现在补提工单
                        Long jobID = alarmRecord.getJobId();
                        if ("1".equals(isJob) && null == jobID) {
                            //生成新的工单
                            AlarmJob alarmJob = alarmJobManager.saveData(devCode, alarmRecord.getWellCode(),
                                    DeviceTypeEnum.WasteGas.toString(), "1");
                            jobID=alarmJob.getId();
                            ThreadUtil.excuteMsg(jobID, "",busWell == null ? "" : busWell.getWellCode());
                        }else if("0".equals(isJob)){//不需要产生工单时
                            jobID=null;
                        }
                        alarmRecordManager.saveData(jobID, "1", alarmLevel,
                                WasteGasAlarmEnum.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 != null ?
                                    busWell.getWellCode() : "", DeviceTypeEnum.WasteGas.toString(), "1");
                        }

                        //2.写入新的告警
                        alarmRecordManager.saveData(alarmJob == null ? null : alarmJob.getId(), "1", alarmLevel,
                                WasteGasAlarmEnum.OVER_THRESH.getName(),
                                alarmValue.substring(0, alarmValue.length() - 1), device,
                                devCode, busWell != null ? 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 ? null : alarmJob.getId(), WasteGasAlarmEnum.OVER_THRESH.getName(),
                                busWell != null ? 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() + "失败-------");
            }
        }
    }


}
