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.NoiseDigAlarmEnum;
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 javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class NoiseDigManager extends HibernateEntityDao<NoiseDig> {
    @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  final  double constant=0.0153;

    public Map<String, Object> saveData(String devId, String wellCode, String cell, String uptime,
                                        String frequency, String dData) throws IOException {

        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            NoiseDig noise = new NoiseDig(devId, wellCode, cell,
                    DateUtils.sdf4.parse(DateUtils.DateFormat(uptime)),
                    frequency, dData);
            save(noise);
        } 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 {
                String val = ((JSONObject) jsonArray.get(i)).get("noiseVal").toString();
                String freq = ((JSONObject) jsonArray.get(i)).get("noiseFreq").toString();
                String upTime = ((JSONObject) jsonArray.get(i)).get("uptime").toString();
                val = String.format("%.2f", Double.valueOf(val));
                freq = String.format("%.2f", Double.valueOf(freq));
                //1.清离线
                deviceManager.clearOffline(devCode);
                //2.清除设备告警
                alarmRecordManager.clearAlarmByNormalData(devCode, "2");
                //3.存数据
                saveData(devCode, busWell == null ? "" : busWell.getWellCode(), cell, upTime, freq, val);              //4.有无超限处理流程（判断最后一条数据）                saveData(devCode, busWell == null ? "" : busWell.getWellCode(), gas, cell, upTime);//存储采集数据
                if (i < jsonArray.size() - 1) continue;
                String thresh = alarmRuleManager.getRuleStr(devCode, DeviceTypeEnum.NoiseDig.toString());//获取报警阈值
                List<Object[]> ruleRankList = new ArrayList<Object[]>();
                double rankThresh = 0;
                String isAlarm = "1";//是否开启报警(1为开启)
                String isJob = "1";//是否开启工单(1为开启)
                if (busWell != null) ruleRankList = alarmRuleManager.getRuleRank(devCode, busWell.getDeptid());
                if (ruleRankList.size() > 0 && StringUtils.isNotBlank(thresh)) {
                    Object rankValue = ((Object[]) ruleRankList.get(ruleRankList.size() - 1))[2];
                    rankThresh = (Float.valueOf(rankValue.toString())) / 100 * Float.valueOf(thresh);
                    isAlarm = ((Object[]) ruleRankList.get(ruleRankList.size() - 1))[4].toString();
                    isJob = ((Object[]) ruleRankList.get(ruleRankList.size() - 1))[5].toString();
                }
                rankThresh = rankThresh == 0 ? (StringUtils.isNotBlank(thresh) ? Double.valueOf(thresh) : 0) : rankThresh;
                if ("1".equals(isAlarm) && rankThresh != 0 && Double.valueOf(val) >= rankThresh) {//超限
                    AlarmRecord alarmRecord = alarmRecordManager.getThresholdAlarm(devCode);
                    Device device = deviceManager.getDeviceByDevCode(devCode);
                    //获取报警等级
                    String alarmContent = NoiseDigAlarmEnum.OVER_THRESH.getName();
                    Integer alarmLevel = 0;
                    if (busWell != null) {
//                        List<Object[]> ruleRankList=  alarmRuleManager.getRuleRank(devCode,busWell.getDeptid());
                        for (int j = 0; j < ruleRankList.size(); j++) {
                            Object rankValue = ((Object[]) ruleRankList.get(j))[2];
                            if (null != rankValue) {

                                if (Float.valueOf(val) >= (new BigDecimal(rankValue.toString()).multiply(new BigDecimal(thresh)).floatValue()) / 100) {
//                                    NoiseDigAlarmEnum noiseDigAlarmEnum=NoiseDigAlarmEnum.getByIndex(
//                                            String.valueOf(Long.valueOf(((Object[]) ruleRankList.get(j))[0].toString()) + 4));
//                                    alarmContent = noiseDigAlarmEnum!=null?noiseDigAlarmEnum.getName():alarmContent;
                                    alarmLevel = Integer.valueOf(((Object[]) ruleRankList.get(j))[0].toString());

                                    break;
                                }
                            }
                        }
                    }

                    if (null != alarmRecord) {//已存在报警
                        //1.清除上一条告警记录
                        alarmRecordManager.clearAlarm(devCode, "1", "");
                        //2.写入新的告警记录,更新工单号为上一条告警记录的工单号,若以前没开启工单，现在补提工单
                        Long jobID = alarmRecord.getJobId();
                        if ("1".equals(isJob) && null == jobID && null != device &&
                                "1".equals(device.getJobGenerationType())) {
                            //生成新的工单
                            AlarmJob alarmJob = alarmJobManager.saveData(devCode, alarmRecord.getWellCode(),
                                    DeviceTypeEnum.NoiseDig.toString(), "1");
                            jobID = alarmJob.getId();
                            ThreadUtil.excuteMsg(jobID, "", busWell == null ? "" : busWell.getWellCode());
                        } else if ("0".equals(isJob)) {//不需要产生工单时
                            jobID = null;
                        }
                        alarmRecordManager.saveData(jobID, "1", alarmLevel, alarmContent,
                                val, alarmRecord.getDevice(), devCode, alarmRecord.getWellCode(), upTime, alarmContent);
                    } else {//不存在上一条报警时

                        if (device == null) return;//未注册设备舍弃
                        AlarmJob alarmJob = null;
                        if ("1".equals(isJob) && "1".equals(device.getJobGenerationType())) {
                            //1.生成新的工单
                            alarmJob = alarmJobManager.saveData(devCode, busWell != null ?
                                    busWell.getWellCode() : "", DeviceTypeEnum.NoiseDig.toString(), "1");
                        }

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

                        ThreadUtil.excuteMsg(alarmJob == null ? null : 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(NoiseDigAlarmEnum.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 && "1".equals(device.getJobGenerationType())) {
                    alarmJob = alarmJobManager.saveData(devCode, busWell != null ?
                            busWell.getWellCode() : "", DeviceTypeEnum.NoiseDig.toString(), "0");
                }
                alarmRecordManager.saveData(alarmJob.getId(), "2", null,
                        NoiseDigAlarmEnum.valueOf(jsonArray.get(i).toString()).getName(),
                        String.valueOf(NoiseDigAlarmEnum.valueOf(jsonArray.get(i).toString()).getIndex()),
                        device, devCode, null != busWell ? busWell.getWellCode() : "", logTime,
                        NoiseDigAlarmEnum.valueOf(jsonArray.get(i).toString()).getName());

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