package com.mortals.xhx.busiz.web;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.net.URLDecoder;
import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.model.OrderCol;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.service.ILogService;
import com.mortals.framework.service.impl.FileLogServiceImpl;
import com.mortals.framework.util.DataUtil;
import com.mortals.framework.util.DateUtils;
import com.mortals.xhx.base.login.web.LoginForm;
import com.mortals.xhx.base.system.message.impl.MessageProducer;
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.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.key.QueueKey;
import com.mortals.xhx.common.key.RedisKey;
import com.mortals.xhx.common.model.DefaultTbQueueMsgHeaders;
import com.mortals.xhx.common.model.MessageHeader;
import com.mortals.xhx.common.pdu.DeviceReq;
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.model.DeviceModuleDistributeEntity;
import com.mortals.xhx.module.device.model.DeviceModuleDistributeQuery;
import com.mortals.xhx.module.device.model.DeviceQuery;
import com.mortals.xhx.module.device.service.DeviceLogService;
import com.mortals.xhx.module.device.service.DeviceModuleDistributeService;
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.service.PlatformService;
import com.mortals.xhx.module.product.model.ProductEntity;
import com.mortals.xhx.module.product.model.ProductQuery;
import com.mortals.xhx.module.product.model.ProductVersionEntity;
import com.mortals.xhx.module.product.model.ProductVersionQuery;
import com.mortals.xhx.module.product.service.ProductService;
import com.mortals.xhx.module.product.service.ProductVersionService;
import com.mortals.xhx.module.site.model.SiteQuery;
import com.mortals.xhx.module.site.service.SiteService;
import com.mortals.xhx.queue.DefaultTbQueueMsg;
import com.mortals.xhx.queue.TbQueueMsg;
import com.mortals.xhx.queue.TbQueueMsgHeaders;
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 javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.*;
import java.util.stream.Collectors;

