package com.mvc.iot.aep;

import com.mvc.iot.IotStoreBlockingQueue;
import com.mvc.iot.IotTaskStatus;
import com.mvc.iot.model.IotTempModel;
import com.mvc.iot.aep.enums.AepMsgType;
import com.mvc.model.aep.AepRootModel;
import com.mvc.service.taizhang.TaskRemoteCfgService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class AepDataHandler implements Runnable{
    private static Logger log = LoggerFactory.getLogger(AepDataHandler.class);

    @Resource
    private TaskRemoteCfgService taskRemoteCfgService;

    @Override
    public void run() {
        while (true) {
            try {
                AepRootModel tempModel = IotStoreBlockingQueue.aepCacheQueue.take();
                handleAepData(tempModel);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void handleAepData(AepRootModel model) throws Exception {
        AepMsgType msgType = AepMsgType.getByDescription(model.getMessageType());
        switch (msgType) {
            case DATAREPORT://数据上报
                IotTempModel tempModel = new IotTempModel(2,model.getIMEI(), model.getPayload().getOriginalData());
                IotStoreBlockingQueue.iotDataQueue.put(tempModel);
                break;
            case COMMANDRESPONSE://命令响应
                if (model.getTaskId() == null || model.getResult() == null || !model.getResult().containsKey("resultCode")) {
                    log.info("[AEP]设备命令响应但无效");
                    return;
                }
                //根据状态去更新远程配置表...
                String taskId = model.getTaskId().toString();//任务ID
                String result = model.getResult().getString("resultCode");//响应结果
                IotTaskStatus status = IotTaskStatus.getByAepResultCode(result);
                taskRemoteCfgService.updateIotTaskStatus(taskId, status.getCode());
                break;
            case EVENTREPORT:
            case DEVICEONLINEOFFLINEREPORT:
            case DATAREPORTTUPUNION:
            case ADDDELETEDEVICE:
            default:
                log.info("[AEP]其它类型消息:");
        }
    }
}
