package com.mortals.xhx.busiz.web;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.ap.GlobalSysInfo;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.IAuthTokenService;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.service.ILogService;
import com.mortals.framework.service.IUser;
import com.mortals.framework.service.impl.FileLogServiceImpl;
import com.mortals.framework.util.DateUtils;
import com.mortals.framework.util.StringUtils;
import com.mortals.xhx.base.framework.annotation.ApiUserAuth;
import com.mortals.xhx.base.login.web.LoginForm;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.busiz.req.DeviceMsgReq;
import com.mortals.xhx.busiz.req.DeviceReq;
import com.mortals.xhx.busiz.req.UploadDeviceReq;
import com.mortals.xhx.busiz.rsp.*;
import com.mortals.xhx.common.code.*;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.common.model.DefaultTbQueueMsgHeaders;
import com.mortals.xhx.common.model.MessageHeader;
import com.mortals.xhx.common.pdu.RespData;
import com.mortals.xhx.common.pdu.site.SitePdu;
import com.mortals.xhx.common.utils.BeanUtil;
import com.mortals.xhx.common.utils.DownMsgTask;
import com.mortals.xhx.common.utils.EncryptUtil;
import com.mortals.xhx.common.utils.SendTaskThreadPool;
import com.mortals.xhx.feign.site.ISiteFeign;
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 com.mortals.xhx.module.firm.model.FirmEntity;
import com.mortals.xhx.module.firm.service.FirmService;
import com.mortals.xhx.module.platform.model.PlatformEntity;
import com.mortals.xhx.module.platform.model.PlatformQuery;
import com.mortals.xhx.module.platform.service.PlatformService;
import com.mortals.xhx.module.product.model.ProductEntity;
import com.mortals.xhx.module.product.model.ProductQuery;
import com.mortals.xhx.module.product.service.ProductService;
import com.mortals.xhx.queue.TbQueueMsgHeaders;
import com.mortals.xhx.queue.TopicPartitionInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.mortals.framework.ap.SysConstains.PROP_PLATFORM_MARK;
import static com.mortals.xhx.common.key.Constant.DES_STR;
import static com.mortals.xhx.common.key.Constant.ENCRYPT_STR;
import static com.mortals.xhx.common.key.ErrorCode.*;
import static com.mortals.xhx.common.key.RedisKey.KEY_TOKEN_API_CACHE;

/**
 * 设备
 *
 * @author: zxfei
 * @date: 2021/8/24 20:28
 */
@RestController
@Slf4j
@RequestMapping("/api")
public class DeviceApiController {
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private ProductService productService;
    @Autowired
    private UserService userService;
    @Autowired
    private IAuthTokenService authTokenService;
    @Autowired
    private PlatformService platformService;
    @Value("${queue.rabbitmq.virtual_host:}")
    private String virtualHost;
    @Value("${queue.rabbitmq.password:}")
    private String password;
    @Value("${queue.rabbitmq.host:}")
    private String host;
    @Value("${queue.rabbitmq.port:}")
    private int port;
    @Value("${queue.rabbitmq.username:}")
    private String username;
    @Value("${queue.rabbitmq.queue-properties.x-message-ttl:86400000}")
    private String messageTtl;
    @Value("${token.secret}")
    private String secret;
    @Autowired
    private SendTaskThreadPool sendTaskThreadPool;
    @Autowired
    private ISiteFeign siteFeign;
    @Autowired
    private FirmService firmService;
    @Autowired
    private DeviceLogService deviceLogService;
    @Autowired
    private ICacheService cacheService;

    @Autowired
    protected ILogService logService = FileLogServiceImpl.getInstance();