import static com.mortals.xhx.common.key.Constant.*;
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 ProductVersionService productVersionService;
    @Autowired
    private PlatformService platformService;
    @Value("${spring.rabbitmq.virtual-host:}")
    private String virtualHost;
    @Value("${spring.rabbitmq.password:}")
    private String password;
    @Value("${spring.rabbitmq.host:}")
    private String host;
    @Value("${spring.rabbitmq.port:0}")
    private int port;
    @Value("${spring.rabbitmq.username:}")
    private String username;
    @Value("${spring.rabbitmq.queue-properties.x-message-ttl:86400000}")
    private String messageTtl;
    @Value("${token.secret}")
    private String secret;

    //private String masterhost = "10.12.185.213";
    //private String phpUrl = "http://10.12.185.213:8090";
    @Autowired
    private SendTaskThreadPool sendTaskThreadPool;
    @Autowired
    private ISiteFeign siteFeign;
    @Value("${platform.type:cloud}")
    private String platFormType;//版本，默认云服务版本
    @Autowired
    private SiteService siteService;
    @Autowired
    private FirmService firmService;
    @Autowired
    private DeviceLogService deviceLogService;
    @Autowired
    private ICacheService cacheService;
    @Autowired
    private MessageProducer messageProducer;
    @Autowired
    private DeviceModuleDistributeService deviceModuleDistributeService;

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

    /**
     * 设备注册
     *
     * @param req
     * @return
     */
    @PostMapping("register")
    @UnAuth
    public String register(HttpServletRequest request, @RequestBody DeviceReq req) {
        log.info("【设备注册】【请求体】-->  " + JSONObject.toJSONString(req));
        String serverName = request.getHeader("server-name");
        String scheme = request.getHeader("server-scheme");
        Integer serverPort = DataUtil.converStr2Int(request.getHeader("server-port"), 0);
        String xforwardedfor = request.getHeader("x-forwarded-for");
        String realIP = request.getHeader("X-Real-IP");
        if (ObjectUtils.isEmpty(scheme)) {
            scheme = "http";
        }
        log.info("scheme:{},request uri:{},request url:{},serverName:{},serverPort:{},xforwardedfor:{},realIP:{}", scheme, request.getRequestURI(), request.getRequestURL(), serverName, serverPort, xforwardedfor, realIP);
        ApiResp<DeviceResp> rsp = new ApiResp<>();
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        DeviceResp deviceResp = new DeviceResp();

        URL url = getServerUrl();
        try {
            DeviceEntity deviceEntity = checkDeviceExistAndCreate(req);
            DeviceQueueAuthInfo authInfo = new DeviceQueueAuthInfo();
            //authInfo.setHost(masterhost);
            //设备地址修改为客户端访问服务端的ip地址
            // authInfo.setHost(url.getHost());
            if (!ObjectUtils.isEmpty(serverName) && Validator.isIpv4(serverName)) {
                authInfo.setHost(serverName);
            } else {
                log.info("设置后台定义的参数地址!{}", url.toString());
                authInfo.setHost(url.getHost());
            }
            authInfo.setPort(port);
            authInfo.setUsername(username);
            authInfo.setPassword(password);
            authInfo.setMessageTtl(messageTtl);
            authInfo.setVirtualHost(virtualHost);

            if (ObjectUtils.isEmpty(deviceEntity.getProductId())) {
                throw new AppException(PRODUCT_IS_EMPTY, PRODUCT_IS_EMPTY_CONTENT);
            }

            ProductEntity productEntity = productService.getCache(deviceEntity.getProductId().toString());
            if (ObjectUtils.isEmpty(productEntity)) {
                throw new AppException(PRODUCT_IS_EMPTY, PRODUCT_IS_EMPTY_CONTENT + "productId:" + deviceEntity.getProductId());
            }

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

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

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

            //单一交换机
            authInfo.setExchangeName(QueueKey.DEFAULT_EXCHANGE);
            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.setScheme(scheme);
            //判断设备是否设置了url 如果设置了，则用设备的 否则用产品的
            //buildHomeUrl(deviceEntity, productEntity, serverInfo, serverName, serverPort);

            //判断当前设备是否设置了分辨率 如果设置了 查询当前设备的资源路径是否存在 如果存在
            String resolution = deviceEntity.getResolution();
            if (!ObjectUtils.isEmpty(resolution)) {
                DeviceModuleDistributeQuery query = new DeviceModuleDistributeQuery();
                query.setProductId(productEntity.getId());
                query.setImageResolution(resolution);
                query.setDistribute(DistributeEnum.是.getValue());
                DeviceModuleDistributeEntity distribute = deviceModuleDistributeService.selectOne(query);
                if(!ObjectUtils.isEmpty(distribute)){
                    //homeDeviceUrl/1/pdj/1920x1080
                    String homeUrl = String.format("/homeDeviceUrl/%s/%s/%s", distribute.getSiteId(), distribute.getProductCode(), distribute.getImageResolutionValue());
                    //根据部署的资源 生成homeurl
                    String domain = GlobalSysInfo.getParamValue(PARAM_SERVER_HTTP_URL, "http://192.168.0.98:11078");
                    if (!ObjectUtils.isEmpty(serverName) && Validator.isIpv4(serverName)) {
                        String str = UrlBuilder.of().setScheme(scheme).setHost(serverName).setPort(serverPort > 0 ? serverPort : 11078).addPath(homeUrl).build();
                        String decodeStr = URLDecoder.decode(str, Charset.defaultCharset());
                        serverInfo.setHomeUrl(decodeStr);
                        serverInfo.setEventUrl(productEntity.getEventUrl());
                    } else {
                        String str = UrlBuilder.of(domain.trim()).addPath(homeUrl).build();
                        String decodeStr = URLDecoder.decode(str, Charset.defaultCharset());
                        serverInfo.setHomeUrl(decodeStr);
                        serverInfo.setEventUrl(productEntity.getEventUrl());
                    }
                }else{
                    buildHomeUrlBySite(deviceEntity, productEntity, serverInfo, serverName, serverPort);
                }
            }else{
                buildHomeUrlBySite(deviceEntity, productEntity, serverInfo, serverName, serverPort);
            }
            //对外地址，访问ip+端口 端口号由platformEntity.getSendUrl()获取
            URI uri = new URI(platformEntity.getSendUrl());
            int port = uri.getPort();
            if (port != -1 && !ObjectUtils.isEmpty(serverName) && Validator.isIpv4(serverName)) {
                String serverUrl = UrlBuilder.of().setScheme(scheme).setHost(serverName).setPort(port > 0 ? port : 11078).build();
                //String serverUrl = UrlBuilder.ofHttp(serverName).setPort(port).build();
                serverInfo.setServerUrl(serverUrl);
            } else {
                serverInfo.setServerUrl(platformEntity.getSendUrl());
            }
            //serverInfo.setServerUrl(platformEntity.getSendUrl());
            //String phpUrl=GlobalSysInfo.getParamValue(PARAM_SERVER_PHP_HTTP_URL, "http://10.12.185.213:8090");
            //serverInfo.setServerUrl(phpUrl);
            registerResp.setServiceInfo(serverInfo);
            DeviceInfo deviceInfo = new DeviceInfo();
            deviceInfo.setSiteId(deviceEntity.getSiteId());
            deviceInfo.setSiteCode(deviceEntity.getSiteCode());
            deviceInfo.setSiteName(deviceEntity.getSiteName());
            deviceInfo.setProductId(productEntity.getId());
            deviceInfo.setProductCode(productEntity.getProductCode());
            deviceInfo.setProductName(productEntity.getProductName());
            deviceInfo.setEnabled(deviceEntity.getEnabled());
            deviceInfo.setSource(deviceEntity.getSource());

            registerResp.setDeviceInfo(deviceInfo);
            log.info("resp:" + JSON.toJSONString(registerResp));
            String content = EncryptUtil.myEnscrt(JSON.toJSONString(registerResp), 9, DES_STR, ENCRYPT_STR);
            deviceResp.setContent(content);
            deviceEntity.setOnlineTime(new Date());
            deviceEntity.setDeviceStatus(DeviceStatusEnum.在线.getValue());
            deviceEntity.setDeviceVersion(req.getDeviceVersion() == null ? "" : req.getDeviceVersion());

            if (deviceEntity.getDeviceStatus() == DeviceStatusEnum.离线.getValue()) {
                DeviceEntity condition = new DeviceEntity();
                condition.setId(deviceEntity.getId());
                condition.setOnlineTime(new Date());
                condition.setDeviceStatus(DeviceStatusEnum.在线.getValue());
                cacheService.lpush(RedisKey.KEY_DEVICE_THIRDPARTY_QUEUE, condition);
                cacheService.lpush(RedisKey.KEY_DEVICE_UPDATE_QUEUE, condition);
            }
            //   deviceService.getDeviceDao().update(deviceEntity);
            rsp.setData(deviceResp);
/*            SendThirdPartyTask sendThirdPartyTask = new SendThirdPartyTask(deviceEntity, productEntity, platformEntity, deviceService);
            sendTaskThreadPool.execute(sendThirdPartyTask);*/
        } catch (AppException e) {
            //log.error("接收数据失败", e);
            rsp.setCode(e.getCode());
            rsp.setMsg(e.getMessage());
            log.info("响应【设备注册】【响应体】-->  " + JSONObject.toJSONString(rsp));
            return JSON.toJSONString(rsp);
        } catch (Exception e) {
            log.error("接收数据异常", e);
            rsp.setCode(ApiRespCodeEnum.FAILED.getValue());
            rsp.setMsg(e.getMessage());
            log.info("响应【设备注册】【响应体】-->  " + JSONObject.toJSONString(rsp));
            return JSON.toJSONString(rsp);
        }
        //log.info("响应【设备注册】【响应体】-->  " + JSONObject.toJSONString(rsp));
        return JSON.toJSONString(rsp);
    }

    private static URL getServerUrl() {
        String domain = GlobalSysInfo.getParamValue(PARAM_SERVER_HTTP_URL, "http://192.168.0.98:11091");
        URL url = URLUtil.url(domain);
        return url;
    }


    /**
     * 获取Token
     *
     * @return
     */
    @PostMapping("getToken")
    @UnAuth
    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)) {
                String token = IdUtil.fastSimpleUUID();
                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})
    @UnAuth
    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<>());

            if (platFormType.equalsIgnoreCase(PlatformTypeEnum.STANDALONE.getValue())) {
                List<SiteInfo> siteInfoList = siteService.find(new SiteQuery()).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 {
                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")
    @UnAuth
    public String deviceUpdateApi(HttpServletRequest request, @RequestBody DeviceReq req) {
        String serverName = request.getHeader("server-name");
        Integer serverPort = DataUtil.converStr2Int(request.getHeader("server-port"), 0);
        String scheme = request.getHeader("server-scheme");
        if (ObjectUtils.isEmpty(scheme)) {
            scheme = "http";
        }
//        String serverName = request.getServerName();
//        int serverPort = request.getServerPort();
        log.info("【设备前端新增或更新】【请求体】-->{}  ,serverName:{}", JSONObject.toJSONString(req), serverName);
        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.getCache(req.getProductId().toString());
            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.getCache(productEntity.getPlatformId().toString());
            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();
                saveDevice(req, platformEntity, productEntity, deviceEntity);
                deviceEntity.setCreateTime(new Date());
                deviceEntity.setCreateUserId(1L);
                deviceService.save(deviceEntity, null);
            } else {
                //更新
                updateDevice(req, platformEntity, productEntity, deviceEntity);
                deviceEntity.setUpdateTime(new Date());
                deviceEntity.setUpdateUserId(1L);
                //cacheService.lpush(RedisKey.KEY_DEVICE_UPDATE_QUEUE, deviceEntity);
                deviceService.update(deviceEntity, null);
            }

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

            DeviceQueueAuthInfo authInfo = new DeviceQueueAuthInfo();
            URL url = getServerUrl();
            //authInfo.setHost(masterhost);
            authInfo.setHost(url.getHost());
            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.setExchangeName(QueueKey.DEFAULT_EXCHANGE);
            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.setScheme(scheme);
            // buildHomeUrl(deviceEntity, productEntity, serverInfo, serverName, serverPort);
            String resolution = deviceEntity.getResolution();
            if (!ObjectUtils.isEmpty(resolution)) {
                DeviceModuleDistributeQuery query = new DeviceModuleDistributeQuery();
                query.setProductId(productEntity.getId());
                query.setImageResolution(resolution);
                query.setDistribute(DistributeEnum.是.getValue());
                DeviceModuleDistributeEntity distribute = deviceModuleDistributeService.selectOne(query);
                if(!ObjectUtils.isEmpty(distribute)){
                    //homeDeviceUrl/1/pdj/1920x1080
                    String homeUrl = String.format("/homeDeviceUrl/%s/%s/%s", distribute.getSiteId(), distribute.getProductCode(), distribute.getImageResolutionValue());
                    //根据部署的资源 生成homeurl
                    String domain = GlobalSysInfo.getParamValue(PARAM_SERVER_HTTP_URL, "http://192.168.0.98:11078");
                    if (!ObjectUtils.isEmpty(serverName) && Validator.isIpv4(serverName)) {
                        String str = UrlBuilder.of().setScheme(scheme).setHost(serverName).setPort(serverPort > 0 ? serverPort : 11078).addPath(homeUrl).build();
                        String decodeStr = URLDecoder.decode(str, Charset.defaultCharset());
                        serverInfo.setHomeUrl(decodeStr);
                        serverInfo.setEventUrl(productEntity.getEventUrl());
                    } else {
                        String str = UrlBuilder.of(domain.trim()).addPath(homeUrl).build();
                        String decodeStr = URLDecoder.decode(str, Charset.defaultCharset());
                        serverInfo.setHomeUrl(decodeStr);
                        serverInfo.setEventUrl(productEntity.getEventUrl());
                    }
                }else{
                    buildHomeUrlBySite(deviceEntity, productEntity, serverInfo, serverName, serverPort);
                }
            }else{
                buildHomeUrlBySite(deviceEntity, productEntity, serverInfo, serverName, serverPort);
            }

            URI uri = new URI(platformEntity.getSendUrl());
            int port = uri.getPort();
            if (port != -1 && !ObjectUtils.isEmpty(serverName) && Validator.isIpv4(serverName)) {
                String serverUrl = UrlBuilder.of().setScheme(scheme).setHost(serverName).setPort(port > 0 ? port : 11078).build();
                //String serverUrl = UrlBuilder.ofHttp(serverName).setPort(port).build();
                serverInfo.setServerUrl(serverUrl);
            } else {
                serverInfo.setServerUrl(platformEntity.getSendUrl());
            }
            //serverInfo.setServerUrl(platformEntity.getSendUrl());
            //String phpUrl=GlobalSysInfo.getParamValue(PARAM_SERVER_PHP_HTTP_URL, "http://10.12.185.213:8090");
            //serverInfo.setServerUrl(phpUrl);
            registerResp.setServiceInfo(serverInfo);

            DeviceInfo deviceInfo = new DeviceInfo();
            deviceInfo.setSiteId(deviceEntity.getSiteId());
            deviceInfo.setSiteCode(deviceEntity.getSiteCode());
            deviceInfo.setSiteName(deviceEntity.getSiteName());
            deviceInfo.setProductId(productEntity.getId());
            deviceInfo.setProductCode(productEntity.getProductCode());
            deviceInfo.setProductName(productEntity.getProductName());
            deviceInfo.setEnabled(deviceEntity.getEnabled());
            deviceInfo.setSource(deviceEntity.getSource());
            registerResp.setDeviceInfo(deviceInfo);
            log.info("响应【设备前端新增或更新】【响应体】-->  " + JSONObject.toJSONString(registerResp));
            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);
        }
        return JSON.toJSONString(rsp);
    }


    /**
     * 检查设备最新版本信息
     *
     * @param req
     * @return
     */
    @PostMapping("checkVersion")
    @UnAuth
    public String checkVersion(HttpServletRequest request, @RequestBody DeviceReq req) {
        String serverName = request.getHeader("server-name");
        Integer serverPort = DataUtil.converStr2Int(request.getHeader("server-port"), 0);
//        String serverName = request.getServerName();
//        int serverPort = request.getServerPort();
        log.info("【检查设备最新版本信息】【请求体】-->  " + JSONObject.toJSONString(req));
        ApiResp<DeviceResp> rsp = new ApiResp<>();
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        DeviceResp deviceResp = new DeviceResp();
        try {
            DeviceEntity deviceEntity = checkDeviceExist(req);

            //查找版本号最大的.  todo 根据站点来划分
            ProductVersionQuery productVersionQuery = new ProductVersionQuery();
            productVersionQuery.setProductId(deviceEntity.getProductId());
            productVersionQuery.setSiteId(deviceEntity.getSiteId());
            productVersionQuery.setOrderColList(Arrays.asList(new OrderCol("version", OrderCol.DESCENDING)));
            ProductVersionEntity productVersionEntity = productVersionService.find(productVersionQuery).stream().filter(item -> StrUtil.endWith(item.getFilePath(), ".apk", true)).findFirst().orElseGet(() -> null);
            // ProductVersionEntity productVersionEntity = productVersionService.selectOne(productVersionQuery);
            if (ObjectUtils.isEmpty(productVersionEntity)) {
                throw new AppException(DEVICE_VERSION_UNEXIST, DEVICE_VERSION_UNEXIST_CONTENT);
            }
            ProductVersionInfo productVersionInfo = new ProductVersionInfo();
            BeanUtils.copyProperties(productVersionEntity, productVersionInfo, BeanUtil.getNullPropertyNames(productVersionEntity));

            buildDownloadUrl(productVersionEntity, productVersionInfo, serverName, serverPort);
            String content = EncryptUtil.myEnscrt(JSON.toJSONString(productVersionInfo), 9, DES_STR, ENCRYPT_STR);
            log.info("响应【设备版本检查】【响应体】-->  " + JSONObject.toJSONString(productVersionInfo));
            deviceResp.setContent(content);
            rsp.setData(deviceResp);
        } catch (AppException 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);
        }
        return JSON.toJSONString(rsp);
    }


    /**
     * 检查设备最新版本信息
     *
     * @param req
     * @return
     */
    @PostMapping("checkVersionbak")
    @UnAuth
    public String checkVersionbak(HttpServletRequest request, @RequestBody DeviceReq req) {
        String serverName = request.getHeader("server-name");
        Integer serverPort = DataUtil.converStr2Int(request.getHeader("server-port"), 0);
//        String serverName = request.getServerName();
//        int serverPort = request.getServerPort();
        log.info("【检查设备最新版本信息】【请求体】-->  " + JSONObject.toJSONString(req));
        ApiResp<DeviceResp> rsp = new ApiResp<>();
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        DeviceResp deviceResp = new DeviceResp();
        try {
            DeviceEntity deviceEntity = checkDeviceExist(req);
            //查找版本号最大的.
            ProductVersionQuery productVersionQuery = new ProductVersionQuery();
            productVersionQuery.setProductId(deviceEntity.getProductId());
            productVersionQuery.setOrderColList(Arrays.asList(new OrderCol("version", OrderCol.DESCENDING)));
            //productVersionQuery.setOrderKind(OrderCol.DESCENDING);

            ProductVersionEntity productVersionEntity = productVersionService.selectOne(productVersionQuery);
            if (ObjectUtils.isEmpty(productVersionEntity)) {
                throw new AppException(DEVICE_VERSION_UNEXIST, DEVICE_VERSION_UNEXIST_CONTENT);
            }
            ProductVersionInfo productVersionInfo = new ProductVersionInfo();
            BeanUtils.copyProperties(productVersionEntity, productVersionInfo, BeanUtil.getNullPropertyNames(productVersionEntity));

            buildDownloadUrl(productVersionEntity, productVersionInfo, serverName, serverPort);
            String content = EncryptUtil.myEnscrt(JSON.toJSONString(productVersionInfo), 9, DES_STR, ENCRYPT_STR);
            log.info("响应【设备版本检查】【响应体】-->  " + JSONObject.toJSONString(productVersionInfo));
            deviceResp.setContent(content);
            rsp.setData(deviceResp);
        } catch (AppException 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);
        }
        return JSON.toJSONString(rsp);
    }

    private void saveDevice(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());
    }


    private void updateDevice(DeviceReq req, PlatformEntity platformEntity, ProductEntity productEntity, DeviceEntity deviceEntity) {
        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.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 {
            deviceService.downMsg(list);
        } 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
     * @return
     */
    @PostMapping("callbackByProduct")
    @UnAuth
    public String callbackByProduct(@RequestBody DeviceMsgReq deviceMsgReq, HttpServletRequest req) {
        log.info("【设备产品数据消息接收】【请求体】--> {} reqAddr:{}", JSONObject.toJSONString(deviceMsgReq), req.getRemoteAddr());
        ApiResp<String> rsp = new ApiResp<>();
        rsp.setMsg(ApiRespCodeEnum.SUCCESS.getLabel());
        rsp.setCode(ApiRespCodeEnum.SUCCESS.getValue());
        try {
            ProductEntity productEntity = productService.selectOne(new ProductQuery().productCode(deviceMsgReq.getProductCode()));
            if (!ObjectUtils.isEmpty(productEntity)) {
                List<DeviceEntity> deviceEntities = deviceService.find(new DeviceQuery().productId(productEntity.getId()).siteId(deviceMsgReq.getSiteid()));
                List<DeviceMsgReq> list = deviceEntities.stream().map(item -> {
                    DeviceMsgReq msgReq = new DeviceMsgReq();
                    BeanUtils.copyProperties(deviceMsgReq, msgReq, BeanUtil.getNullPropertyNames(deviceMsgReq));
                    msgReq.setDeviceCode(item.getDeviceCode());
                    return msgReq;
                }).collect(Collectors.toList());
                DownMsgTask downMsgTask = new DownMsgTask(list, platformService, productService, deviceService, deviceLogService, messageProducer);
                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")
    @UnAuth
    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.getCache(deviceEntity.getPlatformId().toString());
                if (ObjectUtils.isEmpty(platformEntity)) {
                    throw new AppException("当前设备未配置所属系统平台，请在后台配置后再激活！");
                }
                // authInfo.setHost(platformEntity.getPlatformSn());
                ProductEntity productEntity = productService.getCache(deviceEntity.getProductId().toString());
                if (ObjectUtils.isEmpty(productEntity)) {
                    throw new AppException("当前设备未配置所属产品，请在后台配置后再激活！");
                }

                TbQueueMsgHeaders header = new DefaultTbQueueMsgHeaders();
                header.put(MessageHeader.MESSAGETYPE, MESSAGETYPE_HEARTBEAT);
                header.put(MessageHeader.DEVICECODE, req.getDeviceCode());
                header.put(MessageHeader.TIMESTAMP, DateUtils.getCurrStrDateTime());
                header.put(MessageHeader.MESSAGESIGN, "abcd1234");
                TbQueueMsg queueMsg = new DefaultTbQueueMsg(IdUtil.fastUUID(), "==", header);
//                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 < 10; i++) {
                    messageProducer.sendMsg(QueueKey.DEFAULT_EXCHANGE, Constant.UPLOAD_TOPIC + deviceEntity.getDeviceCode(), JSON.toJSONString(queueMsg));
                    //log.info("sendMesageTopic:{}", JSON.toJSONString(info));
                    //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")
    @UnAuth
    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.getCache(productEntity.getPlatformId().toString());
        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.setProductCode(productEntity.getProductCode());
        deviceEntity.setProductName(productEntity.getProductName());
        deviceEntity.setIp(req.getIp());
        deviceEntity.setCenternum(req.getCenternum());
        deviceEntity.setPort(req.getPort());
        deviceEntity.setLeadingOfficial(req.getLeadingOfficial());
        deviceEntity.setLeadingOfficialTelephone(req.getLeadingOfficialTelephone());
        deviceEntity.setDeviceRemark(req.getDeviceRemark());
        deviceEntity.setCreateUserId(1L);
        deviceEntity.setCreateTime(new Date());
        deviceEntity.setSwitchSend(false);
        if (!ObjectUtils.isEmpty(req.getResolution())) {
            deviceEntity.setResolution(req.getResolution());
            deviceEntity.setResolutionValue(req.getResolution());
        }
        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.getCache(productEntity.getPlatformId().toString());
        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.setProductCode(productEntity.getProductCode());
        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);
        deviceEntity.setLeadingOfficial(req.getLeadingOfficial());
        deviceEntity.setDeviceInFloor(req.getDeviceInFloor());
        deviceEntity.setDeviceInBuilding(req.getDeviceInBuilding());
        if (!ObjectUtils.isEmpty(req.getResolution())) {
            deviceEntity.setResolution(req.getResolution());
            deviceEntity.setResolutionValue(req.getResolution());
        }
        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.setOfflineTime(new Date());
        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.selectOne(new DeviceQuery().deviceCode(req.getDeviceCode()));
        if (ObjectUtils.isEmpty(deviceEntity)) {
            //初始化新增基础设备，后续在线完善信息后再行注册添加
            deviceEntity = new DeviceEntity();
            deviceEntity.initAttrValue();
            deviceEntity.setDeviceMac(req.getDeviceCode());
            deviceEntity.setDeviceCode(req.getDeviceCode());
            deviceEntity.setDeviceVersion(req.getDeviceVersion() == null ? "" : req.getDeviceVersion());
            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());
            }
        }
    }

    private void buildHomeUrlBySite(DeviceEntity deviceEntity, ProductEntity productEntity, ServerInfo serverInfo, String serverName, Integer serverPort) {
        String scheme = serverInfo.getScheme();
        String homeUrl = "";
        //根据站点与资源部署来生成homeurl
        DeviceModuleDistributeQuery query = new DeviceModuleDistributeQuery();
        query.setSiteId(deviceEntity.getSiteId());
        query.setProductId(productEntity.getId());
        query.setDistribute(DistributeEnum.是.getValue());
        query.setSelectedList(Arrays.asList(YesNoEnum.YES.getValue(), YesNoEnum.NO.getValue()));
        query.setOrderColList(Arrays.asList(new OrderCol("selected", OrderCol.DESCENDING)));
        DeviceModuleDistributeEntity deviceModuleDistributeEntity = deviceModuleDistributeService.selectOne(query);
        if (ObjectUtils.isEmpty(deviceModuleDistributeEntity)) {
        } else {
            //homeDeviceUrl/1/pdj/1920x1080
            homeUrl = String.format("/homeDeviceUrl/%s/%s/%s", deviceModuleDistributeEntity.getSiteId(), deviceModuleDistributeEntity.getProductCode(), deviceModuleDistributeEntity.getImageResolutionValue());

            //根据部署的资源 生成homeurl
            String domain = GlobalSysInfo.getParamValue(PARAM_SERVER_HTTP_URL, "http://192.168.0.98:11078");
            if (!ObjectUtils.isEmpty(serverName) && Validator.isIpv4(serverName)) {
                String str = UrlBuilder.of().setScheme(scheme).setHost(serverName).setPort(serverPort > 0 ? serverPort : 11078).addPath(homeUrl).build();
                String decodeStr = URLDecoder.decode(str, Charset.defaultCharset());
                serverInfo.setHomeUrl(decodeStr);
                serverInfo.setEventUrl(productEntity.getEventUrl());
            } else {
                String str = UrlBuilder.of(domain.trim()).addPath(homeUrl).build();
                String decodeStr = URLDecoder.decode(str, Charset.defaultCharset());
                serverInfo.setHomeUrl(decodeStr);
                serverInfo.setEventUrl(productEntity.getEventUrl());
            }
        }

    }

    private void buildHomeUrl(DeviceEntity deviceEntity, ProductEntity productEntity, ServerInfo serverInfo, String serverName, Integer serverPort) {
        String homeUrl = "";
        if (!ObjectUtils.isEmpty(productEntity.getHomeUrl())) {
            homeUrl = productEntity.getHomeUrl();
        }

        if (!ObjectUtils.isEmpty(deviceEntity.getHomeUrl())) {
            homeUrl = deviceEntity.getHomeUrl();
        }
        //log.info("domain:" + GlobalSysInfo.getParamValue(PARAM_SERVER_HTTP_URL, ""));
        String domain = GlobalSysInfo.getParamValue(PARAM_SERVER_HTTP_URL, "http://127.0.0.1:11078");
        if (!ObjectUtils.isEmpty(serverName) && Validator.isIpv4(serverName)) {
            String str = UrlBuilder.ofHttp(serverName).setPort(serverPort > 0 ? serverPort : 11078).addPath(homeUrl).build();
            String decodeStr = URLDecoder.decode(str, Charset.defaultCharset());
            serverInfo.setHomeUrl(decodeStr);
            serverInfo.setEventUrl(productEntity.getEventUrl());
        } else {
            String str = UrlBuilder.of(domain.trim()).addPath(homeUrl).build();
            String decodeStr = URLDecoder.decode(str, Charset.defaultCharset());
            serverInfo.setHomeUrl(decodeStr);
            serverInfo.setEventUrl(productEntity.getEventUrl());
        }


    }

    private void buildDownloadUrl(ProductVersionEntity productVersionEntity, ProductVersionInfo productVersionInfo, String serverName, Integer serverPort) {
        String download = "";
        if (!ObjectUtils.isEmpty(productVersionEntity.getFilePath())) {
            String fileType = FileUtil.extName(productVersionEntity.getFilePath());
            if ("zip".equals(fileType)) {
                String mainName = FileUtil.mainName(productVersionEntity.getFilePath());
                String replace = StrUtil.replace(productVersionEntity.getFilePath(), FileUtil.getName(productVersionEntity.getFilePath()), "");
                download = replace + mainName + "/";
                log.info("download:" + download);
            } else {
                download = productVersionEntity.getFilePath();
                log.info("download:" + download);
            }
        }
        String domain = GlobalSysInfo.getParamValue(PARAM_SERVER_HTTP_URL, "http://192.168.0.98:11091");
        if (!ObjectUtils.isEmpty(serverName) && Validator.isIpv4(serverName)) {
            String str = UrlBuilder.ofHttp(serverName).setPort(serverPort > 0 ? serverPort : 11078).addPath(download).build();
            String decodeStr = URLDecoder.decode(str, Charset.defaultCharset());
            productVersionInfo.setDownloadUrl(decodeStr);

        } else {
            String str = UrlBuilder.of(domain.trim()).addPath(download).build();
            String decodeStr = URLDecoder.decode(str, Charset.defaultCharset());
            productVersionInfo.setDownloadUrl(decodeStr);
        }

        /*        productVersionInfo.setDownloadUrl(download);*/
        log.info("downurl:" + productVersionInfo.getDownloadUrl());
    }


    public static void main(String[] args) throws Exception {

        UrlBuilder testPath = UrlBuilder.of().setScheme("https").setHost("10.12.185.213").setPort(31078).addPath("test/a");

        System.out.println(testPath.build());


        String domain = "http://10.12.185.213:11078";

        UrlBuilder urlBuilder = UrlBuilder.ofHttp(domain).addPath("test");

        System.out.println(urlBuilder.build());

        String str = "http://10.12.185.213:11078/homeDeviceUrl%2Fdsj%2F1920x1080/";

        System.out.println(str);

        String decode = URLDecoder.decode(str, Charset.defaultCharset());
        System.out.println(decode);

        str = "/file/fileupload/1675836231156.zip";

        System.out.println(FileUtil.getPrefix(str));
        System.out.println(FileUtil.mainName(str));
        System.out.println(FileUtil.getName(str));
        String replace = StrUtil.replace(str, FileUtil.getName(str), "");
        System.out.println(replace);

        //FileUtil.getName()


        //URL url = URLUtil.url(domain);

        // System.out.println(StrUtil.removeAllLineBreaks(domain));

/*        String content="OTFENjJBODBBRjFFNDNERDVGMDVGNkY3RTg1MEVDNDIxQUNFNTRCRDhDQTM2QjNGM0MwNEUyNERGOTg3NzVCNjRDRkU1MDg0NjU0QjU1ODgzRTg2OUM4MUJGRTE3ODQzRjJFQkMwNjdEMTRCRTdCQ0RDRENBNDFEQkJEMzQyRThGMzUzOTQ3MjVFRjE5RDUzOTlBMTAxQkM0MzZDRTY4M0Y0Mzg5ODZGM0Y3NUZGMTNEMEQyRDMwMzYzREE4OTBCNEVFM0EwQ0IzNjk3RkNDNTY5NDhENEVGNkE4RUU1QzE5QTg3QzAzMTM4MUE5REQ3RjRCQkQ3RjZDQjhDQUM1RkFENTZCNDZGMjhGQ0Q0MkY3MzI5MUM0MDk5QkUxNDkzRTcwRTQ5NzY1OTZDOURENzJBMzQyQjNENjQ2Q0EyNTkwMDk0QkNENTEyNzNBMzM3NkMwNUJDM0VBQTU3OThDNjk5RDQ0ODMyRTE3RTI1NzdGMDBGN0FENzlDMkYwRkVFMDQwNzIzQzM1NDdGREUxMzQzNjlDMzUzNEU0MkNDRkIwMTY3ODUxRTk1ODQ4RTU1MzU0NDZFQUY4M0NGMEY2QzlEMEFERjU1M0M0QTFGOEI2N0IxQzk0RkQ3Q0VCRjVBRTdCRDlBREFCQzZCNDgyMkFGMTk5REY2QUQwNUIwNUZGMDdENjY4RjlCOTUxMUU2RDhDQzA5NTVCNkM5NDk0ODNGN0NDQUEwQzA5NDRGOTcyMkE0Q0MyRTY2RUQ1QjI3NDY2N0VEMkZEN0I2ODY0NjYzMTA2N0I4MERDMTc1MkY4OTk4QTEyOTk4RENDM0NEQUNFMUFFNjkxOUExRUJDRUM4RjYyNDkxNTBFMTBCNDE4RkNCOUEzODEwMkJCQkY4QkUzNzRCRjU3NkZERDE2OEExMTg4QjUxNDREMkUxOTRGNkEzREM0OUM0N0RCQzkzMkMzNkRGMUQ1QTU0MTBBNTE3MTA1QzMwMTk3MENDMEZDREI5MzJEMjlEOTZGMzgyQkU1Q0UwOTQxOURGQ0YyRTFDMzUxRUIyQTk5REY3QTRGMkY2NDYzODU0M0Q4Q0I1RkFENkRFMkVFREI5QzQ3REJCMjlCRUJBQ0RCN0ZCOTAxOTJGRTQwMDRFNTgzQzcyMjVBMEMxQzJFRUU2MTM4M0QyQTM4OTRFNTFERkNFQjk1QTNDRTdERTNEQUU0MTc0RTJDOTcyMDBBRDY0Rjg3REFFOTg5NTk1REFDRjhGMjcyNUUxMzM3MkY0NkNCRDQ3NjVEMjEyNzM3OEZDQ0M0OEFBMzlCMDhDRjk5QTlDQjkyQzZDRjFFMkFDMDE2OENERTA3MUE0OEE0QTVCNEYyRDg4NEIzMDgxQ0M3MjkxQ0M1RjkxRUFFNEMyMTgxQjhBMUQ1MjJGNDJDNEIxQzcxNTlFQjIyQTNBQ0VEQzkwRDVCNEY4RkQ0MzU2NDU1M0I1MTBDQzRCNEY3QkNCNjJEOUZBRkM3MjI5OTFERDBCQjgwRjgxRTE1MjQ2RDVCRjE0Q0RENzFGNTk1MzQ3MjUyNjMxMDlBQTJEREI1MkEzRDZBMTY0MUJFOEMxM0Q2NTE1OTNDMTIxMzk4QjIxNTZGMTFGMEQ0NjI4MzlEMEUxREI0NzgwMDkxNzg4RTU4NzlDRTRBMjhDMEVDOTAwQjhBMDg0RUREQ0RFNTE0OEI5MTQzOEM4Qjc0NkQ2N0Q0MDU1MEQ4OENENTU4NjQ1N0NBQjE1RTNEM0RCQTE3M0EyNjU4QTlFNTc4RUVCMkU2NEI3Nzc4MTU5Nzk1OUY2QjY1MjlFRjI5M0QzQjBEQjNCRDg5N0NEQzkxNEU5OTZCNjFCMzE5MEZCNDZDQzdCOTA1RTBGM0M5OTBFOTE2MkI3OTY5NzBDMjMxRDI5MjNFNDYzODdFOEE2QkREOThBRDlBOUIzMzNFMTgxMzBCMERCRkRFREY3NjUxNjQxODQ4MkEwQkVENTlEOEM2ODlFNkMzM0UxQkJDMzgwNzFCQkQzQUQ1MzdDOUQ0QTEzRTAwQzYxRUY0QjAwRTkzQUJCNjc5NUJCNDEyNzA5MjVCNEI5NzdCNzg4NzVCNERBMDNDRkM5NDc5NjRGNDI4RUYwRTdCN0EzNEQ1MjgwRTczM0I2N0M4MjQwQjQ4NDdEQzgzOUQ2RURDMDZENDg2OTMyNjgxNzJBRkVERERBRjI2RjY4MzI3RTQ1QzExQzU5NDEzQjc0Q0FDMDM0NDMwRUU4MEQ5RUYyQThBMTYyRjM5RTZDNjc2MjIxNUU3QUU1NTlFREFCODc3M0M4N0JFNDI2MkE2RjkxQUY4NjYwQ0Y0MjNBNjM1MjFDMUQ5RjNCRUJEMkQ0MDdCNzNBRTYwRENGNDY2NDY4Mjk5MDc4NkEyRUU5MkQ3Mjc3N0YyREVFOEY1NzNBQzFBMjI2MjA3RTNEQjYzMzc5MjI2ODUwQ0Y5MjU3QjIzNDEzQTQ5OEYxMEQ2MjI1OTc0QjUyQUU1QzcyQjg1Qjg0Qjg1QUJFNkExRjlEMTYzMUEyRTNCMUQ4MDg4QzMxNzQyREQyRUU5NzA3QzRGMzY0RDlCNzIwRkVFM0Q5QTU5NjAyQUNBQzVCMjBGREQ2Q0ZCQUUzOUZCM0U2MTQyOQ==";

        String decrypt = EncryptUtil.decrypt(content, ENCRYPT_STR);

        System.out.println(decrypt);*/

        //String content = EncryptUtil.myEnscrt("", 9, DES_STR, ENCRYPT_STR);


        //System.out.println(content);


/*        String decrypt = EncryptUtil.decrypt("W10=", ENCRYPT_STR);

        System.out.println(decrypt);*/


        System.out.println(new String(Base64.decode("W10=")));

    }

}
