package com.priusis.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
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<JSONObject> getControlRequest() throws IOException {
        return R.success(JSONUtil.parseObj(SysConfigUtil.getProperty("control.request")));
    }

    /**
     * 接受远程控制请求
     */
    @GetMapping(value = "accept_request")
    public R<Void> acceptRequest() throws IOException {
        String requestParams = SysConfigUtil.getProperty("control.request");
        if (StrUtil.isBlank(requestParams)) return R.error("无远程请求");
        SysConfigUtil.saveProperty("control.request", null);
        JSONObject obj = JSONUtil.parseObj(requestParams);
        String id = obj.getStr("id");
        // 开启VNC Server todo 设置ID
        Runtime.getRuntime().exec("cmd /c C:\\Program Files\\RealVNC\\VNC Server\\vncserver.exe");

        // 从参数里取出控制的时间，单位分钟
        int minute = obj.getInt("time");
        // 定时任务，指定分钟后执行一次
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @SneakyThrows
            @Override
            public void run() {
                // 杀掉VNC Server进程
                Process process = Runtime.getRuntime().exec("cmd /c tasklist /fo csv | findstr vncserver.exe");
                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();
    }
}
