<template>
  <div style="background-color: #ececec; padding: 5px;height:90vh;overflow:hidden">
    <a-row :gutter="[6,6]" style="height:100%">
      <a-col :span="leftWidth" style="height:100%">
        <a-card title="服务器配置" :bordered="false" style="height:100%">
          <template #extra> 
            <a-button @click="hideAndShow()">隐藏</a-button>
          </template>
          <a-form
            ref="formRef"
            :model="formState"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-form-item label="服务器日志目录" name="remoteDirectory">
              <a-input v-model:value="formState.remoteDirectory" />
            </a-form-item>
            <a-form-item label="本地存放日志目录" name="localDirectory">
              <a-input v-model:value="formState.localDirectory" />
            </a-form-item>
            <a-form-item label="云服务器HOST" name="host">
              <a-input v-model:value="formState.host" />
            </a-form-item>
            <a-form-item label="服务器帐户" name="user">
              <a-input v-model:value="formState.user" />
            </a-form-item>
            <a-form-item label="帐号密码" name="password">
              <a-input type="password" v-model:value="formState.password" />
            </a-form-item>
          </a-form>
        </a-card>
      </a-col>
      <a-col :span="7" style="height:100%">
        <a-card title="服务器日志文件" :bordered="false" style="height:100%;display:flex;flex-direction:column">
          <template #title>
            服务器日志
          </template>
          <template #extra> 
            <a-button v-if="leftWidth==0" @click="hideAndShow()">显示</a-button>
            <a-button @click="setRemotLogDataEvent">查看</a-button>
            <a-button @click="downloadLogEvent">下载</a-button>
          </template>
          <div style="flex:1;min-height:0">
            <vxe-grid
              v-bind="serverGridOptions"
              :loading="loading"
              :data="serverLogfileList"
            >
              <template #toolbar_buttons>
                <span>共 {{ serverLogfileList.length }} 条记录</span>
              </template>
            </vxe-grid>
          </div>
        </a-card>
      </a-col>
      <a-col :span="7" style="height:100%">
        <a-card title="本地日志文件" :bordered="false" style="height:100%;display:flex;flex-direction:column">
          <template #extra> 
            <a-button @click="setLocalLogDataEvent">查看</a-button>
          </template>
          <div style="flex:1;min-height:0">
            <vxe-grid
              v-bind="localGridOptions"
              :loading="loading2"
              :data="localLogfileList"
            >
              <template #toolbar_buttons>
                <span>共 {{ localLogfileList.length }} 条记录</span>
              </template>
              <template #operate="{ row }">
                <a-button type="link" size="small" @click="logAnalyzerEvent(row)">分析</a-button>
              </template>
            </vxe-grid>
          </div>
        </a-card>
      </a-col>
      <a-col :span="10-leftWidth" style="height:100%">
        <a-card title="分析报告" :bordered="false" style="height:100%;display:flex;flex-direction:column" :loading="loading3">
          <template #default>
            <div style="flex:1;overflow:auto">
              <p v-for="(item,i) in recordList" :key="i">{{ item }}</p>
            </div>
          </template>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, nextTick } from 'vue';
import { VxeGridProps } from 'vxe-table';
import 'vxe-table/lib/style.css';

import { getRemoteLogList, getLocalLogList, downloadRemoteFile, logAnalyzer } from './index.api';

const formState = ref({
  remoteDirectory: '/var/log',
  localDirectory: "D:/log/",
  host: "47.98.203.68",
  user: "root",
  password: "zrch-ABC-bj",
  filename: ''
});

const loading = ref(false);
const loading2 = ref(false);
const loading3 = ref(false);
const labelCol = { span: 8 };
const wrapperCol = { span: 16 };
const serverLogfileList = ref([]);
const localLogfileList = ref([]);
const recordList = ref([]);
const leftWidth = ref(5);

// 计算表格高度
const calculateTableHeight = () => {
  const windowHeight = window.innerHeight;
  const cardHeaderHeight = 57; // 卡片标题栏高度
  const toolbarHeight = 42; // 工具栏高度
  const padding = 20; // 内边距
  return windowHeight - cardHeaderHeight - toolbarHeight - padding - 40;
};

