package com.example.sjkbf.controller;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.sjkbf.common.FileManage;
import com.example.sjkbf.config.Configuration.CurrentUserId;
import com.example.sjkbf.entity.*;
import com.example.sjkbf.entity.projectconfig.Project;
import com.example.sjkbf.service.ProjectPerService;
import com.example.sjkbf.service.UserAndServerService;
import com.example.sjkbf.service.UserServerProjectService;
import com.example.sjkbf.service.UserService;
import com.google.common.util.concurrent.RateLimiter;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bozhiqiang
 * @since 2025-04-15
 */
@RestController
@RequestMapping("/rindro")
public class UserController {

    @Autowired
    private ProjectPerService projectPerService;

    @Autowired
    private UserService userService;


    @Autowired
    private UserAndServerService userAndServerService;

    @Autowired
    private UserServerProjectService userServerProjectService;

    @Autowired
    FileManage fileManage;


    //下载插件相关内容
    @PostMapping("/download")
    public ResponseEntity<Object> download(@RequestBody Map<String,String> body) throws Exception {
//        //如果不是通用文件就要先检查
//        if (!body.get("projectName").contains("通用")) {
//            List<UserServerProject> byUserName = userServerProjectService.getByUserName(userName);
//            if (byUserName == null) {
//                // 若服务器没有该插件，返回错误信息的通用结果
//                return new ResponseEntity<>(CommonResult.failed("没有插件授权 无法下载相关内容"), HttpStatus.OK);
//            }
//            for (UserServerProject userServerProject : byUserName) {
//                boolean isExpired = false;
//                if (userServerProject.getProjectName().equals(body.get("projectName"))) {
//                    isExpired =true;
//                }
//                if (!isExpired){
//                    return new ResponseEntity<>(CommonResult.failed("没有插件授权 无法下载相关内容"), HttpStatus.OK);
//                }
//            }
//        }
        String file =  "/root/rindro/download/profile/"+body.get("projectName")+".zip";
        String os = System.getProperty("os.name").toLowerCase();
        if (os.contains("win")) {
            file =  "C:\\Users\\12134\\Desktop\\工作目录\\rindro\\download\\profile\\"+body.get("projectName")+".zip";
        }

        Path baseDir = Paths.get(file).toAbsolutePath().normalize();
        Resource resource = new FileSystemResource(baseDir);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"");

