package org.well.well.resp;

import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.well.well.base.AbstractResponse;
import org.well.well.base.DeviceTypeEnum;
import org.well.well.manager.DeviceConfigManager;
import org.well.well.manager.ImeiManager;
import org.well.well.manager.NoiseDigManager;

/**
 * Created by lenovo on 2018/1/9.
 */
public class NoiseDigResponse extends AbstractResponse {

    private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    private static final String[] mType = {"Data", "Event", "SetResponse", "GetResponse", "StartupRequest"};
    @Override
    public void run() {
        ClassPathXmlApplicationContext ac = this.getAc();
        NoiseDigManager noiseDigManager = ac.getBean(NoiseDigManager.class);
        DeviceConfigManager deviceConfigManager = ac.getBean(DeviceConfigManager.class);
        ImeiManager imeiManager = ac.getBean(ImeiManager.class);
        JSONObject json = JSONObject.fromObject(this.getContent());
        String devCode = json.get("devCode").toString();
        logger.info("--------RECEIVE:设备编号：" + devCode + "，上传数据：" + json.toString() + "-------");
        JSONObject jsonObject = (JSONObject) json.get("mBody");
        if (mType[0].equals(json.get("mType")) || mType[3].equals(json.get("mType"))) {//存储上报数据
            noiseDigManager.processNormalData(jsonObject,devCode);
        } else if (mType[1].equals(json.get("mType"))) {//存储报警事件
            noiseDigManager.processAlarmData(jsonObject,devCode);
        } else if (mType[2].equals(json.get("mType"))) {//更新下发参数状态
            try {
                if (DeviceTypeEnum.NoiseDig.name().equals(json.get("devType"))) {
                    if ("NoiseDigConfigSuccess".equals(jsonObject.get("bType"))) {
                        deviceConfigManager.updateStatus(devCode);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("--------ERROR:设备编号：" + devCode + "，更新参数下发状态失败-------");
            }
        }else if (mType[4].equals(json.get("mType"))) {//三码存储
            try {
                String imei = jsonObject.get("imei").toString();
                String iccid = jsonObject.get("iccid").toString();
                imeiManager.saveData(devCode,imei,iccid);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("--------ERROR:设备编号：" + devCode + "，更新参数下发状态失败-------");
            }
        }

    }
}