    /**
     * 设备注册
     *
     * @param req
     * @return
     */
    @PostMapping("register")
    public String register(@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 = checkDeviceExistAndCreate(req);
            DeviceQueueAuthInfo authInfo = new DeviceQueueAuthInfo();
            authInfo.setHost(host);
            authInfo.setPort(port);
            authInfo.setUsername(username);
            authInfo.setPassword(password);
            authInfo.setMessageTtl(messageTtl);
            authInfo.setVirtualHost(virtualHost);

            ProductEntity productEntity = productService.get(deviceEntity.getProductId());
            if (ObjectUtils.isEmpty(productEntity)) {
                throw new AppException(PRODUCT_IS_EMPTY, PRODUCT_IS_EMPTY_CONTENT);
            }

            if (ObjectUtils.isEmpty(productEntity.getPlatformId())) {
                throw new AppException(PLATFORM_UNEXIST, PLATFORM_UNEXIST_CONTENT);
            }

            PlatformEntity platformEntity = platformService.get(productEntity.getPlatformId());
            if (ObjectUtils.isEmpty(platformEntity)) {
                throw new AppException(PLATFORM_IS_EMPTY, PLATFORM_IS_EMPTY_CONTENT);
            }

            if (deviceEntity.getDeviceStatus() == DeviceStatusEnum.未激活.getValue()) {
                throw new AppException(DEVICE_UNACTIVE, DEVICE_UNACTIVE_CONTENT);
            }

            authInfo.setExchangeName(platformEntity.getPlatformSn() + Constant.EXCHANGE_SPLIT + productEntity.getProductCode());
            authInfo.setUploadTopicFilter(Constant.UPLOAD_TOPIC + deviceEntity.getDeviceCode());
            authInfo.setDownTopicFilter(Constant.DOWN_TOPIC + deviceEntity.getDeviceCode());

            RegisterResp registerResp = new RegisterResp();
            registerResp.setRabbmitInfo(authInfo);
            ServerInfo serverInfo = new ServerInfo();
            serverInfo.setHomeUrl(productEntity.getHomeUrl() == null ? "" : productEntity.getHomeUrl());
            serverInfo.setServerUrl(platformEntity.getSendUrl());
            registerResp.setServiceInfo(serverInfo);
            DeviceInfo deviceInfo = new DeviceInfo();
            deviceInfo.setSiteId(deviceEntity.getSiteId());
            deviceInfo.setSiteCode(deviceEntity.getSiteCode());
            deviceInfo.setSiteName(deviceEntity.getSiteName());
            deviceInfo.setProductId(productEntity.getId());
            deviceInfo.setProductName(productEntity.getProductName());
            deviceInfo.setEnabled(deviceEntity.getEnabled());
            deviceInfo.setSource(deviceEntity.getSource());

            registerResp.setDeviceInfo(deviceInfo);
            String content = EncryptUtil.myEnscrt(JSON.toJSONString(registerResp), 9, DES_STR, ENCRYPT_STR);
            deviceResp.setContent(content);
            deviceEntity.setOnlineTime(new Date());
            deviceEntity.setDeviceStatus(DeviceStatusEnum.在线.getValue());
            deviceService.update(deviceEntity);
            rsp.setData(deviceResp);
            deviceService.sendThirdParty(deviceEntity, productEntity, platformEntity, DeviceMethodEnum.ONLINE);
        } catch (AppException e) {
            log.error("接收数据失败", e);
            rsp.setCode(e.getCode());
            rsp.setMsg(e.getMessage());
            return JSON.toJSONString(rsp);
        } 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);
    }

    /**
     * 获取Token
     *
     * @return
     */
    @PostMapping("getToken")
    public String getToken(@RequestBody LoginForm loginForm) {
        ApiResp<String> rsp = new ApiResp<>();
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        try {
            UserEntity userEntity = userService.doLogin(loginForm.getLoginName(), loginForm.getPassword(), "");
            if (!ObjectUtils.isEmpty(userEntity)) {
//                this.authTokenService.setUser(userEntity);
//                userEntity.setExpireTime(DateUtils.addCurrDate(7).getTime());
//                userEntity.setToken(IdUtil.fastSimpleUUID());
//                String token = authTokenService.createToken(userEntity);
                String token = IdUtil.fastSimpleUUID();

                //long expireTime = DateUtil.between(DateUtil.beginOfWeek(new Date()), DateUtil.endOfWeek(new Date()), DateUnit.SECOND);

                cacheService.setnx(KEY_TOKEN_API_CACHE + token, "", 604800);
                rsp.setData(token);
            }
        } catch (AppException e) {
            log.error("接收数据失败", e);
            rsp.setCode(e.getCode());
            rsp.setMsg(e.getMessage());
            return JSON.toJSONString(rsp);
        } catch (Exception e) {
            log.error("异常", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            return JSON.toJSONString(rsp);
        }
        log.info("响应【获取Token】【响应体】--> {}", JSONObject.toJSONString(rsp));
        return JSON.toJSONString(rsp);
    }

    /**
     * 初始化话设备基本信息
     *
     * @return
     */
    @RequestMapping(value = "deviceInit", method = {RequestMethod.POST, RequestMethod.GET})
    public String deviceInit() {
        ApiResp<DeviceInitResp> rsp = new ApiResp<>();
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        DeviceInitResp deviceInitResp = new DeviceInitResp();
        try {
            List<ProductInfo> productInfoList = productService.find(new ProductEntity()).stream().map(item -> {
                ProductInfo productInfo = new ProductInfo();
                BeanUtils.copyProperties(item, productInfo, BeanUtil.getNullPropertyNames(item));
                productInfo.setProductId(item.getId());
                return productInfo;
            }).collect(Collectors.toList());
            deviceInitResp.setProductList(productInfoList);
            if (ObjectUtils.isEmpty(productInfoList)) deviceInitResp.setProductList(new ArrayList<>());

            List<FirmInfo> firmList = firmService.find(new FirmEntity()).stream().map(item -> {
                FirmInfo firmInfo = new FirmInfo();
                firmInfo.setDeviceFirmId(item.getId());
                firmInfo.setDeviceFirmname(item.getFirmName());
                return firmInfo;
            }).collect(Collectors.toList());

            deviceInitResp.setFirmList(firmList);
            if (ObjectUtils.isEmpty(firmList)) deviceInitResp.setFirmList(new ArrayList<>());
            SitePdu sitePdu = new SitePdu();
            sitePdu.setSize(-1);
            Rest<RespData<List<SitePdu>>> resp = siteFeign.list(sitePdu);
            if (resp.getCode() == 1) {
                List<SitePdu> sitePduList = resp.getData().getData();
                List<SiteInfo> siteInfoList = sitePduList.stream().map(site -> {
                    SiteInfo siteInfo = new SiteInfo();
                    siteInfo.setSiteId(site.getId());
                    siteInfo.setSiteName(site.getSiteName());
                    siteInfo.setSiteCode(site.getSiteCode());
                    return siteInfo;
                }).collect(Collectors.toList());
                deviceInitResp.setSiteList(siteInfoList);
            } else {
                deviceInitResp.setSiteList(new ArrayList<>());
            }
            rsp.setData(deviceInitResp);
        } catch (AppException e) {
            log.error("接收数据失败", e);
            rsp.setCode(e.getCode());
            rsp.setMsg(e.getMessage());
            return JSON.toJSONString(rsp);
        } 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("deviceUpdate")
    public String deviceUpdateApi(@RequestBody DeviceReq req) {
        log.info("【设备前端新增或更新】【请求体】-->  " + JSONObject.toJSONString(req));
        ApiResp<DeviceResp> rsp = new ApiResp<>();
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        DeviceResp deviceResp = new DeviceResp();
        try {
            if (ObjectUtils.isEmpty(req.getDeviceCode())) {
                throw new AppException(DEVICE_CODE_IS_EMPTY, DEVICE_CODE_IS_EMPTY_CONTENT);
            }
            if (ObjectUtils.isEmpty(req.getSiteId())) {
                throw new AppException(SITEID_IS_EMPTY, SITEID_IS_EMPTY_CONTENT);
            }
            ProductEntity productEntity = productService.get(req.getProductId());
            if (ObjectUtils.isEmpty(productEntity)) {
                throw new AppException(PRODUCT_IS_EMPTY, PRODUCT_IS_EMPTY_CONTENT);
            }

            if (ObjectUtils.isEmpty(productEntity.getPlatformId())) {
                throw new AppException(PLATFORM_UNEXIST, PLATFORM_UNEXIST_CONTENT);
            }

            PlatformEntity platformEntity = platformService.get(productEntity.getPlatformId());
            if (ObjectUtils.isEmpty(platformEntity)) {
                throw new AppException(PLATFORM_IS_EMPTY, PLATFORM_IS_EMPTY_CONTENT);
            }

            DeviceEntity deviceEntity = deviceService.getExtCache(req.getDeviceCode());
            if (ObjectUtils.isEmpty(deviceEntity)) {
                //初始化新增基础设备，后续在线完善信息后再行注册添加
                deviceEntity = new DeviceEntity();
                deviceEntity.initAttrValue();
                saveOrUpdate(req, platformEntity, productEntity, deviceEntity);
                deviceEntity.setCreateTime(new Date());
                deviceEntity.setCreateUserId(1L);
                deviceService.save(deviceEntity, null);
            } else {
                //更新
                saveOrUpdate(req, platformEntity, productEntity, deviceEntity);
                deviceEntity.setUpdateTime(new Date());
                deviceEntity.setUpdateUserId(1L);
                deviceService.update(deviceEntity, null);
            }

            if (deviceEntity.getDeviceStatus() == DeviceStatusEnum.未激活.getValue()) {
                throw new AppException(DEVICE_UNACTIVE, DEVICE_UNACTIVE_CONTENT);
            }

            DeviceQueueAuthInfo authInfo = new DeviceQueueAuthInfo();
            authInfo.setHost(host);
            authInfo.setPort(port);
            authInfo.setUsername(username);
            authInfo.setPassword(password);
            authInfo.setMessageTtl(messageTtl);
            authInfo.setVirtualHost(virtualHost);

            authInfo.setExchangeName(platformEntity.getPlatformSn() + Constant.EXCHANGE_SPLIT + productEntity.getProductCode());
            authInfo.setUploadTopicFilter(Constant.UPLOAD_TOPIC + deviceEntity.getDeviceCode());
            authInfo.setDownTopicFilter(Constant.DOWN_TOPIC + deviceEntity.getDeviceCode());

            RegisterResp registerResp = new RegisterResp();
            registerResp.setRabbmitInfo(authInfo);

            ServerInfo serverInfo = new ServerInfo();
            serverInfo.setHomeUrl(productEntity.getHomeUrl());
            serverInfo.setServerUrl(platformEntity.getSendUrl());
            registerResp.setServiceInfo(serverInfo);

            DeviceInfo deviceInfo = new DeviceInfo();
            deviceInfo.setSiteId(deviceEntity.getSiteId());
            deviceInfo.setSiteCode(deviceEntity.getSiteCode());
            deviceInfo.setSiteName(deviceEntity.getSiteName());
            deviceInfo.setProductId(productEntity.getId());
            deviceInfo.setProductName(productEntity.getProductName());
            deviceInfo.setEnabled(deviceEntity.getEnabled());
            deviceInfo.setSource(deviceEntity.getSource());
            registerResp.setDeviceInfo(deviceInfo);
            String content = EncryptUtil.myEnscrt(JSON.toJSONString(registerResp), 9, DES_STR, ENCRYPT_STR);
            deviceResp.setContent(content);
            rsp.setData(deviceResp);
        } catch (AppException e) {
            log.error("接收数据失败", e);
            rsp.setCode(e.getCode());
            rsp.setMsg(e.getMessage());
            return JSON.toJSONString(rsp);
        } 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);
    }

    private void saveOrUpdate(DeviceReq req, PlatformEntity platformEntity, ProductEntity productEntity, DeviceEntity deviceEntity) {
        BeanUtils.copyProperties(req, deviceEntity, BeanUtil.getNullPropertyNames(req));

        deviceEntity.setPlatformId(platformEntity.getId());
        deviceEntity.setPlatformName(platformEntity.getPlatformName());

        deviceEntity.setProductId(productEntity.getId());
        deviceEntity.setProductName(productEntity.getProductName());
        deviceEntity.setProductCode(productEntity.getProductCode());

        deviceEntity.setSiteId(req.getSiteId());
        deviceEntity.setSiteCode(req.getSiteCode());
        deviceEntity.setSiteName(req.getSiteName());

        deviceEntity.setDeviceMac(req.getDeviceCode());
        deviceEntity.setDeviceCode(req.getDeviceCode());

        deviceEntity.setEnabled(YesNoEnum.YES.getValue());
        deviceEntity.setDeviceStatus(DeviceStatusEnum.未激活.getValue());

        deviceEntity.setSource(req.getSource());
    }

    /**
     * 第三方回调
     *
     * @param list
     * @return
     */
    @PostMapping("callback")
    @UnAuth
    public String callback(@RequestBody List<DeviceMsgReq> list) {
        log.info("【设备数据消息接收】【请求体】-->  " + JSONObject.toJSONString(list));
        ApiResp<String> rsp = new ApiResp<>();
        rsp.setMsg(ApiRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        try {
            DownMsgTask downMsgTask = new DownMsgTask(list, platformService, productService, deviceService, deviceLogService);
            sendTaskThreadPool.execute(downMsgTask);
        } catch (AppException e) {
            log.error("接收数据失败", e);
            rsp.setCode(e.getCode());
            rsp.setMsg(e.getMessage());
            return JSON.toJSONString(rsp);
        } 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);
    }


    /**
     * 设备数据上报
     *
     * @param req
     * @return
     */
    @PostMapping("upload")
    public String upload(@RequestBody UploadDeviceReq 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.getDeviceCode());
            if (!ObjectUtils.isEmpty(deviceEntity)) {
                //将上报信息转发到mq中

                PlatformEntity platformEntity = platformService.get(deviceEntity.getPlatformId());
                if (ObjectUtils.isEmpty(platformEntity)) {
                    throw new AppException("当前设备未配置所属系统平台，请在后台配置后再激活！");
                }
                // authInfo.setHost(platformEntity.getPlatformSn());
                ProductEntity productEntity = productService.get(deviceEntity.getProductId());
                if (ObjectUtils.isEmpty(productEntity)) {
                    throw new AppException("当前设备未配置所属产品，请在后台配置后再激活！");
                }
                String exchangeName = platformEntity.getPlatformSn() + Constant.EXCHANGE_SPLIT + productEntity.getProductCode();

                TopicPartitionInfo info = TopicPartitionInfo.builder().exchangeName(exchangeName).topic(Constant.UPLOAD_TOPIC + deviceEntity.getDeviceCode()).build();
                TbQueueMsgHeaders header = new DefaultTbQueueMsgHeaders();
                header.put(MessageHeader.MESSAGETYPE, Constant.MESSAGETYPE_HEARTBEAT);
                header.put(MessageHeader.DEVICECODE, deviceEntity.getDeviceCode());
                for (int i = 0; i < 100; i++) {
                    deviceService.sendDeviceMessage(deviceEntity, info, header, JSON.toJSONString(req),null, null);
                    Thread.sleep(50);
                }
                //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);
    }


    /**
     * 设备对外接收接口
     *
     * @param req
     * @return
     */
    @PostMapping("receive")
    @ApiUserAuth
    public String receive(HttpServletRequest request, @RequestBody DeviceReq req) {
        log.info("【设备接收】【请求体】-->  " + JSONObject.toJSONString(req));
        ApiResp<String> rsp = new ApiResp<>();
        rsp.setMsg(ApiRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        StringBuilder message = new StringBuilder();
        message.append(String.format("【外部请求】类型【%s】 内容:%s", DeviceMethodEnum.getByValue(req.getReceiveMethod()).getDesc(), JSONObject.toJSONString(req)));
        recordSysLog(request, message.toString());
        try {
            switch (DeviceMethodEnum.getByValue(req.getReceiveMethod())) {
                case ADD:
                    deviceAdd(req);
                    break;
                case UPDATE:
                    deviceUpdate(req);
                    break;
                case DEL:
                    deviceDel(req);
                    break;
                case ACTIVE:
                    deviceActive(req);
                    break;
                case ENABLED:
                    deviceEnabled(req);
                    break;
                case STOP:
                    deviceStop(req);
                    break;
            }
        } catch (AppException e) {
            log.error("接收数据失败", e);
            rsp.setCode(e.getCode());
            rsp.setMsg(e.getMessage());
            return JSON.toJSONString(rsp);
        } 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);
    }


    private void deviceAdd(DeviceReq req) throws AppException {
        log.info("【设备新增】【请求体】-->  " + JSONObject.toJSONString(req));
        //根据设备编码查询设备
        DeviceEntity deviceEntity = deviceService.getExtCache(req.getDeviceCode());
        if (!ObjectUtils.isEmpty(deviceEntity)) {
            throw new AppException(DEVICE_CODE_IS_EXIST, DEVICE_CODE_IS_EXIST_CONTENT);
        }
        ProductEntity productEntity = productService.selectOne(new ProductQuery().productCode(req.getProductCode()));
        if (ObjectUtils.isEmpty(productEntity)) {
            throw new AppException(PRODUCT_IS_EMPTY, PRODUCT_IS_EMPTY_CONTENT);
        }
        PlatformEntity platformEntity = platformService.get(productEntity.getPlatformId());
        if (ObjectUtils.isEmpty(platformEntity)) {
            throw new AppException(PLATFORM_IS_EMPTY, PLATFORM_IS_EMPTY_CONTENT);
        }

        deviceEntity = new DeviceEntity();
        deviceEntity.initAttrValue();
        deviceEntity.setDeviceName(req.getDeviceName());
        deviceEntity.setDeviceCode(req.getDeviceCode());
        deviceEntity.setDeviceMac(req.getDeviceCode());
        deviceEntity.setSiteId(req.getSiteId());
        deviceEntity.setSiteCode(req.getSiteCode());
        deviceEntity.setSiteName(req.getSiteName());
        deviceEntity.setPlatformId(platformEntity.getId());
        deviceEntity.setPlatformName(platformEntity.getPlatformName());
        deviceEntity.setProductId(productEntity.getId());
        deviceEntity.setProductName(productEntity.getProductName());
        deviceEntity.setIp(req.getIp());
        deviceEntity.setCenternum(req.getCenternum());
        deviceEntity.setPort(req.getPort());
        deviceEntity.setDeviceRemark(req.getDeviceRemark());
        deviceEntity.setCreateUserId(1L);
        deviceEntity.setCreateTime(new Date());
        deviceEntity.setSwitchSend(false);
        deviceService.save(deviceEntity);

    }

    private void deviceUpdate(DeviceReq req) throws AppException {
        log.info("【设备更新】【请求体】-->  " + JSONObject.toJSONString(req));
        //根据设备编码查询设备
        DeviceEntity deviceEntity = deviceService.getExtCache(req.getDeviceCode());

        if (ObjectUtils.isEmpty(deviceEntity)) {
            throw new AppException(DEVICE_CODE_IS_EMPTY, DEVICE_CODE_IS_EMPTY_CONTENT);
        }

        ProductEntity productEntity = productService.selectOne(new ProductQuery().productCode(req.getProductCode()));
        if (ObjectUtils.isEmpty(productEntity)) {
            throw new AppException(PRODUCT_IS_EMPTY, PRODUCT_IS_EMPTY_CONTENT);
        }

        PlatformEntity platformEntity = platformService.get(productEntity.getPlatformId());
        if (ObjectUtils.isEmpty(platformEntity)) {
            throw new AppException(PLATFORM_IS_EMPTY, PLATFORM_IS_EMPTY_CONTENT);
        }

        deviceEntity.setDeviceName(req.getDeviceName());
        deviceEntity.setDeviceCode(req.getDeviceCode());
        deviceEntity.setDeviceMac(req.getDeviceCode());
        deviceEntity.setSiteId(req.getSiteId());
        deviceEntity.setSiteCode(req.getSiteCode());
        deviceEntity.setSiteName(req.getSiteName());
        deviceEntity.setPlatformId(platformEntity.getId());
        deviceEntity.setPlatformName(platformEntity.getPlatformName());
        deviceEntity.setProductId(productEntity.getId());
        deviceEntity.setProductName(productEntity.getProductName());
        deviceEntity.setIp(req.getIp());
        deviceEntity.setCenternum(req.getCenternum());
        deviceEntity.setPort(req.getPort());
        deviceEntity.setDeviceRemark(req.getDeviceRemark());
        deviceEntity.setUpdateUserId(1L);
        deviceEntity.setUpdateTime(new Date());
        deviceEntity.setSwitchSend(false);
        deviceService.update(deviceEntity);

    }

    private void deviceDel(DeviceReq req) throws AppException {
        log.info("【设备删除】【请求体】-->  " + JSONObject.toJSONString(req));
        //根据设备编码查询设备
        DeviceEntity deviceEntity = checkDeviceExist(req);
        deviceService.remove(new Long[]{deviceEntity.getId()}, null);

    }

    private void deviceActive(DeviceReq req) throws AppException {
        log.info("【设备激活】【请求体】-->  " + JSONObject.toJSONString(req));
        //根据设备编码查询设备
        DeviceEntity deviceEntity = checkDeviceExist(req);
        if (deviceEntity.getDeviceStatus() > DeviceStatusEnum.未激活.getValue()) {
            throw new AppException("当前设备已激活！");
        }
        deviceEntity.setDeviceStatus(DeviceStatusEnum.离线.getValue());
        deviceEntity.setUpdateTime(new Date());
        deviceEntity.setUpdateUserId(1L);
        deviceEntity.setSwitchSend(false);
        deviceService.update(deviceEntity);

    }

    private void deviceEnabled(DeviceReq req) throws AppException {
        log.info("【设备启用】【请求体】-->  " + JSONObject.toJSONString(req));
        //根据设备编码查询设备
        DeviceEntity deviceEntity = checkDeviceExist(req);
        deviceEntity.setEnabled(YesNoEnum.YES.getValue());
        deviceEntity.setUpdateTime(new Date());
        deviceEntity.setUpdateUserId(1L);
        deviceEntity.setSwitchSend(false);
        deviceEntity.setUpdateTime(new Date());
        deviceEntity.setUpdateUserId(1L);
        deviceService.update(deviceEntity);
    }

    private void deviceStop(DeviceReq req) throws AppException {
        log.info("【设备停用】【请求体】-->  " + JSONObject.toJSONString(req));
        DeviceEntity deviceEntity = checkDeviceExist(req);
        deviceEntity.setEnabled(YesNoEnum.NO.getValue());
        deviceEntity.setUpdateTime(new Date());
        deviceEntity.setUpdateUserId(1L);
        deviceEntity.setSwitchSend(false);
        deviceEntity.setUpdateTime(new Date());
        deviceEntity.setUpdateUserId(1L);
        deviceService.update(deviceEntity);
    }

    private DeviceEntity checkDeviceExist(DeviceReq req) {
        if (ObjectUtils.isEmpty(req.getDeviceCode())) {
            throw new AppException(DEVICE_CODE_IS_EMPTY, DEVICE_CODE_IS_EMPTY_CONTENT);
        }
        DeviceEntity deviceEntity = deviceService.getExtCache(req.getDeviceCode());
        if (ObjectUtils.isEmpty(deviceEntity)) {
            throw new AppException(DEVICE_NOT_EXIST, DEVICE_NOT_EXIST_CONTENT);

        }
        return deviceEntity;
    }

    private DeviceEntity checkDeviceExistAndCreate(DeviceReq req) {
        if (ObjectUtils.isEmpty(req.getDeviceCode())) {
            throw new AppException(DEVICE_CODE_IS_EMPTY, DEVICE_CODE_IS_EMPTY_CONTENT);
        }
        DeviceEntity deviceEntity = deviceService.getExtCache(req.getDeviceCode());
        if (ObjectUtils.isEmpty(deviceEntity)) {
            //初始化新增基础设备，后续在线完善信息后再行注册添加
            deviceEntity = new DeviceEntity();
            deviceEntity.initAttrValue();
            deviceEntity.setDeviceMac(req.getDeviceCode());
            deviceEntity.setDeviceCode(req.getDeviceCode());
            deviceEntity.setCreateTime(new Date());
            deviceEntity.setCreateUserId(1L);
            deviceService.getDeviceDao().insert(deviceEntity);
            deviceService.putCache(deviceEntity.getDeviceCode(), deviceEntity);
            throw new AppException(DEVICE_CONFIG_IS_EMPTY, DEVICE_CONFIG_IS_EMPTY_CONTENT);

        }
        return deviceEntity;
    }


    protected void recordSysLog(HttpServletRequest request, String message) {
        if (this.logService != null) {
            String platformMark = "other-platform";
            String requestUrl = request.getRequestURI();
            try {
                this.logService.doHandlerLog(platformMark, 0L, "other", "other", requestUrl, message, ServletUtil.getClientIP(request), new Date());
            } catch (Exception e) {
                this.log.debug("记录系统操作日志异常-->" + e.getMessage());
            }
        }
    }


}
