package com.mortals.xhx.busiz.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mortals.xhx.base.DeviceAuth;
import com.mortals.xhx.base.framework.ws.message.SendToAllRequest;
import com.mortals.xhx.base.framework.ws.util.WebSocketUtil;
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.busiz.security.DeviceTokenService;
import com.mortals.xhx.common.code.*;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.module.device.model.DeviceEntity;
import com.mortals.xhx.module.device.service.DeviceLogService;
import com.mortals.xhx.module.device.service.DeviceService;
import lombok.extern.apachecommons.CommonsLog;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 设备
 *
 * @author: zxfei
 * @date: 2021/8/24 20:28
 */
@RestController
@CommonsLog
@RequestMapping("/api")
public class DeviceApiController {

    @Autowired
    private DeviceLogService deviceLogService;
    @Autowired
    private DeviceService deviceService;

    @Autowired
    private DeviceTokenService deviceTokenService;


    /**
     * 设备激活
     *
     * @param req
     * @return
     */
    @PostMapping("active")
    public String active(@RequestBody DeviceReq req) {
        log.info("【设备激活】【请求体】-->  " + JSONObject.toJSONString(req));
        ApiResp<DeviceResp> rsp = new ApiResp<>();
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        DeviceResp deviceResp = new DeviceResp();
        try {
            //根据设备编码查询设备是否存在，如果存在判断是否已经激活
            DeviceEntity deviceEntity = deviceService.getExtCache(req.getDeviceNum());
            if (!ObjectUtils.isEmpty(deviceEntity)) {
                //判断设备是否已经激活，如果已激活返回token信息
                if (deviceEntity.getActive() == ActiveEnum.已激活.getValue() && deviceEntity.getStatus() == StatusEnum.启用.getValue()) {
                    String token = deviceTokenService.createToken(deviceEntity);
                    deviceResp.setToken(token);
                }
                deviceEntity.setOnlineTime(new Date());
                deviceEntity.setDeviceOnlineStatus(DeviceOnlineStatusEnum.在线.getValue());
                deviceEntity.setIp(req.getIp());
                deviceEntity.setPort(req.getPort());
                deviceEntity.setSiteNum(req.getSitenum());
                deviceEntity.setCenternum(req.getCenternum());
                deviceService.update(deviceEntity);
            } else {
                //新增设备
                deviceEntity = new DeviceEntity();
                deviceEntity.initAttrValue();
                deviceEntity.setDeviceCode(req.getDeviceNum());
                deviceEntity.setDeviceMac(req.getDeviceMac());
                deviceEntity.setIp(req.getIp());
                deviceEntity.setPort(req.getPort());
                deviceEntity.setSiteNum(req.getSitenum());
                deviceEntity.setCenternum(req.getCenternum());
                deviceEntity.setCreateUserId(1L);
                deviceEntity.setCreateTime(new Date());
                deviceService.save(deviceEntity);
                rsp.setMsg("当前设备未激活，激活后再上线。");
                WebSocketUtil.broadcast(SendToAllRequest.TYPE, new SendToAllRequest().setContent(JSON.toJSONString(deviceEntity)));
            }
            rsp.setData(deviceResp);
        } catch (Exception e) {
            log.error("接收数据失败", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            return JSON.toJSONString(rsp);
        }
        log.info("响应【设备激活】【响应体】-->  " + JSONObject.toJSONString(rsp));
        return JSON.toJSONString(rsp);
    }


    /**
     * 设备数据上报
     *
     * @param req
     * @return
     */
    @PostMapping("upload")
    @DeviceAuth
    public String upload(@RequestBody DeviceReq req) {
        log.info("【设备数据上报】【请求体】-->  " + JSONObject.toJSONString(req));
        ApiResp<String> rsp = new ApiResp<>();
        rsp.setMsg(ApiRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        try {
            //根据设备编码查询设备
            DeviceEntity deviceEntity = deviceService.getExtCache(req.getDeviceNum());
            if (!ObjectUtils.isEmpty(deviceEntity)) {
                //将上报信息转发到mq中
                ApiResp<String> sendDeviceMessageResp = deviceService.sendDeviceMessage(deviceEntity.getId(), Constant.UPLOAD_TOPIC, JSON.toJSONString(req), null);
            log.info(String.format("sendMsgResp:%s", JSON.toJSONString(sendDeviceMessageResp)));
            }
        } catch (Exception e) {
            log.error("接收数据失败", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            return JSON.toJSONString(rsp);
        }

        log.debug("响应【设备数据上报】【响应体】-->  " + JSONObject.toJSONString(rsp));
        return JSON.toJSONString(rsp);
    }


}
