<template>
  <!-- 数据集管理 -->
  <el-card class="dataset-container">
    <div class="table-container">

      <TableModel
        :formLabel="formLabel"
        :showOperation="true"
        :showRightTools="false"
        ref="datasetTableRef"
        :columnsList="columnsList"
        :request-api="datasetListAPI"
        :handleColWidth="280"
      >
        <template slot="tableTitle">
          <h3>数据列表</h3>
        </template>
        <template slot="tableActions">
          <el-button
            @click="handleAdd"
            v-hasPermi="['data:dataset:add']"
            class="add-btn"
          >
            <i class="el-icon-plus"></i> 新建数据集
          </el-button>
        </template>

        <!-- 自定义列：标注进度 -->
        <template slot="annotationProgress" slot-scope="{ data }">
          <span>{{ data.annotationProgress }}</span>
        </template>

        <template slot="createTime" slot-scope="{ data }">
          {{ formatDate(data.createTime) }}
        </template>

        <!-- 操作列 -->
        <template slot="handle" slot-scope="{ data }">
          <el-button
            type="text"
            v-hasPermi="['data:dataset:export']"
            class="action-btn export-btn"
            @click="handleExport(data)"
          >
            导出
          </el-button>
          <el-button
            type="text"
            v-hasPermi="['data:dataset:version:list']"
            class="action-btn version-view-btn"
            @click="handleVersionView(data)"
          >
            版本查看
          </el-button>
          <el-button
            type="text"
            v-hasPermi="['data:dataset:version:add']"
            class="action-btn version-add-btn"
            @click="handleVersionAdd(data)"
          >
            新增版本
          </el-button>
          <el-button
            type="text"
            v-hasPermi="['data:dataset:del']"
            class="action-btn delete-btn"
            @click="handleDelete(data)"
          >
            删除
          </el-button>
        </template>
      </TableModel>
    </div>

    <!-- 新建/修改数据集弹窗 -->
    <DatasetForm
      v-if="showDatasetForm"
      :title="title"
      :visible="showDatasetForm"
      :rowData="row"
      :isAdd="isAdd"
      @closeDialog="handleCloseDialog"
      :width="600"
      @handleQuery="handleQuery"
    />

    <!-- 新增版本弹窗 -->
    <DatasetVersionAdd
      :visible="showVersionAddDialog"
      :datasetVersionId="currentDatasetVersionId"
      :datasetId="currentDatasetId"
      @closeDialog="handleVersionAddClose"
      @refreshList="handleQuery"
    />
  </el-card>
</template>

<script>
import TableModel from '@/components/TableModel2'
import { columnsList, formLabel } from './config'
import { datasetListAPI, delDatasetDataAPI } from '@/api/data/dataset'
import DatasetForm from './components/DatasetForm.vue'
import DatasetVersion from './components/DatasetVersion.vue'
import DatasetVersionAdd from './components/DatasetVersionAdd.vue'
import { encryptWithSM4 } from '@/utils/sm'
import {exportCocoZipAPI, exportVocZipAPI, exportImagesAPI} from "@/api/data/labeling";


