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.GasLiquidAlarmEnum;
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.domain.*;
import org.well.well.dto.LiquidDTO;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by test203 on 2017/11/30.
 */
@Service
public class LGLiquidManager extends HibernateEntityDao<LGLiquid> {


    @Resource
    private AlarmRecordManager alarmRecordManager;
    @Resource
    private AlarmRuleManager alarmRuleManager;
    @Resource
    private DeviceManager deviceManager;
    @Resource
    private BusWellManager busWellManager;
    @Resource
    private AlarmJobManager alarmJobManager;

    private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    public Map<String, Object> saveData(LiquidDTO liquidDTO) throws IOException {

        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            LGLiquid liquid = new LGLiquid();
            liquid.setDevId(liquidDTO.getDevCode());
            liquid.setCell(liquidDTO.getCell());
            liquid.setLiquidData(liquidDTO.getLiquidData());
            liquid.setLogtime(new Date());
            liquid.setUptime(DateUtils.sdf4.parse(DateUtils.DateFormat(liquidDTO.getUptime())));
            liquid.setLiquidData(liquidDTO.getLiquidData());
            liquid.setWellCode(liquidDTO.getWellCode());
            save(liquid);
        } 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("liquid")) {
                    continue;
                }
                String level = ((JSONObject) jsonArray.get(i)).get("liquid").toString();
                String upTime = ((JSONObject) jsonArray.get(i)).get("uptime").toString();
                Float wellDeep=busWell!=null?busWell.getDeep():0;
                Float liquidHeight=StringUtils.isNotBlank(level)?Float.valueOf(level)/100:0;
                level = String.format("%.2f",wellDeep+liquidHeight);

                //1.清离线
                deviceManager.clearOffline(devCode);
                //2.清除设备告警
                alarmRecordManager.clearAlarmByNormalData(devCode, "2");
                //3.存数据
                LiquidDTO liquidDTO = new LiquidDTO(level, cell,
                        upTime, devCode, busWell == null ? "" : busWell.getWellCode());
                //存采集数据
                this.saveData(liquidDTO);
                //4.有无超限处理流程（判断最后一条数据）
                if (i < jsonArray.size() - 1) {
                    continue;
                }
                //获取报警阈值
                String thresh = alarmRuleManager.getRuleStr(devCode, DeviceTypeEnum.Liquid.toString());
                List<Object[]> ruleRankList = new ArrayList<Object[]>();
                float rankThresh = 0;
                //是否开启报警(1为开启)
                String isAlarm = "1";
                //是否开启工单(1为开启)
                String isJob = "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) ? Float.valueOf(thresh) : 0) : rankThresh;
                //超限
                if ("1".equals(isAlarm) && rankThresh != 0 && Float.valueOf(level) >= rankThresh) {
                    Device device = deviceManager.getDeviceByDevCode(devCode);
                    AlarmRecord alarmRecord = alarmRecordManager.getThresholdAlarm(devCode);
                    //获取报警等级
                    String alarmContent = GasLiquidAlarmEnum.LIQUID_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(level) >= (new BigDecimal(rankValue.toString()).multiply(new BigDecimal(thresh))).floatValue() / 100) {
                                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.LG.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,
                                level, 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.LG.toString(), "1");
                        }
                        //2.写入新的告警
                        alarmRecordManager.saveData(alarmJob != null ? alarmJob.getId() : null, "1", alarmLevel,
                                alarmContent, level, device,
                                devCode, busWell == null ? "" : busWell.getWellCode(), upTime, alarmContent);
//                        //3.toDo:向app推送报警消息
//                        ThreadUtil.excuteMsg(alarmJob!=null?alarmJob.getId():null, 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() + "失败-------");
            }
        }
    }

}
