@echo off
chcp 65001 >nul
title 订单日报系统 - Windows服务管理

cd /d "%~dp0"

REM ============================================
REM  使用 NSSM 将程序注册为 Windows 服务
REM  需要先下载 nssm.exe 放到当前目录
REM  下载地址: https://nssm.cc/download
REM ============================================

set SERVICE_NAME=DailyReportSystem
set SERVICE_DESC=订单日报系统服务
set NSSM_EXE=nssm.exe

if not exist "%NSSM_EXE%" (
    echo [错误] 未找到 %NSSM_EXE%
    echo.
    echo 请先下载 NSSM:
    echo   1. 访问 https://nssm.cc/download
    echo   2. 下载 Win64 版本
    echo   3. 解压后将 nssm.exe 放到当前目录
    echo.
    pause
    exit /b 1
)

REM 检查虚拟环境
set "PYTHON_PATH="
if exist ".venv\Scripts\python.exe" (
    set "PYTHON_PATH=%cd%\.venv\Scripts\python.exe"
) else (
    for /f "delims=" %%i in ('where python 2^>nul') do (
        if not defined PYTHON_PATH set "PYTHON_PATH=%%i"
    )
    if not defined PYTHON_PATH (
        echo [错误] 未找到 Python，请先安装 Python 或创建虚拟环境
        pause
        exit /b 1
    )
)

echo ========================================
echo   订单日报系统 - Windows服务管理
echo ========================================
echo.
echo 服务名称: %SERVICE_NAME%
echo Python路径: %PYTHON_PATH%
echo 工作目录: %cd%
echo.
echo 请选择操作:
echo   1. 安装服务
echo   2. 启动服务
echo   3. 停止服务
echo   4. 重启服务
echo   5. 删除服务
echo   6. 查看服务状态
echo   0. 退出
echo.
set /p choice=请输入选项: 

if "%choice%"=="1" goto install
if "%choice%"=="2" goto start
if "%choice%"=="3" goto stop
if "%choice%"=="4" goto restart
if "%choice%"=="5" goto remove
if "%choice%"=="6" goto status
if "%choice%"=="0" goto end

:install
echo.
echo [信息] 正在安装服务...
%NSSM_EXE% install %SERVICE_NAME% "%PYTHON_PATH%" "%cd%\run_prod.py"
%NSSM_EXE% set %SERVICE_NAME% AppDirectory "%cd%"
%NSSM_EXE% set %SERVICE_NAME% DisplayName "%SERVICE_DESC%"
%NSSM_EXE% set %SERVICE_NAME% Description "订单日报系统 - 自动生成充电订单日报报表"
%NSSM_EXE% set %SERVICE_NAME% Start SERVICE_AUTO_START
%NSSM_EXE% set %SERVICE_NAME% AppStdout "%cd%\logs\service_stdout.log"
%NSSM_EXE% set %SERVICE_NAME% AppStderr "%cd%\logs\service_stderr.log"
%NSSM_EXE% set %SERVICE_NAME% AppRotateFiles 1
%NSSM_EXE% set %SERVICE_NAME% AppRotateOnline 1
%NSSM_EXE% set %SERVICE_NAME% AppRotateBytes 10485760
echo [信息] 服务安装完成！
goto end

:start
echo.
echo [信息] 正在启动服务...
net start %SERVICE_NAME%
goto end

:stop
echo.
echo [信息] 正在停止服务...
net stop %SERVICE_NAME%
goto end

:restart
echo.
echo [信息] 正在重启服务...
net stop %SERVICE_NAME%
timeout /t 3 /nobreak >nul
net start %SERVICE_NAME%
goto end

:remove
echo.
echo [警告] 即将删除服务 %SERVICE_NAME%
set /p confirm=确认删除吗？(y/n): 
if /i not "%confirm%"=="y" goto end
echo [信息] 正在停止服务...
net stop %SERVICE_NAME% 2>nul
echo [信息] 正在删除服务...
%NSSM_EXE% remove %SERVICE_NAME% confirm
echo [信息] 服务已删除！
goto end

:status
echo.
echo [信息] 服务状态:
sc query %SERVICE_NAME%
goto end

:end
echo.
pause
