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.springframework.transaction.annotation.Transactional;
import org.well.well.AlarmEnumDTO.WellAlarmEnum;
import org.well.well.AlarmEnumDTO.WellPlusAlarmEnum;
import org.well.well.core.hibernate.HibernateEntityDao;
import org.well.well.domain.BusWell;
import org.well.well.domain.Device;
import org.well.well.domain.Well;
import org.well.well.domain.WellPlus;

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

@Service
public class WellPlusManager 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 {

            WellPlus wellPlus = new WellPlus(devCode, wellCode, desc, status);
            save(wellPlus);
        } 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();
                //3.存数据
                this.saveData(devCode, busWell == null ? "" : busWell.getWellCode(),
                        WellPlusAlarmEnum.NORMAL.toString(),
                        String.valueOf(WellPlusAlarmEnum.NORMAL.getIndex()));//存采集数据

                if (i < jsonArray.size() - 1) continue;
                //1.清离线
                deviceManager.clearOffline(devCode);
                //2.清除设备告警
                alarmRecordManager.clearAlarmByNormalData(devCode, "2");
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("--------ERROR:设备编号：" + devCode + "，存储数据：" + jsonArray.get(i).toString() + "失败-------");
            }
        }
    }

    @Transactional
    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 {

                //2.存入数据表
                this.saveData(devCode, busWell == null ? "" : busWell.getWellCode(),
                        WellPlusAlarmEnum.valueOf(jsonArray.get(i).toString()).getName(),
                        String.valueOf(WellPlusAlarmEnum.valueOf(jsonArray.get(i).toString()).getIndex()));
                //3.根据不同的报警，进入不同的处理方法(主要分开盖和其他类型的报警)

                //3.1井盖开盖报警处理
                if (WellPlusAlarmEnum.WellPlusOpenAlarm.name().equals(jsonArray.get(i).toString())) {

//                    alarmRecordManager.clearAlarm(devCode, "2", "");//清除设备本身报警
                    if (null != busWell && "1".equals(busWell.getBfzt())) {//布防状态

                        alarmRecordManager.clearAlarm(devCode, "", "");//清除以前报警
                        Device device = deviceManager.getDeviceByDevCode(devCode);
                        if (device == null) return; //没注册舍弃
                        alarmRecordManager.saveData(null, "1", null,
                                WellPlusAlarmEnum.WellPlusOpenAlarm.getName(),
                                String.valueOf(WellPlusAlarmEnum.WellPlusOpenAlarm.getIndex()), device,
                                devCode, busWell != null ? busWell.getWellCode() : null, logTime,
                                WellPlusAlarmEnum.WellPlusOpenAlarm.getName());
                    }
                }
                //3.2低电量和设备故障报警处理
                else if (WellPlusAlarmEnum.WellPlusLevelAlarm.name().equals(jsonArray.get(i).toString()) ||
                        WellPlusAlarmEnum.WellPlusUnknown.name().equals(jsonArray.get(i).toString())) {

                    //写入新的报警
                    Device device = deviceManager.getDeviceByDevCode(devCode);
                    if (null == device) return;
                    alarmRecordManager.saveData(null, "1", null,
                            WellPlusAlarmEnum.valueOf(jsonArray.get(i).toString()).getName(),
                            String.valueOf(WellPlusAlarmEnum.valueOf(jsonArray.get(i).toString()).getIndex()),
                            device, devCode, null != busWell ? busWell.getWellCode() : "", logTime,
                            WellPlusAlarmEnum.valueOf(jsonArray.get(i).toString()).getName());
                }
                if (i < jsonArray.size() - 1) continue;
                //1.清离线
                deviceManager.clearOffline(devCode);

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