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.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.core.util.ThreadUtil;
import org.well.well.domain.AlarmRecord;
import org.well.well.domain.BusWell;
import org.well.well.domain.Device;
import org.well.well.domain.LGLiquid;
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.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 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;


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

    private final String devcodePrex = "3220";//需要对此类设备监测值加安装高度

    private List<Object[]> installHeighsList;

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

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

    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();
                if (StringUtils.isBlank(level)) continue;

                Float levelFloat = new BigDecimal(level).floatValue() / 100;
                //3220开头的设备需要加安装高度
                if (devCode.indexOf(devcodePrex) == 0 && levelFloat != 0) {
                    if (null == installHeighsList) {
                        installHeighsList = deviceManager.getInstallHeightDevices();
                    }
                    for(Object[] objects: installHeighsList){
                        if(objects[0]!=null&&devCode.equals(objects[0].toString())){
                            levelFloat+=  Float.valueOf(objects[1].toString());
                            break;
                        }
                    }
                    level=levelFloat+"";
                }
                //1.存数据
                LiquidDTO liquidDTO = new LiquidDTO(String.format("%.2f", Double.valueOf(levelFloat)), 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 (levelFloat >= Float.valueOf(thresh)) {
                    Device device = deviceManager.getDeviceByDevCode(devCode);
                    //获取报警内容
                    String alarmContent = GasLiquidAlarmEnum.LIQUID_OVER_THRESH.getName();

                    //未注册设备舍弃
                    if (device == null) {
                        return;
                    }

                    //2.写入新的告警
                    alarmRecordManager.saveData(null, "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.清除之前的报警
                    alarmRecordManager.clearAlarmByNormalData(devCode, "1");
                }
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("--------ERROR:设备编号：" + devCode + "，存储数据：" + jsonArray.get(i).toString() + "失败-------");
            }
        }
    }

}
