package com.bocloud.ims.booter.controller.config;

import com.alibaba.fastjson.JSONObject;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.LogBean;
import com.bocloud.common.utils.LogCrawler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
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.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/v1")
@Api(value = "服务日志管理", tags = "服务日志管理")
public class LogViewController {

    private static Logger logger = LoggerFactory.getLogger(LogViewController.class);

    /**
     * 获取服务日志的信息
     *
     * @param filepath
     * @param position
     * @param presize
     * @return
     */
    @ApiOperation(tags = {"CMC", "CSC"}, value = "获取服务日志的信息",  httpMethod = "GET")
    @GetMapping("/logview")
    public BocloudResult<LogBean> fetch(@RequestParam(value = "filepath") String filepath,
                                        @RequestParam(value = "position") Long position,
                                        @RequestParam(value = "presize") Long presize) {
        BocloudResult<LogBean> crawlResult = LogCrawler.crawl(filepath, position, presize);
        if (crawlResult.isSuccess()) {
            return new BocloudResult<>(true, JSONObject.toJSONString(crawlResult.getData()));
        }
        return new BocloudResult<>(false, crawlResult.getMessage());
    }

    /**
     * 历史日志打包下载
     *
     * @param filepath
     * @param begin
     * @param end
     * @param server
     * @return
     */
    @ApiOperation(tags = {"CMC", "CSC"}, value = " 历史日志打包下载",  httpMethod = "GET")
    @GetMapping("/logzip")
    public JSONObject zip(@RequestParam(value = "filepath") String filepath,
                          @RequestParam(value = "begin") String begin,
                          @RequestParam(value = "end") String end,
                          @RequestParam(value = "server") String server) {
        List<File> files = new ArrayList<>();
        File file = new File(filepath);
        File[] tempList = file.listFiles();
        if (null != tempList && tempList.length > 0) {
            for (int i = 0; i < tempList.length; i++) {
                if (tempList[i].isFile()) {
                    files.add(tempList[i]);
                }
            }
        }

        List<File> list = new ArrayList<>();
        for (File newFile : files) {
            if (newFile.getName().contains(server)) {
                // 判断文件名长度是否有14位，所需的文件长度都大于14位
                if (newFile.getName().length() < 14) {
                    continue;
                }
                // 截取文件名字中的第4-14个字符 ，拿到日期
                String date = newFile.getName().substring(4, 14);
                if (date.compareTo(begin) >= 0 && date.compareTo(end) <= 0) {
                    list.add(newFile);
                }
            }
        }

        JSONObject dataObj = new JSONObject();
        byte[] data;
        // 遍历文件，将其写入二进制数组
        for (File newFile : list) {
            try (FileInputStream fis = new FileInputStream(newFile);
                 ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fis.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                }
                data = bos.toByteArray();
                dataObj.put(newFile.getName(), data);
            } catch (Exception e) {
                logger.error("Get error message：", e);
            }
        }
        return dataObj;
    }
}