export default {
  name: 'Dataset',
  components: {
    TableModel,
    DatasetForm,
    DatasetVersion,
    DatasetVersionAdd
  },
  data() {
    return {
      // 搜索表单
      searchForm: {
        datasetName: ''
      },
      // 表格配置
      formLabel,
      columnsList,
      datasetVersionId: '',
      datasetListAPI,
      // 弹窗控制
      showDatasetForm: false,
      title: '1111',
      row: {},
      isAdd: '', // add/edit标识
      showVersionDialog: false, // 版本查看弹窗
      showVersionAddDialog: false, // 新增版本弹窗
      currentDatasetId: '', // 当前选中的数据集ID
      currentDatasetVersionId: ''
    }
  },

  created() {},

  methods: {
    // 时间格式化工具函数
    formatDate(dateStr, format = 'YYYY-MM-DD HH:mm:ss') {
      if (!dateStr) return '-';
      // 兼容 ISO 格式时间字符串
      const date = new Date(dateStr);
      if (isNaN(date.getTime())) return '-';

      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');

      return format.replace('YYYY', year)
        .replace('MM', month)
        .replace('DD', day)
        .replace('HH', hours)
        .replace('mm', minutes)
        .replace('ss', seconds);
    },

    /** 新增数据集按钮操作 */
    handleAdd() {
      this.title = '新建数据集'
      this.isAdd = 'add'
      // 修复：使用$nextTick确保DOM更新后再显示弹窗
      this.$nextTick(() => {
        this.showDatasetForm = true
      })
    },

    /** 关闭弹窗（新增统一的关闭方法，优化逻辑） */
    handleCloseDialog() {
      this.showDatasetForm = false
      this.row = {}
      this.isAdd = ''
    },

    /** 版本查看操作 */
    handleVersionView(row) {

      // 把数字转为字符串后再加密
      const datasetIdStr = String(row.datasetId);
      console.log('asdasd',datasetIdStr)
      this.$router.push({
        name: 'DatasetVersionList',
        query: {
          datasetId: encryptWithSM4(datasetIdStr), // 传入字符串而非数字
        }
      })
    },

    /** 新增版本操作 */
    handleVersionAdd(row) {
      console.log('rows', row)
      this.currentDatasetId = row.datasetId
      this.currentDatasetVersionId = row.datasetVersionId
      // 重置版本ID和数据集ID后再打开弹窗，避免数据残留
      this.$nextTick(() => {
        this.showVersionAddDialog = true
      })
    },

    /** 新增版本弹窗关闭处理 - 关键修复：清空关联ID */
    handleVersionAddClose() {
      this.showVersionAddDialog = false
      this.currentDatasetId = ''
      this.currentDatasetVersionId = ''
    },

    /** 导出操作 */
    async handleExport(row) {
      const datasetVersionId = row.datasetVersionId
      // 根据选择的格式处理导出
      try {
        let blob, fileName;
        blob = await exportImagesAPI({ datasetVersionId });
        fileName = `数据集图片.zip`;
        // 处理文件下载
        this.downloadFile(blob, fileName);
        this.$message.success('导出成功，正在下载...');
      } catch (error) {
        // 异常处理（兼容blob格式的错误信息）
        console.error('导出失败：', error);
        if (error.response?.data instanceof Blob) {
          const text = await new Response(error.response.data).text();
          const res = JSON.parse(text);
          this.$message.error(res.msg || '导出失败，无可用数据');
        } else {
          this.$message.error(error.msg || '导出失败，请稍后重试');
        }
      }
    },

    downloadFile(blob, fileName) {
      // 创建下载链接
      const url = window.URL.createObjectURL(new Blob([blob]));
      const a = document.createElement('a');
      a.href = url;
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      // 释放URL对象，清理临时标签
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    },

    /* 搜索/刷新列表操作 */
    handleQuery() {
      this.$refs.datasetTableRef.getTableList()
    },

    /** 重置搜索 */
    resetSearch() {
      this.searchForm = {
        datasetName: ''
      }
      this.handleQuery()
    },

    /** 删除操作 */
    handleDelete(row) {
      this.$confirm(
        `确定要删除"${row.datasetName}"吗？删除后将无法恢复！`,
        '操作提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true,
          customClass: 'delete-confirm-dialog',
        },
      ).then(() => {
        delDatasetDataAPI({
          datasetId: row.datasetId,
        })
          .then((res) => {
            if (res.code === 200) {
              this.$message.success('删除成功')
              this.handleQuery()
            } else {
              this.$message.error(res.msg || '删除失败')
            }
          })
          .catch((error) => {
            console.error('删除失败:', error)
          })
      })
    },
  },
}
</script>

<style scoped lang="scss">
// 容器样式：匹配截图的纯白背景
.dataset-container {
  height: calc(100vh - 84px);
  overflow: hidden;
  background: #fff;
  padding: 16px 20px;
}

// 搜索栏样式：匹配截图布局
.search-bar {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  gap: 10px;

  .search-input {
    width: 220px;
    height: 32px;
  }

  .query-btn {
    background: #1f72ea;
    border: none;
    border-radius: 4px;
    width: 60px;
    height: 32px;
  }

  .reset-btn {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    width: 60px;
    height: 32px;
  }
}

::v-deep .table-card {
  height: calc(100vh - 200px) !important;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

// 新建数据集按钮：匹配截图的蓝色按钮样式
.add-btn {
  width: 128px;
  height: 36px;
  background: #1f72ea;
  border-radius: 4px;
  color: #fff;
  border: none;
  font-size: 14px;
  margin-bottom: 10px;

  &:hover {
    background: #4a8bff;
  }
}

// 操作按钮样式：完全匹配截图的颜色和样式
.action-btn {
  margin-right: 5px;
  font-size: 13px;
  padding: 0;
  height: auto;

  &:last-child {
    margin-right: 0;
  }

  // 导出按钮（蓝色）
  &.export-btn {
    color: #1f72ea;
  }

  // 版本查看按钮（浅蓝色）
  &.version-view-btn {
    color: #4e94fd;
  }

  // 新增版本按钮（橙色）
  &.version-add-btn {
    color: #ff9800;
  }

  // 删除按钮（红色）
  &.delete-btn {
    color: #f56c6c;
  }
}
</style>
