package com.priusis.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import com.priusis.lib.R;
import com.priusis.util.SysConfigUtil;
import lombok.SneakyThrows;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author yangli
 * @since 2021/09/16
 */
@Validated
@RestController
@RequestMapping(value = "remote_control")
public class RemoteControlController {


    /**
     * 前端定时任务查询远程控制请求，不为空则表示有请求，展示确认弹窗
     */
    @GetMapping(value = "get_control_request")
    public R<String> getControlRequest() throws IOException {
        return R.success(SysConfigUtil.getProperty("control.request"));
    }

    /**
     * 接受远程控制请求
     *
     */
    @GetMapping(value = "accept_request")
    public R<Void> acceptRequest() throws IOException {
        String requestParams = SysConfigUtil.getProperty("control.request");
        SysConfigUtil.saveProperty("control.request", null);
        // todo 根据参数开启VNC

        // todo 从参数里取出控制的时间，单位分钟
        int minute = 30;
        // 定时任务，指定分钟后执行一次
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @SneakyThrows
            @Override
            public void run() {
                // 杀掉VNC进程
                Process process = Runtime.getRuntime().exec("cmd /c tasklist /fo csv | findstr winvnc");
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "GBK"))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        String pid = line.split(",")[1].replace("\"", "");
                        Runtime.getRuntime().exec("cmd /c taskkill /pid " + pid).destroy();
                    }
                    process.destroy();
                }
                timer.cancel();
            }
        }, DateTime.now().offset(DateField.MINUTE, minute));
        return R.success();
    }

    /**
     * 拒绝远程控制请求
     */
    @GetMapping(value = "refuse_request")
    public R<Void> refuseRequest() throws IOException {
        SysConfigUtil.saveProperty("control.request", null);// 直接清除请求参数
        return R.success();
    }
}
