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.GasLiquidAlarmEnum;
import org.well.well.AlarmEnumDTO.MethaneAlarmEnum;
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.ThreadUtil;
import org.well.well.domain.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class LGGasManager extends HibernateEntityDao<LGGas> {


    @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());

    public Map<String, Object> saveData(String address, String wellCode,
                                        String strength, String cell, String uptime) {

        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            LGGas methane = new LGGas(address, wellCode, strength, cell,
                    new Timestamp((DateUtils.sdf4.parse(DateUtils.DateFormat(uptime)).getTime())),
                    new Timestamp((new Date()).getTime()));
            save(methane);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }


    public void processNormalData(JSONObject jsonObject, String devCode) {
        String cell = jsonObject.get("cell").toString();
        JSONArray jsonArray = (JSONArray) jsonObject.get("datas");
        BusWell busWell = busWellManager.getWellByDevCode(devCode);
        for (int i = 0; i < jsonArray.size(); i++) {
            try {
                if (null == ((JSONObject) jsonArray.get(i)).get("gas")) {
                    continue;
                }
                String gas = ((JSONObject) jsonArray.get(i)).get("gas").toString();
                String upTime = ((JSONObject) jsonArray.get(i)).get("uptime").toString();
                gas = String.format("%.2f", Double.valueOf(gas));
                //1.清离线
                deviceManager.clearOffline(devCode);
                //2.清除设备告警
                alarmRecordManager.clearAlarmByNormalData(devCode, "2");
                //3.存数据
                saveData(devCode, busWell == null ? "" : busWell.getWellCode(), gas, cell, upTime);
                //4.有无超限处理流程（判断最后一条数据）
                if (i < jsonArray.size() - 1) {
                    continue;
                }
                //获取报警阈值
                String thresh = alarmRuleManager.getRuleStr(devCode, DeviceTypeEnum.Methane.toString());
                if (Float.valueOf(gas) >= Float.valueOf(thresh.split(",")[1])) {//浓度超限
                    AlarmRecord alarmRecord = alarmRecordManager.getThresholdAlarm(devCode);
                    Device device = deviceManager.getDeviceByDevCode(devCode);
                    //获取报警等级
                    String alarmContent = GasLiquidAlarmEnum.GAS_OVER_THRESH.getName();
                    Integer alarmLevel = 0;
                    alarmLevel = Float.valueOf(gas) >= Float.valueOf(thresh.split(",")[0]) ?
                            1 : (Float.valueOf(gas) >= Float.valueOf(thresh.split(",")[1]) ?
                            2 : alarmLevel);
                    //已存在报警
                    if (null != alarmRecord) {
                        //1.清除上一条告警记录
                        alarmRecordManager.clearAlarm(devCode, "1", "");
                        //2.写入新的告警记录,工单号为上一条告警记录的工单号
                        Long jobId = (device != null && "1".equals(device.getJobGenerationType())) ? alarmRecord.getJobId() : null;
                        alarmRecordManager.saveData(jobId, "1", alarmLevel, alarmContent,
                                gas, alarmRecord.getDevice(), devCode, alarmRecord.getWellCode(), upTime, alarmContent);
                    } else {//不存在上一条报警时
                        //未注册设备舍弃
                        if (device == null) {
                            return;
                        }
                        //判断是否生成工单
                        AlarmJob alarmJob = new AlarmJob();
                        if ("1".equals(device.getJobGenerationType())) {
                            //1.生成新的工单
                            alarmJob = alarmJobManager.saveData(devCode, busWell != null ?
                                    busWell.getWellCode() : "", DeviceTypeEnum.LG.toString(), "1");
                        }

                        //2.写入新的告警
                        alarmRecordManager.saveData(alarmJob.getId(), "1", alarmLevel,
                                alarmContent, gas, device,
                                devCode, busWell != null ? busWell.getWellCode() : "", upTime, alarmContent);
                        //3.toDo:向app推送报警消息
                        ThreadUtil.excuteMsg(alarmJob.getId(), alarmContent, 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() + "失败-------");
            }
        }
    }


    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(GasLiquidAlarmEnum.valueOf(jsonArray.get(i).toString()).getIndex()));
                //3.写入新的报警
                Device device = deviceManager.getDeviceByDevCode(devCode);
                //没注册设备舍弃
                if (null == device) {
                    return;
                }
                BusWell busWell = busWellManager.getWellByDevCode(devCode);
                //4.若无工单写入新的工单
                AlarmJob alarmJob = new AlarmJob();
                if ("1".equals(device.getJobGenerationType())) {
                    alarmJob = alarmJobManager.getByDevAndType(devCode, "0");
                    if (null == alarmJob) {
                        alarmJob = alarmJobManager.saveData(devCode, busWell != null ?
                                busWell.getWellCode() : "", DeviceTypeEnum.LG.toString(), "0");
                    }
                }
                alarmRecordManager.saveData(alarmJob.getId(), "2", null,
                        GasLiquidAlarmEnum.valueOf(jsonArray.get(i).toString()).getName(),
                        String.valueOf(GasLiquidAlarmEnum.valueOf(jsonArray.get(i).toString()).getIndex()),
                        device, devCode, null != busWell ? busWell.getWellCode() : "", logTime,
                        GasLiquidAlarmEnum.valueOf(jsonArray.get(i).toString()).getName());

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