<template>
    <ap-container>
        <ap-header margin="1111" class="flex-justify-between">
            <div>
                <el-form :inline="true" class="layout-header-form" @submit.native.prevent="searchEvent">
                    <el-form-item label="项目:" class="layout-header-form-item">
                        <el-select ref="selectRef" v-model="selectedFolder" placeholder="请选择项目">
                            <el-option v-for="item in folderList" :key="item.value" :label="item.text" :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
                <el-button type="primary" @click="searchEvent">查询</el-button>
            </div>
            <div>
                <el-button type="danger" @click="showDeleteLog">删除日志</el-button>
            </div>
        </ap-header>
        <ap-container>
            <ap-aside width="350px" margin="0111">
                <ap-aside-tree ref="treeRef" :options.sync="treeOptions">
                <span slot="tree" slot-scope="scope">
                    {{ scope.data.label }}
                </span>
                </ap-aside-tree>
            </ap-aside>
            <ap-main margin="0110">
                <ap-main margin="1110" class="flex-col">
                    <div style="height: 30px;" class="flex-justify-between">
                        <div>
                            <span style="font-weight: bold;">{{ title }}</span>
                        </div>
                        <div>
                            <ap-button type="primary" icon="el-icon-view" :click="loadFile">查看</ap-button>
                            <el-button type="primary" icon="el-icon-download" @click="downloadFile">下载</el-button>
                            <ap-button type="primary" icon="el-icon-bug" :click="readContainerLog">实时日志</ap-button>
                        </div>
                    </div>
                    <div class="ap-split-line"/>
                    <div v-html="fileContent" class="flex-1 file-content">
                    </div>
                </ap-main>

            </ap-main>
        </ap-container>
        <el-dialog title="删除指定日期前的日志" :visible.sync="showDeleteDialogFlag"
                   width="600px">

            <el-date-picker v-model="deleteDate" format="yyyy-MM" value-format="timestamp" type="month" :picker-options='pickerOptions'></el-date-picker>

            <span slot="footer">
                <el-button @click="showDeleteDialogFlag = false">取 消</el-button>
                <el-button type="primary" @click="deleteLog">确 定</el-button>
            </span>
        </el-dialog>
    </ap-container>
</template>

<script>
import {download} from 'ap-util/util/FileServiceUtil'
import {setCurrentCompanyId} from "ap-util/util/LoginUserUtil";

export default {
    name: 'SysLog',
    data() {
        return {
            selectedFolder: "",
            folderList: [],
            showDeleteDialogFlag: false,
            deleteDate: "",
            pickerOptions: {
                disabledDate(time) {
                    // 只能删除三个月前
                    const delDate = new Date();
                    delDate.setMonth(delDate.getMonth() - 3);
                    return time.getTime() > delDate.getTime();
                }
            },
            // ----- 左侧树 -----
            treeOptions: this.getTreeOption(),
            selectNode: "",
            // ----- 右侧 -----
            selectedId: "",
            title: "请选择",
            fileContent: "请选择需要查看的内容",
        }
    },
    mounted() {
        this.loadFolder();
    },
    methods: {
        loadFolder() {
            this.$request({
                url: '/apm/sys/log/getLogFolder',
                method: 'post',
                data: {}
            }).then(response => {
                this.folderList = response.data;
            })
        },
        searchEvent() {
            if (this.selectedFolder == null || this.selectedFolder == "") {
                this.$message.error("请先选择项目");
                return;
            }
            this.$refs.treeRef.reLoadTreeData();
        },
        showDeleteLog() {
            this.showDeleteDialogFlag = true;
        },
        deleteLog() {
            this.$confirm('确定要指定日期前的日志文件！', '提示', {
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$request({
                    url: '/apm/sys/log/deleteLogFolders',
                    method: 'post',
                    data: {
                        deleteDate: this.deleteDate
                    }
                }).then(response => {
                    this.$message.success(response.data)
                })
            });
        },
        // 左侧树：配置
        getTreeOption() {
            let treeOptions = {
                title: "日志文件列表",
                onClick: (data, node, comp) => {
                    this.title = "【" + data.id + "】";
                    this.selectedId = data.id;
                    if (node.isLeaf) {
                        this.fileContent = "点击【查看】，在线预览！<br>点击【下载】，下载日志文件！";
                    }
                },
                defaultExpandAll: false,
                initData: false,
                loadOptions: {
                    url: "/apm/sys/log/getLogFileList",
                    treeKey: {
                        idKey: "id",
                        parentKey: "parentId",
                        childrenKey: "children",
                        label: "id"
                    },
                    data: () => {
                        return {
                            selectedFolder: this.selectedFolder
                        }
                    },
                    success: (response) => {
                    },
                },
            };

            return treeOptions;
        },
        loadFile() {
            if (!this.selectedId.endsWith(".log")) {
                this.$message.error("只能查看[.log]结尾的文件");
                return;
            }
            return new Promise((resolve) => {
                this.$request({
                    url: '/apm/sys/log/getFileContent',
                    method: 'post',
                    data: {
                        fileUrl: this.selectedId
                    }
                }).then(response => {
                    if (response.data.length > 1024 * 1024 * 10) {
                        this.$confirm('文件大小大于10M，建议下载查看！', '提示', {
                            confirmButtonText: '继续预览',
                            cancelButtonText: '取消预览',
                            type: 'warning'
                        }).then(() => {
                            this.fileContent = this.formatFileContent(response.data);
                        })
                    } else {
                        this.fileContent = this.formatFileContent(response.data);
                    }

                }).finally(() => {
                    resolve();
                });
            });
        },
        formatFileContent(content) {
            if (content == null || content.length < 1) {
                return "内容为空";
            }
            return content;
        },
        downloadFile() {
            if (!this.selectedId.endsWith(".log") && !this.selectedId.endsWith(".zip")) {
                this.$message.error("请选择需要下载的文件！");
                return;
            }
            let container = this.selectedFolder.split("/").pop();
            download({
                url: '/apm/sys/log/downloadLog',
                data: {
                    fileUrl: this.selectedId,
                    container: container,
                },
                methods: 'post'
            })
        },
        readContainerLog() {
            if (this.selectedFolder == null || this.selectedFolder == "") {
                this.$message.error("请选择项目")
                return;
            }
            let container = this.selectedFolder.split("/").pop();
            let str = '<div style="font-weight: bold;">容器' + container + '的日志：最新300行</div>';
            return new Promise((resolve) => {
                this.$request({
                    url: '/apm/sys/log/readContainerLog',
                    method: 'post',
                    data: {
                        container: container,
                        line: 300
                    }
                }).then(response => {
                    let res = response.data
                    for (let i = 0; i < res.length; i++) {
                        str += '<div class="ap-ellipse">' + res[i] + '</div>';
                    }
                    this.fileContent = str;
                }).finally(() => {
                    resolve();
                });
            });
        }
    }
}
</script>

<style scoped>
.file-content {
    overflow: auto;
    background-color: #F5F5F5;
    font-size: 12px;
}
</style>
