package com.mvc.iot;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ctg.ag.sdk.biz.aep_device_command.CancelCommandResponse;
import com.ctg.ag.sdk.biz.aep_device_command.CreateCommandResponse;
import com.mvc.iot.aep.AepApiHelper;
import com.mvc.iot.aep.config.AepConfig;
import com.mvc.iot.aep.model.AepCommandBodyModel;
import com.mvc.iot.aep.model.AepResponseRootModel;
import com.mvc.iot.onenet.OneNetApiHelper;
import com.mvc.iot.onenet.model.OneNetApiResponseModel;
import com.mvc.model.DeviceAccModel;
import com.mvc.model.TaskRemoteCfgModel;
import com.mvc.service.taizhang.DeviceAccService;
import com.mvc.service.taizhang.TaskRemoteCfgService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * IOT 平台API处理
 */
@Component
public class IotApiHelper {
    private static final Logger logger = LoggerFactory.getLogger(IotApiHelper.class);

    @Resource
    private OneNetApiHelper oneNetApiHelper;

    @Resource
    private AepApiHelper aepApiHelper;

    @Resource
    private DeviceAccService deviceAccService;

    @Resource
    private TaskRemoteCfgService taskRemoteCfgService;

    @Resource
    private AepConfig aepConfig;

    /**
     * 发送远程配置任务
     *
     * @param cfgModel
     * @throws Exception
     */
    public void sendRemoteCfgTask(TaskRemoteCfgModel cfgModel) throws Exception {
        String message = taskRemoteCfgService.getHexaskRemoteCfg(cfgModel);//报文内容
        if (cfgModel.getIotType().equals("1")) {//移动OneNet
            OneNetApiResponseModel oneNetRes = oneNetApiHelper.sendCommand(cfgModel.getDeviceAccModel().getImei(), message);
            if (oneNetRes != null && oneNetRes.getCode() == 0 && oneNetRes.getData() != null && oneNetRes.getData().containsKey("uuid")) {
                String uuid = oneNetRes.getData().getString("uuid");
                cfgModel.setIotTaskId(uuid);
            } else {
                logger.info("[OneNet]:send command failed:{}", oneNetRes.getMsg());
            }
        } else {//AEP
            AepCommandBodyModel bodyModel = new AepCommandBodyModel(cfgModel.getDeviceAccModel().getIotDeviceId(), cfgModel.getCreateMan(), Integer.valueOf(aepConfig.getProductId()), message);
            CreateCommandResponse response = aepApiHelper.createCommand(bodyModel);
            if (response != null && response.getStatusCode() == 200) {
                String json = new String(response.getBody(), "utf-8");
                //AepResponseRootModel<JSONObject> {"code":1314,"msg":"指令下发，设备状态不合法","result":null} 此格式解析会报 not match : - 
                AepResponseRootModel<String> aepResModel = JSON.parseObject(json, new TypeReference<>() {
                });
                if (aepResModel.getCode() == 0) {
                    JSONObject dataObject = JSON.parseObject(aepResModel.getResult());
                    if (dataObject.containsKey("commandId")) {
                        cfgModel.setIotTaskId(dataObject.getString("commandId"));
                    }
                }
                /*if (aepResModel.getCode() == 0 && aepResModel.getResult().containsKey("commandId")) {
                    cfgModel.setIotTaskId(aepResModel.getResult().get("commandId").toString());
                }*/
            } else {
                logger.info("[AEP]:send command failed:{}", response.getMessage());
            }
        }
        if (!StringUtils.isNotEmpty(cfgModel.getIotTaskId())) {//IOT平台创建失败
            cfgModel.setIotTaskStatus(IotTaskStatus.CREATE_FAIL.getCode());
        }
        taskRemoteCfgService.updateTaskRemoteCfg(cfgModel);
    }

    /**
     * 取消远程配置任务
     *
     * @param cfgModel
     * @throws Exception
     */
    public void cancelRemoteCfgTask(TaskRemoteCfgModel cfgModel) throws Exception {
        boolean success = false;
        if (cfgModel.getIotType().equals("1")) {//移动OneNet
            DeviceAccModel deviceAccModel = deviceAccService.findDeviceAccBysn(cfgModel.getDeviceSn());
            if (deviceAccModel == null) {//台账被删除或不匹配了
                logger.info("[OneNet]:cancel command, device acc not found,deviceSn:{}", cfgModel.getDeviceSn());
                return;
            }
            OneNetApiResponseModel oneNetRes = oneNetApiHelper.cancelCommand(cfgModel.getIotTaskId(), deviceAccModel.getImei());
            if (oneNetRes != null && oneNetRes.getCode() == 0) {
                cfgModel.setIotTaskStatus(String.valueOf(IotTaskStatus.CANCELED.getCode()));
                success = true;
            } else {
                logger.info("[OneNet]:cancel command failed:{}", oneNetRes.getMsg());
            }
        } else {//AEP
            CancelCommandResponse response = aepApiHelper.cancleCommand(cfgModel.getIotTaskId(), cfgModel.getIotDeviceId());
            if (response != null && response.getStatusCode() == 200) {
                String json = new String(response.getBody(), "utf-8");
                AepResponseRootModel<String> aepResModel = JSON.parseObject(json, new TypeReference<>() {
                });
                if (aepResModel.getCode() == 0) {
                    cfgModel.setIotTaskStatus(String.valueOf(IotTaskStatus.CANCELED.getCode()));
                    success = true;
                } else {
                    logger.info("[AEP]:cancel command failed:{}", aepResModel.getMsg());
                }
            } else {
                logger.info("[AEP]:cancel command failed:{}", response.getMessage());
            }
        }
        if (success) {
            taskRemoteCfgService.updateTaskRemoteCfg(cfgModel);
        }
    }
}
