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.base.DeviceTypeEnum;
import org.well.well.core.hibernate.HibernateEntityDao;
import org.well.well.core.util.DateUtils;
import org.well.well.domain.AlarmJob;
import org.well.well.domain.BusWell;
import org.well.well.domain.Device;
import org.well.well.domain.H2s;
import org.well.well.AlarmEnumDTO.H2SAlarmEnum;
import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class H2SManager extends HibernateEntityDao<H2s> {
    @Resource
    private AlarmRecordManager alarmRecordManager;
    @Resource
    private AlarmRuleManager alarmRuleManager;
    @Resource
    private DeviceManager deviceManager;
    @Resource
    private BusWellManager busWellManager;
    @Resource
    private AlarmJobManager alarmJobManager;

    private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    public Map<String, Object> saveData(String devcode, String wellCode,
                                        String strength, String cell, String uptime,
                                        String pci, String rsrp, String snr) {

        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            H2s h2s = new H2s(devcode, wellCode, strength, cell,
                    new Timestamp((DateUtils.sdf4.parse(DateUtils.DateFormat(uptime)).getTime())),
                    new Timestamp((new Date()).getTime()), pci, rsrp, snr);
            save(h2s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }


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

                //1.存数据
                saveData(devCode, busWell == null ? "" : busWell.getWellCode(), hs, cell, upTime, pci, rsrp, snr);
                //2.有无超限处理流程（判断最后一条数据）
                if (i < jsonArray.size() - 1) {
                    continue;
                }

                //4.清除设备告警
                alarmRecordManager.clearAlarmByNormalData(devCode, "");
                //获取报警阈值
                List<Object[]> ruleRankList = alarmRuleManager.getRuleRank(devCode);
                float rankThresh = 0;
                String isAlarm = "1";
                if (ruleRankList.size() > 0 && ruleRankList.get(0)[0] != null) {
                    Object rankValue = ((Object[]) ruleRankList.get(ruleRankList.size() - 1))[2];
                    rankThresh = rankValue != null ? Float.valueOf(rankValue.toString()) : 0;
                    isAlarm = ((Object[]) ruleRankList.get(ruleRankList.size() - 1))[4].toString();
                }

                if (rankThresh > 0 && "1".equals(isAlarm) && Float.valueOf(hs) >= rankThresh) {//浓度超限
                    Device device = deviceManager.getDeviceByDevCode(devCode);
                    //获取报警等级
                    String alarmContent = H2SAlarmEnum.OVER_THRESH.getName();
                    Integer alarmLevel = 0;
                    for (int j = 0; j < ruleRankList.size(); j++) {
                        Object rankValue = ((Object[]) ruleRankList.get(j))[2];
                        if (null != rankValue) {
                            if (Float.valueOf(hs) >= Float.valueOf(rankValue.toString())) {
                                alarmLevel = Integer.valueOf(((Object[]) ruleRankList.get(j))[0].toString());
                                break;
                            }
                        }
                    }

                    //未注册设备舍弃
                    if (device == null) {
                        return;
                    }
                    AlarmJob alarmJob = alarmJobManager.getByDevAndType(devCode, "1");

                    if (alarmJob == null) {
                        alarmJob=alarmJobManager.saveData(devCode, busWell != null ?
                                busWell.getWellCode() : "", DeviceTypeEnum.HydrogenSulfide.toString(), "1");
                    }
                    //1.写入新的告警
                    alarmRecordManager.saveData(alarmJob.getId(), "1", alarmLevel,
                            alarmContent, hs, device,
                            devCode, busWell != null ? busWell.getWellCode() : "", upTime, alarmContent);
//                    //3.toDo:向app推送报警消息
//                    ThreadUtil.excuteMsg(alarmJob.getId(), alarmContent);
                } else {
                    alarmJobManager.updateAlarmJobByDevCode(devCode, "数据正常，系统自动结束工单");
                }
                //3.清离线
                deviceManager.clearOffline(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 {
                //1.清除离线
                deviceManager.clearOffline(devCode);
                //2.清除同类型的报警信息
                alarmRecordManager.clearAlarm(devCode, "2",
                        String.valueOf(H2SAlarmEnum.valueOf(jsonArray.get(i).toString()).getIndex()));
                //3.写入新的报警
                Device device = deviceManager.getDeviceByDevCode(devCode);
                if (null == device) return;//没注册设备舍弃
                BusWell busWell = busWellManager.getWellByDevCode(devCode);
                //4.若无工单写入新的工单
                AlarmJob alarmJob = alarmJobManager.getByDevAndType(devCode, "0");
                if (null == alarmJob) {
                    alarmJob = alarmJobManager.saveData(devCode, busWell != null ?
                            busWell.getWellCode() : "", DeviceTypeEnum.HydrogenSulfide.toString(), "0");
                }
                alarmRecordManager.saveData(alarmJob.getId(), "2", null,
                        H2SAlarmEnum.valueOf(jsonArray.get(i).toString()).getName(),
                        String.valueOf(H2SAlarmEnum.valueOf(jsonArray.get(i).toString()).getIndex()),
                        device, devCode, null != busWell ? busWell.getWellCode() : "", logTime,
                        H2SAlarmEnum.valueOf(jsonArray.get(i).toString()).getName());

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