package com.mvc.iot.onenet;

import com.alibaba.fastjson.JSONObject;
import com.mvc.iot.IotStoreBlockingQueue;
import com.mvc.iot.IotTaskStatus;
import com.mvc.iot.model.IotTempModel;
import com.mvc.iot.onenet.enums.OneNetMsgType;
import com.mvc.iot.onenet.model.OneNetDataPointsModel;
import com.mvc.iot.onenet.model.OneNetNBcommandCacheReplyModel;
import com.mvc.iot.onenet.model.OneNetRootModel;
import com.mvc.service.taizhang.TaskRemoteCfgService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * OneNet数据处理
 */
@Component
public class OnetDateHandler implements Runnable{
    private static final Logger logger = LoggerFactory.getLogger(OnetDateHandler.class);

    @Resource
    private TaskRemoteCfgService taskRemoteCfgService;

    @Override
    public void run() {
        while (true) {
            try {
                OneNetRootModel tempModel = IotStoreBlockingQueue.oneDateCacheQueue.take();
                handleOneNetData(tempModel);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 处理OneNet数据
     *
     * @param rootModel
     */
    private void handleOneNetData(OneNetRootModel rootModel) {
        try {
            OneNetMsgType oneNetMsgType = OneNetMsgType.getByDescription(rootModel.getMsgType());
            switch (oneNetMsgType) {
                case DATA_POINTS://设备数据上报
                    OneNetDataPointsModel oneNetDataModel = JSONObject.parseObject(rootModel.getSubData().toJSONString(), OneNetDataPointsModel.class);

                    IotTempModel tempModel = new IotTempModel(1,oneNetDataModel.getImei(), oneNetDataModel.getValue().getOriginalData());
                    IotStoreBlockingQueue.iotDataQueue.put(tempModel);
                    break;
                case NB_COMMAND_CACHE_REPLY://NB设备缓存命令下发响应
                    OneNetNBcommandCacheReplyModel nbcacheReplyModel = JSONObject.parseObject(rootModel.getSubData().toJSONString(), OneNetNBcommandCacheReplyModel.class);
                    updateRemoteCfgModel(nbcacheReplyModel);
                    //todo 处理NB设备缓存命令下发响应--去更新远程配置表
                    logger.info("[OneNet]:收到NB设备缓存命令下发响应(NBcommandCacheReply)");
                    break;
                case THING_PROPERTY:
                    logger.info("[OneNet]:收到物模型属性(THING_PROPERTY)");
                    break;
                default:
                    logger.info("[OneNet]:未定义的消息类型:{}", rootModel.getMsgType());
            }


        } catch (Exception e) {
            logger.error("[IOT]队列处理异常:{}", e);
        }
    }

    private void updateRemoteCfgModel(OneNetNBcommandCacheReplyModel replyModel){
        String taskId = replyModel.getCmdId();
        String status = IotTaskStatus.getByOneNetResultCode(replyModel.getSendStatus()).getCode();
        taskRemoteCfgService.updateIotTaskStatus(taskId, status);
    }
}
