package com.ruoyi.file.controller;

import com.ruoyi.file.domain.FileUpdateInfo;
import com.ruoyi.file.domain.FileWithId;
import com.ruoyi.file.service.FileUpdateInfoService;
import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.bean.CommonPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/update")
public class FileUpdateInfoController {

    @Autowired
    private FileUpdateInfoService fileUpdateInfoService;

    //增加服务信息
    @PostMapping("/add")
    public ApiResult<String> addFileToDatabase(@RequestBody FileUpdateInfo fileUpdateInfo) {
        try {
            fileUpdateInfoService.addFileToDatabase(fileUpdateInfo);
            return ApiResult.success("文件信息录入成功");
        } catch (Exception e) {
            return ApiResult.error("文件信息录入失败: " + e.getMessage());
        }
    }

    //检查服务版本
    @PostMapping("/checkById")
    public ApiResult<String> checkFileUpdate(@RequestParam Long id) {
        try {
            boolean isUpdateRequired = fileUpdateInfoService.checkFileUpdate(id);
            String result = isUpdateRequired ? "待更新" : "无需更新";
            return ApiResult.success(result);
        } catch (Exception e) {
            return ApiResult.error("检查文件更新失败：远程仓库未找到对应服务");
        }
    }

    //下载更新服务
    @PostMapping("/reloadById")
    public ApiResult<String> performFileUpdate(@RequestParam Long id) {
        try {
            fileUpdateInfoService.performFileUpdate(id);
            return ApiResult.success("文件更新成功");
        } catch (Exception e) {
            return ApiResult.error("文件更新失败，" + e.getMessage());
        }
    }

    //查询服务信息
    @GetMapping("/query")
    public ApiResult<CommonPage<FileUpdateInfo>> queryFiles(
            @RequestParam(required = false) String fileName,
            @RequestParam(required = false, defaultValue = "1") int current,
            @RequestParam(required = false, defaultValue = "10") int size) {
        try {
            CommonPage<FileUpdateInfo> commonPage;
            if (fileName == null || fileName.trim().isEmpty()) {
                commonPage = fileUpdateInfoService.getAllFiles(current, size);
            } else {
                commonPage = fileUpdateInfoService.getFilesByFileNameContaining(fileName, current, size);
            }
            return ApiResult.success(commonPage);
        } catch (Exception e) {
            return ApiResult.error("查询文件信息失败: " + e.getMessage());
        }
    }

    //删除服务信息
    @DeleteMapping("/deleteById")
    public ApiResult<String> deleteFileById(@RequestParam Long id) {
        try {
            fileUpdateInfoService.deleteFileById(id);
            return ApiResult.success("文件信息删除成功");
        } catch (Exception e) {
            return ApiResult.error("删除文件信息失败: " + e.getMessage());
        }
    }

    //控制服务运行状态（启动start、停止stop、重启restart）
    @PostMapping("/controlById")
    public ApiResult<String> controlServiceById(@RequestParam Long id, @RequestParam String action) {
        try {
            FileUpdateInfo fileUpdateInfo = fileUpdateInfoService.getFileById(id);
            if (fileUpdateInfo == null) {
                return ApiResult.error("未找到对应的文件信息，ID: " + id);
            }
            String fileName = fileUpdateInfo.getFileName();

            // 在控制服务之前，先检测当前服务状态
            int currentStatus = fileUpdateInfoService.getFileStatus(fileName);
            if ((action.equals("start") && currentStatus == 1) || (action.equals("stop") && currentStatus == 2)) {
                return ApiResult.error("服务已经是目标状态，无需重复操作");
            }

            fileUpdateInfoService.controlApplication(fileName, action);

            // 根据 action 返回不同的成功消息
            if ("start".equalsIgnoreCase(action)) {
                return ApiResult.success("启动成功");
            } else if ("stop".equalsIgnoreCase(action)) {
                return ApiResult.success("停止成功");
            } else if ("restart".equalsIgnoreCase(action)) {
                return ApiResult.success("重启成功");
            } else {
                return ApiResult.success(action + "命令已发送");
            }
        } catch (Exception e) {
            return ApiResult.error("控制服务失败: " + e.getMessage());
        }
    }

    // 扫描服务所在目录下的文件
    @GetMapping("/scan")
    public ApiResult<CommonPage<FileWithId>> scanFilesInServiceDir(
            @RequestParam(required = false, defaultValue = "1") int current,
            @RequestParam(required = false, defaultValue = "10") int size) {
        try {
            CommonPage<FileWithId> fileNamesPage = fileUpdateInfoService.scanFilesInServiceDir(current, size);
            return ApiResult.success(fileNamesPage);
        } catch (Exception e) {
            return ApiResult.error("扫描文件失败: " + e.getMessage());
        }
    }
}