package org.well.well.manager;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.well.well.AlarmEnumDTO.LiquidAlarmEnum;
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 org.well.well.dto.LiquidDTO;
import org.well.well.util.SnowFlakeUtil;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.*;

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


    @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(LiquidDTO liquidDTO) throws IOException {

        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Long id = SnowFlakeUtil.getId();
            Liquid liquid = new Liquid();
            liquid.setDbId(id);
            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;
    }

    @Transactional
    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 level = ((JSONObject) jsonArray.get(i)).get("level").toString();
                level = String.format("%.2f", Double.valueOf(level));
                String upTime = ((JSONObject) jsonArray.get(i)).get("uptime").toString();
                //1.存数据
                LiquidDTO liquidDTO = new LiquidDTO(level, cell,
                        upTime, devCode, busWell == null ? "" : busWell.getWellCode());
                this.saveData(liquidDTO);//存采集数据
                //2.有无超限处理流程（判断最后一条数据）
                if (i < jsonArray.size() - 1) continue;
                //3.清离线
                deviceManager.clearOffline(devCode);
                //4.清除设备告警
                alarmRecordManager.clearAlarmByNormalData(devCode, "");
                String thresh = alarmRuleManager.getRuleStr(devCode, DeviceTypeEnum.Liquid.toString());//获取报警阈值

                if (Float.valueOf(level) >= Float.valueOf(thresh)) {//超限

                    Device device = deviceManager.getDeviceByDevCode(devCode);
                    //获取报警等级
                    String alarmContent = LiquidAlarmEnum.OVER_THRESH.getName();

                    //不存在上一条报警时
                    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.Liquid.toString(), "1");
                    }
                    //2.写入新的告警
                    alarmRecordManager.saveData(jobId, "1", null,
                            alarmContent, level, device,
                            devCode, busWell == null ? "" : busWell.getWellCode(), upTime, alarmContent);
//                        //3.toDo:向app推送报警消息

                    ThreadUtil.excuteMsg(null, alarmContent, busWell == null ? "" : busWell.getWellCode());

                } else {//未超限

                    //1.结束之前的工单
                    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(LiquidAlarmEnum.valueOf(jsonArray.get(i).toString()).getIndex()));
                //3.写入新的报警
                Device device = deviceManager.getDeviceByDevCode(devCode);
                if (null == device) return;//没注册设备舍弃
                BusWell busWell = busWellManager.getWellByDevCode(devCode);
                alarmRecordManager.saveData(null, "2", null,
                        LiquidAlarmEnum.valueOf(jsonArray.get(i).toString()).getName(),
                        String.valueOf(LiquidAlarmEnum.valueOf(jsonArray.get(i).toString()).getIndex()),
                        device, devCode, null != busWell ? busWell.getWellCode() : "", logTime,
                        LiquidAlarmEnum.valueOf(jsonArray.get(i).toString()).getName());

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

    public boolean isExist(String devcode, String upTime) {

        Criteria criteria = getSession().createCriteria(Liquid.class);
        criteria.add(Restrictions.eq("devId", devcode));
        try {
            criteria.add(Restrictions.eq("uptime", DateUtils.sdf4.parse(DateUtils.DateFormat(upTime))));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        List<Liquid> methaneList = criteria.list();
        return methaneList.size() > 0 ? true : false;
    }
}