        // 返回包含文件资源的通用结果
        return ResponseEntity.ok()
                .header("Content-Disposition",
                        "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }



    //获得账号信息
    @PostMapping("/getInfo")
    public ResponseEntity<CommonResult<Map<String,Object>>> getInfo(@CurrentUserId String userName) {
        User user = userService.getOne(new QueryWrapper<User>().eq("username", userName));

        Map<String, Object> body = new HashMap<>();
        body.put("userpoints", user.getGold());
        body.put("username", user.getName());
        body.put("useravatar", user.getImg());
        body.put("uservip", "普通会员");
        body.put("usercash", null);

        return ResponseEntity.ok(CommonResult.success(body));
    }

//
//    /**
//     * 获得项目的标题文件
//     * @param colonPath
//     * @return
//     * @throws UnsupportedEncodingException
//     */
//    @RequestMapping("/getimg/{colonPath}")
//    public ResponseEntity<Resource>  getimg(@PathVariable String colonPath) throws UnsupportedEncodingException {
//        String decodedPath = URLDecoder.decode(colonPath, "UTF-8");
//
//        Project byName = projectPerService.getByName(decodedPath);
//        if (byName==null)return null;
//        String imgPath = byName.getImgPath();
//
//        String file =  "/root/rindro/Script/"+imgPath;
//        String os = System.getProperty("os.name").toLowerCase();
//        if (os.contains("win")) {
//            file =  "C:\\Users\\12134\\Desktop\\工作目录\\rindro\\Script\\"+imgPath;
//        }
//
//
//        // 5. 返回文件
//        Resource resource = new FileSystemResource(file);
//        if (!resource.exists()) {
//            return ResponseEntity.notFound().build();
//        }
//
//        return ResponseEntity.ok()
//                .header("Content-Disposition",
//                        "attachment; filename=\"" + resource.getFilename() + "\"")
//                .body(resource);
//    }

    /**
     * 获得项目文件中的图片
     * @param colonPath
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/getimg/{colonPath}/{img}")
    public ResponseEntity<Resource>  getimg2(@PathVariable String colonPath,@PathVariable String img) throws UnsupportedEncodingException {
        String decodedPath = URLDecoder.decode(colonPath, "UTF-8");
        img = URLDecoder.decode(img, "UTF-8");

        Project byName = projectPerService.getByName(decodedPath);

        if (byName==null)return null;
        String imgPath = byName.getImgPath();

        String file =  "/root/rindro/Script/Project/"+imgPath+"/img/"+img+".png";
        String os = System.getProperty("os.name").toLowerCase();
        if (os.contains("win")) {
            file =  "C:\\Users\\12134\\Desktop\\工作目录\\rindro\\Script\\Project\\"+imgPath+"\\img\\"+img+".png";
        }
        // 5. 返回文件
        Resource resource = new FileSystemResource(file);
        if (!resource.exists()) {
            return ResponseEntity.notFound().build();
        }

        return ResponseEntity.ok()
                .header("Content-Disposition",
                        "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }


    /**
     * 获得项目文件中的缩略图（使用Thumbnailator）
     */
    @RequestMapping("/getthumb/{colonPath}/{img}")
    public ResponseEntity<Resource> getThumbnailWithLib(
            @PathVariable String colonPath,
            @PathVariable String img,
            @RequestParam(required = false, defaultValue = "200") int width,
            @RequestParam(required = false, defaultValue = "200") int height)
            throws UnsupportedEncodingException, IOException {

        String decodedPath = URLDecoder.decode(colonPath, "UTF-8");
        img = URLDecoder.decode(img, "UTF-8");

        Project byName = projectPerService.getByName(decodedPath);
        if (byName == null) return ResponseEntity.notFound().build();

        String imgPath = byName.getImgPath();
        String originalFile = "/root/rindro/Script/Project/" + imgPath + "/img/" + img + ".png";
        String os = System.getProperty("os.name").toLowerCase();
        if (os.contains("win")) {
            originalFile = "C:\\Users\\12134\\Desktop\\工作目录\\rindro\\Script\\Project\\" + imgPath + "\\img\\" + img + ".png";
        }

        // 检查原图是否存在
        Resource originalResource = new FileSystemResource(originalFile);
        if (!originalResource.exists()) {
            return ResponseEntity.notFound().build();
        }

        // 使用Thumbnailator生成缩略图
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        Thumbnails.of(originalFile)
                .size(width, height)
                .outputFormat("png")
                .outputQuality(0.8) // 设置输出质量
                .toOutputStream(outputStream);

        byte[] thumbnailBytes = outputStream.toByteArray();
        ByteArrayResource resource = new ByteArrayResource(thumbnailBytes);

        String downloadFileName = img + "_thumb_" + width + "x" + height + ".png";

        return ResponseEntity.ok()
                .header("Content-Type", "image/png")
                .header("Content-Disposition", "attachment; filename=\"" + downloadFileName + "\"")
                .body(resource);
    }


    /**
     * 获得项目文件中的MP4
     * @param colonPath
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/getmp42/{colonPath}/{img}")
    public ResponseEntity<Resource>  getmp4(@PathVariable String colonPath,@PathVariable String img) throws IOException {
        String decodedPath = URLDecoder.decode(colonPath, "UTF-8");
        img = URLDecoder.decode(img, "UTF-8");

        Project byName = projectPerService.getByName(decodedPath);

        if (byName==null)return null;
        String imgPath = byName.getImgPath();

        String file =  "/root/rindro/Script/Project/"+imgPath+"/vid/"+img+".mp4";
        String os = System.getProperty("os.name").toLowerCase();
        if (os.contains("win")) {
            file =  "C:\\Users\\12134\\Desktop\\工作目录\\rindro\\Script\\Project\\"+imgPath+"\\vid\\"+img+".mp4";
        }
        // 5. 返回文件
        Resource resource = new FileSystemResource(file);
        if (!resource.exists()) {
            return ResponseEntity.notFound().build();
        }

        return ResponseEntity.ok()
                .header("Content-Type", "video/mp4")
                // 添加下行强制变为下载行为（与Alist一致）
                .header("Content-Disposition", "attachment; filename=\"" + resource.getFilename() + "\"")
                .header("Accept-Ranges", "bytes")
                .body(resource);
    }


    //购买
    @PostMapping("/buy")
    public ResponseEntity<CommonResult<Object>> buy( @RequestBody Map<String,String> body,@CurrentUserId String userName) throws Exception {


        String buy = userService.buy(body.get("ip"), body.get("projectName"), userName);
        Map<String, Object> result = new HashMap<>();
        result.put("info",buy);
        if (buy.equals("购买成功")){
            UserServerProject byIPAndName = userServerProjectService.getByIPAndName(body.get("ip"), body.get("projectName"));
            DateTime date = DateUtil.date(byIPAndName.getExpirationDate());

            String format = DateUtil.format(date, "yyyy-MM-dd");
            result.put("endTime",format);
            return ResponseEntity.ok(CommonResult.success(result));
        }


        return ResponseEntity.ok(CommonResult.failed(buy));
    }

    //充值
    @GetMapping("/addgold")
    public ResponseEntity<CommonResult<String>> addgold(String userName,Integer gold){
        String addgold = userService.addgold(userName,gold);

        return ResponseEntity.ok(CommonResult.success(addgold));
    }
    //转让
    @PostMapping("/transfer")
    public ResponseEntity<CommonResult<String>> transfer(@RequestBody Map<String,String> body,@CurrentUserId String userName){
        String transfer = userService.transfer(userName,body.get("username"), Integer.valueOf(body.get("gold")));

        return ResponseEntity.ok(CommonResult.success(transfer));
    }


    //给账号添加服务器
    @PostMapping("/addServer")
    public ResponseEntity<CommonResult<String>> addServer(@RequestBody Map<String,String> body,@CurrentUserId String userName){
        String addServer = userService.addServer(body.get("ip"),userName,body.get("username"),body.get("password"),body.get("port"));

        return ResponseEntity.ok(CommonResult.success(addServer));
    }
    //给账号删除服务器
    @PostMapping("/deleteServer")
    public ResponseEntity<CommonResult<String>> deleteServer(@RequestBody Map<String,String> body,@CurrentUserId String userName){
        String deleteServer = userService.deleteServer(body.get("ip"), userName);

        return ResponseEntity.ok(CommonResult.success(deleteServer));
    }
    //获得服务器列表
    @PostMapping("/getServerList")
    public ResponseEntity<CommonResult<List<Map<String,Object>>>> getServerList(@CurrentUserId String userName){
        List<UserAndServer> serverList = userAndServerService.getServerList(userName);
//        List<String> collect = serverList.stream().map(UserAndServer::getServerIp).collect(Collectors.toList());
        List<Map<String, Object> > body = serverList.stream().map(item -> {
            Map<String, Object> map = new HashMap<>();
            map.put("serverIp", item.getServerIp());
            map.put("userName", item.getAccount());
            map.put("password", item.getPassword());
            map.put("port", item.getPort());
            return map;
        }
        ).collect(Collectors.toList());


        return ResponseEntity.ok(CommonResult.success(body));
    }

    //获得服务器信息
    @PostMapping("/getServer")
    public ResponseEntity<CommonResult<UserAndServer>> getServer(@RequestBody Map<String,String> body,@CurrentUserId String userName){

        UserAndServer userAndServer = userAndServerService.getOne(new QueryWrapper<UserAndServer>().eq("user_name", userName).eq("server_ip", body.get("ip")));

        return ResponseEntity.ok(CommonResult.success(userAndServer));
    }

    //获取插件信息
    @PostMapping("/getProjectInfoList")
    public ResponseEntity<CommonResult<Object>> getProjectInfoList(){
        Map<String, Map<String, Object>>  body =  projectPerService.getProjectInfoList();

        return ResponseEntity.ok(CommonResult.success(body));
    }

    /**
     * 获取自己拥有的插件信息
     * @return
     */
    @PostMapping("/getUserProList")
    public ResponseEntity<CommonResult<Object>> getgetUserProList(@RequestBody Map<String,String> body) {
        List<UserServerProject> byUserName = userServerProjectService.getpro(body.get("ip"));
        Map<String, Map<String, Object>> body2 =  projectPerService.getProjectInfoListAll();

        Map<String, Map<String, Object>> re =new HashMap<>();
        for (UserServerProject userServerProject : byUserName) {
            Map<String, Object> objectMap = body2.get(userServerProject.getProjectName());
            DateTime date = DateUtil.date(userServerProject.getExpirationDate());

            String format = DateUtil.format(date, "yyyy-MM-dd");
            objectMap.put("endTime",format);
            objectMap.put("open",userServerProject.getOpen());
            re.put(userServerProject.getProjectName(),objectMap);
        }
        return ResponseEntity.ok(CommonResult.success(re));
    }


    @GetMapping("/download/sh")
    public ResponseEntity<Resource> downloadFileSh() {
        // 构建文件的完整路径
        File file = new File(fileManage.getFile()+"re.sh");

        StaticLog.info("请求下载sh脚本"+file);
        if (!file.exists()) {
            // 如果文件不存在，返回 404 错误
            return ResponseEntity.notFound().build();
        }

        // 创建文件资源对象
        Resource resource = new FileSystemResource(file);

        // 设置响应头，告知浏览器这是一个附件，需要下载
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + "re.sh");

        // 返回响应实体，包含文件资源、响应头和状态码
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }

