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.WellAlarmEnum;
import org.well.well.base.DeviceTypeEnum;
import org.well.well.core.hibernate.HibernateEntityDao;
import org.well.well.core.util.ThreadUtil;
import org.well.well.domain.*;

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

@Service
public class WellManager extends HibernateEntityDao<Well> {
    @Resource
    private AlarmRecordManager alarmRecordManager;
    @Resource
    private BusWellManager busWellManager;
    @Resource
    private AlarmJobManager alarmJobManager;
    @Resource
    private DeviceManager deviceManager;
    @Resource
    private UserManager userManager;
    private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    public Map<String, Object> saveData(String devCode, String wellCode,
                                        String desc, String status) {

        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {

            Well well = new Well(devCode, wellCode, desc, status);
            save(well);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    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 level = ((JSONObject) jsonArray.get(i)).get("value").toString();//"00"
                String upTime = ((JSONObject) jsonArray.get(i)).get("uptime").toString();
                //1.清离线
                deviceManager.clearOffline(devCode);
                //2.清除设备告警
                alarmRecordManager.clearAlarmByNormalData(devCode, "2");
                //3.存数据
                this.saveData(devCode, busWell == null ? "" : busWell.getWellCode(),
                        WellAlarmEnum.NORMAL.toString(),
                        String.valueOf(WellAlarmEnum.NORMAL.getIndex()));//存采集数据
            } catch (Exception 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();
        BusWell busWell = busWellManager.getWellByDevCode(devCode);
        for (int i = 0; i < jsonArray.size(); i++) {
            try {
                //1.清离线
                deviceManager.clearOffline(devCode);
                //2.存入数据表
                this.saveData(devCode, busWell == null ? "" : busWell.getWellCode(),
                        WellAlarmEnum.valueOf(jsonArray.get(i).toString()).getName(),
                        String.valueOf(WellAlarmEnum.valueOf(jsonArray.get(i).toString()).getIndex()));
                //3.根据不同的报警，进入不同的处理方法(主要分开盖和其他类型的报警)

                //3.1井盖开盖报警处理
                if (WellAlarmEnum.WellOpenAlarm.name().equals(jsonArray.get(i).toString())) {
                    alarmRecordManager.clearAlarm(devCode, "2", "");//清除设备本身报警
                    if (null != busWell && "1".equals(busWell.getBfzt())) {//布防状态
                        AlarmRecord alarmRecord = alarmRecordManager.getThresholdAlarm(devCode);
                        if (alarmRecord != null) {
                            //清除报警信息
                            alarmRecordManager.clearAlarm(devCode, "1",
                                    String.valueOf(WellAlarmEnum.WellOpenAlarm.getIndex()));
                            //写入新的报警
                            alarmRecordManager.saveData(alarmRecord.getJobId(), "1", null,
                                    WellAlarmEnum.WellOpenAlarm.getName(),
                                    String.valueOf(WellAlarmEnum.WellOpenAlarm.getIndex()),
                                    alarmRecord.getDevice(), devCode, alarmRecord.getWellCode(), logTime,
                                    WellAlarmEnum.WellOpenAlarm.getName());
                        } else {
                            Device device = deviceManager.getDeviceByDevCode(devCode);
                            if (device == null) return; //没注册舍弃
                            //生成新的工单
                            if ("1".equals(device.getJobGenerationType())) {
                                AlarmJob alarmJob = alarmJobManager.saveData(devCode, busWell.getWellCode(),
                                        DeviceTypeEnum.Well.toString(), "1");

                                alarmRecordManager.saveData(alarmJob.getId(), "1", null,
                                        WellAlarmEnum.WellOpenAlarm.getName(),
                                        String.valueOf(WellAlarmEnum.WellOpenAlarm.getIndex()), device,
                                        devCode, alarmJob.getWellCode(), logTime,
                                        WellAlarmEnum.WellOpenAlarm.getName());
                                //toDo:向app推送报警消息

//                            ThreadUtil.excuteMsg(alarmJob.getId(),WellAlarmEnum.WellOpenAlarm.getName(),
//                                    busWell == null ? "" : busWell.getWellCode());
                            }
                        }
                    }
                }
                //3.2低电量和设备故障报警处理
                else if (WellAlarmEnum.WellLowBatteryAlarm.name().equals(jsonArray.get(i).toString()) ||
                        WellAlarmEnum.WellDeviceBadAlarm.name().equals(jsonArray.get(i).toString())) {
                    //清除报警信息
                    alarmRecordManager.clearAlarm(devCode, "2",
                            String.valueOf(WellAlarmEnum.valueOf(jsonArray.get(i).toString()).getIndex()));
                    //写入新的报警
                    Device device = deviceManager.getDeviceByDevCode(devCode);
                    if (null == device) return;
                    AlarmJob alarmJob = alarmJobManager.getByDevAndType(devCode, "0");
                    if (null == alarmJob && "1".equals(device.getJobGenerationType())) {
                        alarmJob = alarmJobManager.saveData(devCode, busWell.getWellCode(),
                                DeviceTypeEnum.Well.toString(), "0");
                    }
                    alarmRecordManager.saveData(alarmJob.getId(), "2", null,
                            WellAlarmEnum.valueOf(jsonArray.get(i).toString()).getName(),
                            String.valueOf(WellAlarmEnum.valueOf(jsonArray.get(i).toString()).getIndex()),
                            device, devCode, null != busWell ? busWell.getWellCode() : "", logTime,
                            WellAlarmEnum.valueOf(jsonArray.get(i).toString()).getName());
                }

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