<template>
  <!-- 数据集管理 -->
  <el-card class="dataset-container">
    <div class="content-header">
      <div class="header-actions">
        <el-button class="reset-btn" @click="handleClose()">返回</el-button>
      </div>
    </div>

    <div class="table-container">
      <TableModel
        :formLabel="formLabel"
        :showOperation="true"
        :showRightTools="false"
        ref="datasetTableRef"
        :columnsList="columnsList"
        :request-api="datasetVersionListAPI"
        :handleColWidth="180"
        :sendParams="{datasetId : datasetId}"
      >
        <template slot="tableTitle">
          <h3>数据列表</h3>
        </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:version:add']"
            class="action-btn version-add-btn"
            @click="handleExport(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>
  </el-card>
</template>

<script>
import TableModel from '@/components/TableModel2'
import { columnsList, formLabel } from './config'
import { datasetVersionListAPI, delDatasetVersionDataAPI } from '@/api/data/dataset'
import { decryptWithSM4, encryptWithSM4 } from '@/utils/sm'
import {exportImagesAPI} from "@/api/data/labeling";

export default {
  name: 'DatasetVersionList', // 修正组件名，避免冲突
  components: {
    TableModel
  },
  data() {
    return {
      datasetId: this.convertToNumber(decryptWithSM4(this.$route.query.datasetId)),
      searchForm: {
        datasetName: ''
      },
      formLabel,
      columnsList,
      datasetVersionListAPI,
      showDatasetForm: false,
      title: '1111',
      row: {},
      isAdd: '',
      showVersionDialog: false,
      showVersionAddDialog: false,
      currentDatasetId: '',
      currentDatasetVersionId: ''
    }
  },

  // 关键修改1：mounted钩子强制查询（比created更可靠）
  mounted() {
    this.queryVersionList()
    // 监听路由参数变化（如果同页面切换数据集ID）
    this.$watch(
      () => this.$route.query.datasetId,
      () => {
        this.datasetId = this.convertToNumber(decryptWithSM4(this.$route.query.datasetId))
        this.queryVersionList()
      }
    )
  },

  methods: {
    // 封装查询方法，方便复用
    queryVersionList() {
      if (this.datasetId && this.$refs.datasetTableRef) {
        // 强制刷新列表（先清空再查询）
        this.$refs.datasetTableRef.getTableList(true)
      }
    },

    handleClose() {
      const obj = {
        path: "/data/dataset",
      };
      this.$tab.closeOpenPage(obj);
    },

    convertToNumber(value) {
      if (!value || value === '' || value === 'undefined' || value === 'null') {
        return '';
      }
      const num = Number(value);
      return isNaN(num) ? '' : num;
    },

    formatDate(dateStr, format = 'YYYY-MM-DD HH:mm:ss') {
      if (!dateStr) return '-';
      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'
      this.$nextTick(() => {
        this.showDatasetForm = true
      })
    },

    handleCloseDialog() {
      this.showDatasetForm = false
      this.row = {}
      this.isAdd = ''
    },

    handleVersionView(row) {
      this.currentDatasetId = row.datasetId
      this.showVersionDialog = true
    },

    // 关键修改2：新增版本后刷新列表
    handleVersionAdd(row) {
      console.log('rows', row)
      this.currentDatasetId = row.datasetId
      this.currentDatasetVersionId = row.datasetVersionId
      this.$nextTick(() => {
        this.showVersionAddDialog = true
      })
    },

    // 关键修改3：新增版本弹窗关闭后刷新列表
    handleVersionAddClose() {
      this.showVersionAddDialog = false
      this.currentDatasetId = ''
      this.currentDatasetVersionId = ''
      // 新增版本后主动查询
      this.queryVersionList()
    },

    /** 导出操作 */
    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.queryVersionList()
    },

    resetSearch() {
      this.searchForm = {
        datasetName: ''
      }
      this.queryVersionList()
    },

    handleDelete(row) {
      this.$confirm(
        `确定要删除"${row.datasetName}"吗？删除后将无法恢复！`,
        '操作提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true,
          customClass: 'delete-confirm-dialog',
        },
      ).then(() => {
        delDatasetVersionDataAPI({
          datasetVersionId: row.datasetVersionId,
        })
          .then((res) => {
            if (res.code === 200) {
              this.$message.success('删除成功')
              this.queryVersionList() // 删除后刷新
            } 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;
}

// 新增：返回按钮样式（和示例代码保持一致）
.content-header {
  display: flex;
  justify-content: flex-start; // 左对齐
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.reset-btn {
  margin-left: 1550px;
  background: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
  font-weight: 600;
  padding: 12px 24px;
  border-radius: 6px;
  box-shadow: 0px 4px 12px 0px rgba(0, 0, 0, 0.1);
  letter-spacing: 0.5px;
  font-size: 14px;
  transition: all 0.3s ease;

  &:hover {
    background: #f5f7fa;
    border-color: #c0c4cc;
    color: #409EFF;
    box-shadow: 0px 6px 16px 0px rgba(0, 0, 0, 0.15);
    transform: translateY(-1px);
  }
}

// 搜索栏样式：匹配截图布局
.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>