    @GetMapping("/download/c")
    public ResponseEntity<Resource> downloadFileC() {
        // 构建文件的完整路径
        return getResourceResponseEntity("download/ndpsm_svr", "ndpsm_svr");
    }

    @GetMapping("/download/d")
    public ResponseEntity<Resource> downloadFileD() {
        // 构建文件的完整路径
        return getResourceResponseEntity("download/DPS_Login_Gateway", "DPS_Login_Gateway");
    }


    @GetMapping("/download/djson")
    public ResponseEntity<Resource> downloadFileDjson() {
        return getResourceResponseEntity("download/config.json", "config.json");
    }

    @GetMapping("/download/dsh")
    public ResponseEntity<Resource> downloadFileDsh() {
        return getResourceResponseEntity("download/DpsLoginRestartSh", "DpsLoginRestartSh");
    }
    @GetMapping("/download/ddsh")
    public ResponseEntity<Resource> downloadFileDrsh() {
        return getResourceResponseEntity("download/DpsLoginDownloadSh", "DpsLoginDownloadSh");
    }

    private ResponseEntity<Resource> getResourceResponseEntity(String x, String x1) {
        // 构建文件的完整路径
        File file = new File(fileManage.getFile() + x);
        if (!file.exists()) {
            // 如果文件不存在，返回 404 错误
            return ResponseEntity.notFound().build();
        }

        // 创建文件资源对象
        Resource resource = new FileSystemResource(file);

        // 设置响应头，告知浏览器这是一个附件，需要下载
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + x1);