// 服务器日志表格配置
const serverGridOptions = reactive<VxeGridProps>({
  border: true,
  resizable: true,
  showOverflow: true,
  highlightHoverRow: true,
  size: 'mini',
  autoResize: true,
  height: calculateTableHeight(),
  rowConfig: {
    isHover: true,
    height: 40
  },
  columnConfig: {
    resizable: true
  },
  columns: [
    { 
      type: 'seq', 
      width: "20%", 
      title: '序号', 
      fixed: 'left',
      align: 'center'
    },
    { 
      field: 'filename', 
      title: '名称', 
      showOverflow: 'ellipsis',
      sortable: true
    },
    { 
      field: 'size', 
      title: '大小', 
      width: "20%", 
      align: 'center',
      sortable: true,
      formatter: ({ cellValue }) => formatFileSize(cellValue)
    },
  ],
  toolbarConfig: {
    zoom: true,
    custom: true,
    slots: {
      buttons: 'toolbar_buttons'
    }
  }
});

// 本地日志表格配置
const localGridOptions = reactive<VxeGridProps>({
  border: true,
  resizable: true,
  showOverflow: true,
  highlightHoverRow: true,
  size: 'mini',
  autoResize: true,
  height: calculateTableHeight(),
  rowConfig: {
    isHover: true,
    height: 40
  },
  columnConfig: {
    resizable: true
  },
  columns: [
    { 
      type: 'seq', 
      width: "20%", 
      title: '序号', 
      fixed: 'left',
      align: 'center'
    },
    { 
      field: 'filename', 
      title: '名称', 
      showOverflow: 'ellipsis',
      sortable: true
    },
    { 
      field: 'size', 
      title: '大小', 
      width:  "20%", 
      align: 'center',
      sortable: true,
      formatter: ({ cellValue }) => formatFileSize(cellValue)
    },
    { 
      title: '操作', 
      width:  "20%", 
      fixed: 'right',
      align: 'center',
      slots: { default: 'operate' }
    }
  ],
  toolbarConfig: {
    zoom: true,
    custom: true,
    slots: {
      buttons: 'toolbar_buttons'
    }
  }
});

// 响应窗口大小变化
const handleResize = () => {
  serverGridOptions.height = calculateTableHeight();
  localGridOptions.height = calculateTableHeight();
};

async function setRemotLogDataEvent() {
  loading.value = true;
  serverLogfileList.value = await getRemoteLogList(formState.value);
  loading.value = false;
}

async function setLocalLogDataEvent() {
  loading2.value = true;
  localLogfileList.value = await getLocalLogList(formState.value);
  loading2.value = false;
}

async function downloadLogEvent() {
  loading.value = true;
  await downloadRemoteFile(formState.value);
  loading.value = false;
}

async function logAnalyzerEvent(row) {
  formState.value.filename = row.filename;
  loading3.value = true;
  recordList.value = await logAnalyzer(formState.value);
  loading3.value = false;
}

function hideAndShow() {
  leftWidth.value = leftWidth.value ? 0 : 5;
  // 重新计算表格高度
  nextTick(() => {
    handleResize();
  });
}

function formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    
    const k = 1024;
    const sizes = ['B', 'K', 'M', 'G', 'T'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

onMounted(() => {
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize);
  // 初始计算高度
  handleResize();
});
</script>

<style scoped>
/* 自定义 VXE Grid 样式 */
:deep(.vxe-grid) {
  font-size: 12px;
  height: 100% !important;
}

:deep(.vxe-table--render-wrapper) {
  height: 100% !important;
}

:deep(.vxe-table--body) {
  background-color: #fff;
}

:deep(.vxe-table--border-line) {
  border-color: #e8e8e8;
}

:deep(.vxe-table--header-border-line) {
  border-color: #e8e8e8;
}

:deep(.vxe-toolbar) {
  background-color: #f5f5f5;
  padding: 8px 12px;
  border-bottom: 1px solid #e8e8e8;
  margin-bottom: 0;
}

:deep(.vxe-cell--tooltip) {
  max-width: 300px;
  word-break: break-all;
}

/* 确保卡片内容区域充满 */
:deep(.ant-card-body) {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 16px;
}

/* 表格容器样式 */
.table-container {
  flex: 1;
  min-height: 0;
  height: 100%;
}
</style>