package cn.reghao.autodop.dmaster.sys.controller;

import cn.reghao.autodop.common.util.jvm.JVM;
import cn.reghao.autodop.common.util.jvm.po.JvmInfo;
import cn.reghao.autodop.common.util.jvm.po.JvmStat;
import cn.reghao.jdkutil.result.WebBody;
import cn.reghao.autodop.dmaster.util.UploadDownload;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author reghao
 * @date 2021-04-04 21:24:18
 */
@Api(tags = "用户页面")
@RequestMapping("/sys")
@Controller
public class SysPageController {
    private UploadDownload uploadDownload;
    private JVM jvm;

    public SysPageController(UploadDownload uploadDownload) {
        this.uploadDownload = uploadDownload;
        this.jvm = new JVM();
    }

    @ApiOperation(value = "系统备份还原页面")
    @GetMapping("/bak")
    public String sysBakPage(Model model) {
        return "/sys/bak";
    }

    @ApiOperation(value = "JVM 状态页面")
    @GetMapping("/jvmstatus")
    public String jvmStatusPage(Model model) {
        JvmInfo jvmInfo = jvm.info();
        JvmStat jvmStat = jvm.stat();

        model.addAttribute("jvmInfo", jvmInfo);
        model.addAttribute("jvmStat", jvmStat);
        return "/sys/jvmstatus";
    }

    @ApiOperation(value = "数据备份")
    @GetMapping("/bak/export")
    @ResponseBody
    public void dataBackup(HttpServletResponse response) throws IOException {
        String json = "test data";
        ByteArrayInputStream bytesIn = new ByteArrayInputStream(json.getBytes());
        BufferedInputStream bis = new BufferedInputStream(bytesIn);
        uploadDownload.download("test1", bis, response);
    }

    @ApiOperation(value = "数据还原")
    @PostMapping("/bak/import")
    @ResponseBody
    public String dataRestore(@RequestParam("file") MultipartFile file) throws IOException {
        byte[] bytes = file.getBytes();
        String json = new String(bytes, StandardCharsets.UTF_8);
        return WebBody.success();
    }
}
