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.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.StringUtils;
import org.well.well.core.util.ThreadUtil;
import org.well.well.domain.AlarmJob;
import org.well.well.domain.BusWell;
import org.well.well.domain.Device;
import org.well.well.domain.Methane;
import org.well.well.util.SnowFlakeUtil;

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

@Service
public class MethaneManager extends HibernateEntityDao<Methane> {


    @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 {
            String timeFormat = DateUtils.DateFormat(uptime);
            Methane methane = new Methane(address, wellCode, strength, cell,
                    new Timestamp(StringUtils.isNotBlank(timeFormat) ? DateUtils.sdf4.parse(timeFormat).getTime() : null),
                    new Timestamp((new Date()).getTime()));
            save(methane);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("----uptime时间转换失败-----："+uptime);
        }
        return resultMap;
    }


    @Transactional
    public void processNormalData(JSONObject jsonObject, String devCode) {
        String cell = jsonObject.getString("cell");
        JSONArray jsonArray = jsonObject.getJSONArray("datas");
        BusWell busWell = busWellManager.getWellByDevCode(devCode);
        for (int i = 0; i < jsonArray.size(); i++) {
            try {
                String gas = ((JSONObject) jsonArray.get(i)).getString("gas");
                String upTime = ((JSONObject) jsonArray.get(i)).getString("uptime");
                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&&ruleRankList.get(0)[0]!=null) {
                    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);
                    //获取报警等级
                    String alarmContent = MethaneAlarmEnum.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;//未注册设备舍弃
                    AlarmJob alarmJob = alarmJobManager.getByDevAndType(devCode, "1");
                    Long jobId=alarmJob==null? SnowFlakeUtil.getId():alarmJob.getId();
                    if(alarmJob==null){
                        alarmJobManager.saveData(jobId,devCode, busWell != null ?
                                busWell.getWellCode() : "", DeviceTypeEnum.Methane.toString(), "1");
                    }
                    //1.写入新的告警
                    alarmRecordManager.saveData(jobId, "1", alarmLevel,
                            alarmContent, gas, device,
                            devCode, busWell != null ? busWell.getWellCode() : "", upTime, alarmContent);
                    //2.toDo:向app推送报警消息
                    ThreadUtil.excuteMsg(null, alarmContent, busWell == null ? "" : busWell.getWellCode());

                }else {
                    alarmJobManager.updateAlarmJobByDevCode(devCode, "数据正常，系统自动结束工单");
                }
                //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 = jsonObject.getJSONArray("eventType");
        String logTime = jsonObject.getString("logTime");
        for (int i = 0; i < jsonArray.size(); i++) {
            try {
                //1.清除同类型的报警信息
                alarmRecordManager.clearAlarm(devCode, "2",
                        String.valueOf(MethaneAlarmEnum.valueOf(jsonArray.get(i).toString()).getIndex()));
                //2.写入新的报警
                Device device = deviceManager.getDeviceByDevCode(devCode);
                if (null == device) return;//没注册设备舍弃
                BusWell busWell = busWellManager.getWellByDevCode(devCode);
                alarmRecordManager.saveData(null, "2", null,
                        MethaneAlarmEnum.valueOf(jsonArray.get(i).toString()).getName(),
                        String.valueOf(MethaneAlarmEnum.valueOf(jsonArray.get(i).toString()).getIndex()),
                        device, devCode, null != busWell ? busWell.getWellCode() : "", logTime,
                        MethaneAlarmEnum.valueOf(jsonArray.get(i).toString()).getName());

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

}
