package org.well.well.manager;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
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.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
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.存数据
                saveData(devCode, busWell == null ? "" : busWell.getWellCode(), gas, cell, upTime);
                //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) {
                    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(gas) >= rankThresh) {//浓度超限
                    Device device = deviceManager.getDeviceByDevCode(devCode);
//                    AlarmRecord alarmRecord = alarmRecordManager.getThresholdAlarm(devCode);
                    //获取报警等级
                    String alarmContent = GasLiquidAlarmEnum.GAS_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(gas) >= Float.valueOf(rankValue.toString())) {
                                alarmLevel = Integer.valueOf(((Object[]) ruleRankList.get(j))[0].toString());
                                break;
                            }
                        }
                    }

                    //未注册设备舍弃
                    if (device == null) {
                        return;
                    }

                    //1.写入新的告警
                    alarmRecordManager.saveData(null, "1", alarmLevel,
                            alarmContent, gas, device,
                            devCode, busWell != null ? busWell.getWellCode() : "", upTime, alarmContent);
                    //3.toDo:向app推送报警消息
                    ThreadUtil.excuteMsg(null, alarmContent, busWell == null ? "" : busWell.getWellCode());

                }
                //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 {

                //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.若无工单写入新的工单

                alarmRecordManager.saveData(null, "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() + "失败-------");
            }
        }
    }

}
