package com.mortals.xhx.busiz.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.service.ICacheService;
import com.mortals.xhx.busiz.req.DeviceReq;
import com.mortals.xhx.busiz.rsp.ApiResp;
import com.mortals.xhx.busiz.rsp.DeviceResp;
import com.mortals.xhx.common.code.ApiRespCodeEnum;
import com.mortals.xhx.common.code.DeviceActionEnum;
import com.mortals.xhx.common.utils.SendTaskThreadPool;
import com.mortals.xhx.common.utils.UploadTask;
import com.mortals.xhx.module.device.service.DeviceLogService;
import com.mortals.xhx.module.device.service.DeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static com.mortals.xhx.common.key.RedisKey.KEY_DEVICE_TYPE_CACHE;

/**
 * 设备
 *
 * @author: zxfei
 * @date: 2021/8/24 20:28
 */
@RestController
@Slf4j
@RequestMapping("/api/device")
public class DeviceApiController {
    @Autowired
    private DeviceLogService deviceLogService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private SendTaskThreadPool sendTaskThreadPool;
    @Autowired
    private ICacheService cacheService;

    /**
     * 设备数据上报
     *
     * @param req
     * @return
     */
    @PostMapping("upload")
    public String upload(DeviceReq req) {
        log.debug("【设备数据上报】【请求体】-->  " + JSONObject.toJSONString(req));
        ApiResp<DeviceResp> rsp = new ApiResp<>();
        rsp.setMsg(ApiRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        UploadTask uploadTask = new UploadTask(req, deviceLogService, deviceService);
        if (!ObjectUtils.isEmpty(sendTaskThreadPool)) {
            sendTaskThreadPool.execute(uploadTask);
        }

        //判断当前设备是否设置了标志类型，如果设置了 则访问
        DeviceResp deviceResp = new DeviceResp();
        deviceResp.setCmd(DeviceActionEnum.正常.getValue());
        Integer type = cacheService.get(KEY_DEVICE_TYPE_CACHE + req.getDevicenum(), Integer.class);
        if (!ObjectUtils.isEmpty(type)) {
            deviceResp.setCmd(type);
        }
        rsp.setData(deviceResp);
        cacheService.del(KEY_DEVICE_TYPE_CACHE + req.getDevicenum());
        //if(!ObjectUtils.isEmpty(type))
        log.debug("响应【设备数据上报】【响应体】-->  " + JSONObject.toJSONString(rsp));
        return JSON.toJSONString(rsp);
    }


}
