package org.springblade.modules.system.controller;

import cn.hutool.core.io.FileUtil;
import io.swagger.annotations.Api;
import org.springblade.common.utils.LinuxUtil;
import org.springblade.core.launch.constant.AppConstant;
import org.springblade.core.tool.api.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author pangqijun
 * Date 2022/11/25
 * Description
 */
@RestController
@RequestMapping(AppConstant.APPLICATION_LOG_NAME + "/appErrorLog")
@Api(value = "App错误日志", tags = "接口权限")
public class AppErrorLogController {

	@Value("${apk.logPath}")
	private String logPath;

	@GetMapping("list")
	public R list() {
		List<String> commands = new ArrayList<>();
		commands.add("ls -lht --time-style=\"+%Y-%m-%d %H:%I:%S\" " + logPath);
		List<String> strings = LinuxUtil.executeNewFlow(commands);
		List<Map<String, String>> fileNames = new ArrayList<>();
		strings.forEach(e -> {
			String[] s = e.split(" ");
			if (s.length > 3) {
				Map<String, String> map = new HashMap<>();
				map.put("fileName", s[s.length - 1]);
				map.put("createTime", s[s.length - 3] + " " + s[s.length - 2]);
				fileNames.add(map);
			}
		});
		return R.data(fileNames);
	}

	@GetMapping("view")
	public R view(@RequestParam String fileName) {
		return R.data(FileUtil.readString(logPath + fileName, StandardCharsets.UTF_8));
	}

}