        // 返回响应实体，包含文件资源、响应头和状态码
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }


    @GetMapping("/download/jdk")
    public ResponseEntity<Resource> downloadFileJdk() {
        // 构建文件的完整路径
        return getResourceResponseEntity("jdk", "ndpsm_svr");
    }

    @Autowired
    private RateLimiter globalRateLimiter;

    @GetMapping("/download/jar")
    public ResponseEntity<Resource> downloadFilejar(HttpServletResponse response) {
        File file = new File(fileManage.getFile()+"download/RT.tar.gz");
        if (!file.exists()) {
            return ResponseEntity.notFound().build();
        }

        try (InputStream inputStream = Files.newInputStream(file.toPath());
             BufferedInputStream bis = new BufferedInputStream(inputStream);
             OutputStream os = response.getOutputStream()) {

            // 设置响应头
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=RT.tar.gz");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setContentLengthLong(file.length());

            byte[] buffer = new byte[1024 * 8]; // 8KB 缓冲区
            int bytesRead;

            // 动态限速：每次读取后根据数据量申请令牌
            while ((bytesRead = bis.read(buffer)) != -1) {
                // 申请令牌（阻塞直到获取足够令牌）
                globalRateLimiter.acquire(bytesRead);
                os.write(buffer, 0, bytesRead);
                os.flush();
            }

        } catch (IOException e) {
            return ResponseEntity.status(500).build();
        }
        return ResponseEntity.ok().build();
    }


    @PostMapping("/download/all")
    public ResponseEntity<Resource> downloadFileall(@RequestBody Map<String,String> body,HttpServletResponse response) {
        String s = body.get("key");

        FileReader fileReader = new FileReader(fileManage.getFilemap());
        String result = fileReader.readString();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        String str = jsonObject.getStr(s);

        File file = new File(str);
        StaticLog.info("请求下载文件"+file);

        if (!file.exists()) {
            return ResponseEntity.notFound().build();
        }

        try (InputStream inputStream = Files.newInputStream(file.toPath());
             BufferedInputStream bis = new BufferedInputStream(inputStream);
             OutputStream os = response.getOutputStream()) {

            // 设置响应头
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=RT.tar.gz");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setContentLengthLong(file.length());

            byte[] buffer = new byte[1024 * 8]; // 8KB 缓冲区
            int bytesRead;

            // 动态限速：每次读取后根据数据量申请令牌
            while ((bytesRead = bis.read(buffer)) != -1) {
                // 申请令牌（阻塞直到获取足够令牌）
                globalRateLimiter.acquire(bytesRead);
                os.write(buffer, 0, bytesRead);
                os.flush();
            }
        } catch (IOException e) {
            return ResponseEntity.status(500).build();
        }
        return ResponseEntity.ok().build();
    }

    @RequestMapping("/download/gr")
    public ResponseEntity<Resource> downloadFilegr(String body,HttpServletResponse response) {

        FileReader fileReader = new FileReader(fileManage.getFilemap());
        String result = fileReader.readString();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        String str = jsonObject.getStr(body);

        File file = new File(str);
        StaticLog.info("请求下载文件"+file);

        if (!file.exists()) {
            return ResponseEntity.notFound().build();
        }

        try (InputStream inputStream = Files.newInputStream(file.toPath());
             BufferedInputStream bis = new BufferedInputStream(inputStream);
             OutputStream os = response.getOutputStream()) {

            // 设置响应头
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+file.getName());
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setContentLengthLong(file.length());

            byte[] buffer = new byte[1024 * 8]; // 8KB 缓冲区
            int bytesRead;

            // 动态限速：每次读取后根据数据量申请令牌
            while ((bytesRead = bis.read(buffer)) != -1) {
                // 申请令牌（阻塞直到获取足够令牌）
                globalRateLimiter.acquire(bytesRead);
                os.write(buffer, 0, bytesRead);
                os.flush();
            }
        } catch (IOException e) {
            return ResponseEntity.status(500).build();
        }
        return ResponseEntity.ok().build();
    }


    @RequestMapping("/getversion")
    public String getversion() {

        FileReader fileReader = new FileReader(fileManage.getFile()+"download/version");
        String result = fileReader.readString();
        return result;
    }

    @GetMapping("/getmp4/{colonPath}/{img}")
    public ResponseEntity<Resource> streamVideo(
            @RequestHeader(value = "Range", required = false) String rangeHeader, @PathVariable String colonPath,@PathVariable String img) {

        try {
            String decodedPath = URLDecoder.decode(colonPath, "UTF-8");
            img = URLDecoder.decode(img, "UTF-8");

            Project byName = projectPerService.getByName(decodedPath);

            if (byName==null)return null;
            String imgPath = byName.getImgPath();

            Path videoPath = Paths.get("/root/rindro/Script/Project/"+imgPath+"/vid/"+img+".mp4");


            String os = System.getProperty("os.name").toLowerCase();
            if (os.contains("win")) {
                videoPath =  Paths.get("C:\\Users\\12134\\Desktop\\工作目录\\rindro\\Script\\Project\\"+imgPath+"\\vid\\"+img+".mp4");
            }

            Resource videoResource = new UrlResource(videoPath.toUri());

            if (!videoResource.exists() || !videoResource.isReadable()) {
                return ResponseEntity.notFound().build();
            }

            long contentLength = videoResource.contentLength();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("video/mp4"));
            headers.set("Accept-Ranges", "bytes");

            if (rangeHeader != null && rangeHeader.startsWith("bytes=")) {
                String[] ranges = rangeHeader.substring(6).split("-");
                long start = Long.parseLong(ranges[0]);
                long end = (ranges.length > 1 && !ranges[1].isEmpty())
                        ? Long.parseLong(ranges[1])
                        : contentLength - 1;
                long rangeLength = end - start + 1;

                if (start >= contentLength || end >= contentLength) {
                    return ResponseEntity.status(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE)
                            .header("Content-Range", "bytes */" + contentLength)
                            .build();
                }

                // 获取输入流并跳过起始字节
                InputStream inputStream = videoResource.getInputStream();
                long skippedBytes = inputStream.skip(start);
                if (skippedBytes != start) {
                    throw new IOException("无法跳过指定字节数");
                }

                headers.set("Content-Range", "bytes " + start + "-" + end + "/" + contentLength);
                headers.setContentLength(rangeLength);

                return ResponseEntity.status(HttpStatus.PARTIAL_CONTENT)
                        .headers(headers)
                        .body(new InputStreamResource(inputStream));
            } else {
                return ResponseEntity.ok()
                        .headers(headers)
                        .body(videoResource);
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    //根据ip获取插件列表
    @PostMapping("/getServerProList")
    public ResponseEntity<CommonResult<List<UserServerProject>>> getServerList(@RequestBody Map<String,String> body, @CurrentUserId String userName){
        if (userAndServerService.selectCount(body.get("ip"),userName)==0){
            return ResponseEntity.ok(CommonResult.success(null));
        }
        List<UserServerProject> ip = userServerProjectService.getpro(body.get("ip"));
        return ResponseEntity.ok(CommonResult.success(ip));
    }

    //设置用户单机用的key值
    @PostMapping("/setKey")
    public ResponseEntity<CommonResult<String>> setKey(@RequestBody Map<String,String> body, @CurrentUserId String userName){

        String s = userService.setKey(userName, body.get("clientkey"), body.get("serverkey"));

        return ResponseEntity.ok(CommonResult.success(s));
    }

    @PostMapping("/setproopen")
    public ResponseEntity<CommonResult<String>> setproOpen(@RequestBody Map<String,String> body, @CurrentUserId String userName){
        String s = userServerProjectService.setproOpen(body.get("ip"), body.get("projectName"), body.get("open"),userName);
        return ResponseEntity.ok(CommonResult.success(s));
    }




}
