<!-- src/views/DataPackage.vue -->
<template>
  <div>
    <el-tabs v-model="activeTab">
      <el-tab-pane label="下载列表" name="package">
        <el-table :data="packageList" style="width: 100%">
          <el-table-column prop="packageName" label="数据包名称"></el-table-column>
          <el-table-column prop="createTime" label="上传时间" :formatter="formatDate"></el-table-column>
          <el-table-column prop="packageSize" label="大小" :formatter="formatSize"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="downloadPackage(scope.row.id)" type="primary" size="small">下载</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            @current-change="handlePackagePageChange"
            :current-page="packagePage.current"
            :page-size="packagePage.size"
            :total="packagePage.total"
            layout="total, prev, pager, next">
        </el-pagination>
      </el-tab-pane>

      <el-tab-pane label="日志列表" name="log">
        <el-table :data="logList" style="width: 100%">
          <el-table-column prop="packageName" label="数据包名称"></el-table-column>
          <el-table-column prop="operationType" label="操作类型"></el-table-column>
          <el-table-column prop="operationTime" label="操作时间" :formatter="formatDate"></el-table-column>
          <el-table-column prop="userName" label="用户名">
            <template slot-scope="scope">
              {{ scope.row.userName || 'admin' }}
            </template>
          </el-table-column>

          <el-table-column prop="userAgent" label="客户端信息">
            <template slot-scope="scope">
              {{ formatUserAgent(scope.row.userAgent) }}
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            @current-change="handleLogPageChange"
            :current-page="logPage.current"
            :page-size="logPage.size"
            :total="logPage.total"
            layout="total, prev, pager, next">
        </el-pagination>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import Vue from 'vue'
import {
  Button,
  ButtonGroup,
  Cascader,
  Col,
  Dialog,
  Divider,
  Dropdown,
  DropdownItem,
  DropdownMenu,
  Form,
  FormItem,
  Input,
  Option,
  RadioGroup,
  Row,
  Select,
  TabPane,
  Tabs,
  Tag,
  Tooltip
} from 'element-ui'
import dataPackageApi from '@/js/api/dataPackageApi';

Vue.use(Select)
Vue.use(Option)
Vue.use(Input)
Vue.use(Row)
Vue.use(Col)
Vue.use(Button)
Vue.use(Dialog)
Vue.use(Form)
Vue.use(FormItem)
Vue.use(Divider)
Vue.use(Cascader)
Vue.use(Dropdown)
Vue.use(DropdownMenu)
Vue.use(DropdownItem)
Vue.use(Tabs)
Vue.use(TabPane)
Vue.use(RadioGroup)
Vue.use(Tag)
Vue.use(ButtonGroup)
Vue.use(Tooltip)
export default {
  data() {
    return {
      activeTab: 'package',
      packageList: [],
      logList: [],
      packagePage: {
        current: 1,
        size: 10,
        total: 0
      },
      logPage: {
        current: 1,
        size: 10,
        total: 0
      }
    };
  },
  created() {
    this.fetchPackageList();
    this.fetchLogList();
  },
  methods: {
    fetchPackageList() {
      dataPackageApi.getPackageList(this.packagePage.current - 1, this.packagePage.size)
          .then(response => {
            this.packageList = response.data.content;
            this.packagePage.total = response.data.totalElements;
          });
    },

    fetchLogList() {
      dataPackageApi.getLogList(this.logPage.current - 1, this.logPage.size)
          .then(response => {
            this.logList = response.data.content;
            this.logPage.total = response.data.totalElements;
          });
    },

    handlePackagePageChange(current) {
      this.packagePage.current = current;
      this.fetchPackageList();
    },

    handleLogPageChange(current) {
      this.logPage.current = current;
      this.fetchLogList();
    },

    downloadPackage(id) {
      dataPackageApi.downloadPackage(id)
          .then(response => {
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            // 假设文件名可以从响应头获取
            const contentDisposition = response.headers['content-disposition'];
            let fileName = 'package.dat';
            if (contentDisposition) {
              const fileNameMatch = contentDisposition.match(/filename="(.+?)"/);
              if (fileNameMatch && fileNameMatch.length === 2) {
                fileName = fileNameMatch[1];
              }
            }
            link.setAttribute('download', fileName);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          });
    },

    formatDate(row, column, cellValue) {
      if (!cellValue) return '';
      const date = new Date(cellValue);
      return date.toLocaleString();
    },

    formatSize(row, column, cellValue) {
      if (!cellValue) return '0 B';
      const units = ['B', 'KB', 'MB', 'GB', 'TB'];
      let size = Number(cellValue);
      let unitIndex = 0;
      while (size >= 1024 && unitIndex < units.length - 1) {
        size /= 1024;
        unitIndex++;
      }
      return `${size.toFixed(2)} ${units[unitIndex]}`;
    },
    formatUserAgent(agent) {
      if (!agent) return '未知';
      // 简化显示，可根据需要调整
      // if (agent.includes('Chrome')) return 'Chrome';
      // if (agent.includes('Firefox')) return 'Firefox';
      // if (agent.includes('Safari')) return 'Safari';
      // if (agent.includes('Edge')) return 'Edge';
      return agent.substring(0, 50) + (agent.length > 50 ? '...' : ''); // 截断过长的UA
    }
  }
};
</script>

<style scoped>
/* 分页居中 */
.el-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 可选：调整分页按钮样式 */
.el-pagination.is-background .btn-next,
.el-pagination.is-background .btn-prev,
.el-pagination.is-background .el-pager li {
  margin: 0 5px;
  border-radius: 4px;
}
</style>