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.CommercialGasManager;
import org.well.well.manager.DeviceConfigManager;
import org.well.well.manager.ImeiManager;
import org.well.well.manager.PressureManager;

/**
 * 商务燃气接受处理响应
 */
public class CommercialGasResponse 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();
        CommercialGasManager gasManager = ac.getBean(CommercialGasManager.class);
        DeviceConfigManager deviceConfigManager = ac.getBean(DeviceConfigManager.class);
        ImeiManager imeiManager = ac.getBean(ImeiManager.class);
        JSONObject json = JSONObject.fromObject(this.getContent());
        String devCode = json.getString("devCode");
        JSONObject jsonObject = json.getJSONObject("mBody");
        if (mType[0].equals(json.get("mType")) || mType[3].equals(json.get("mType"))) {//存储上报数据
            gasManager.processNormalData(jsonObject, devCode);
        } else if (mType[1].equals(json.get("mType"))) {//存储报警事件
            gasManager.processAlarmData(jsonObject, devCode);
        } else if (mType[2].equals(json.get("mType"))) {//更新下发参数状态
            try {
                //下发配置回填数据
                if (DeviceTypeEnum.Pressure.name().equals(json.get("devType"))) {
                    if ("GasConfigSuccess".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 + "，更新参数下发状态失败-------");
            }
        }
    }
}
