<template>
  <div class="model-container">
    <!-- 加载失败提示 -->
    <el-alert
      v-if="errorOccurred"
      :title="`加载数据失败: ${errorMessage}`"
      type="error"
      show-icon
      style="margin-bottom: 5px"
    />

    <!-- 下拉菜单 -->
    <el-dropdown
      @command="handleCommand"
      trigger="click"
      :hide-on-click="true"
      style="margin-bottom: 5px"
    >
      <span class="el-dropdown-link">
        {{ selectedModelTypeLabel
        }}<el-icon class="el-icon--right"><ArrowDown /></el-icon>
      </span>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item
            v-for="type in modelTypes"
            :key="type.value"
            :command="type.value"
            :disabled="selectedModelType === type.value"
          >
            {{ type.label }}
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>

    <el-table
      :data="pagedFilteredRows"
      v-loading="loading"
      style="width: 100%"
      empty-text="暂无相关数据"
      v-if="selectedModelType"
      border
      height="calc(100vh - 300px)"
    >
      <el-table-column prop="id" label="序号" min-width="80" />
      <el-table-column prop="name" label="数据集名称" min-width="200" />
      <el-table-column prop="count" label="数据条数" min-width="100" />
      <el-table-column prop="uploadTime" label="更新时间" min-width="180" />
      <el-table-column label="操作" min-width="100">
        <template #default="scope">
          <el-button size="small" @click="selectRow(scope.row)">选择</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控制 -->
    <div
      class="demo-pagination-block"
      v-if="selectedModelType && filteredRows.length > 0"
      style="text-align: center; margin-top: 20px"
    >
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredRows.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 训练模型按钮 -->
    <div
      v-if="
        selectedModelType &&
        pagedFilteredRows.length > 0 &&
        selectedRows.length > 0
      "
      style="text-align: center; margin-top: 5px"
    >
      <el-button type="success" size="small" @click="trainModel"
        >训练模型</el-button
      >
    </div>

    <!-- 当没有选择任何模型类型时显示提示信息 -->
    <div
      v-if="!selectedModelType && !loading && !errorOccurred"
      style="text-align: center; padding-top: 5px"
    >
      请选择一个模型类型以查看详细信息。
    </div>

    <!-- 当筛选结果为空时显示提示信息 -->
    <div
      v-if="
        selectedModelType &&
        filteredRows.length === 0 &&
        !loading &&
        !errorOccurred
      "
      style="text-align: center; padding-top: 5px"
    >
      没有找到与所选模型类型匹配的数据。
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import { ArrowDown } from "@element-plus/icons-vue";
import { table } from "@/API/menus";

interface Dataset {
  id: any;
  name: string;
  description: string;
  type: string;
  count: number;
  status: string;
  uploadTime: string;
}

const loading = ref(true);
const rows = ref<Dataset[]>([]);
const errorOccurred = ref(false);
const errorMessage = ref("");
const selectedRows = ref<Dataset[]>([]);
const currentPage = ref(1);
const pageSize = ref(10);

const modelTypes = [
  { value: "reduce", label: "降酸模型" },
  { value: "reflux", label: "反酸模型" },
];
const selectedModelType = ref();

// 数据过滤后的结果
const filteredRows = computed(() =>
  selectedModelType.value
    ? rows.value.filter((row) => row.type === selectedModelType.value)
    : []
);

// 分页后的过滤数据
const pagedFilteredRows = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredRows.value.slice(start, end);
});

// 定义 fetchData 方法
const fetchData = async () => {
  try {
    const response = await table({ table: "Datasets" });
    return response.data.rows;
  } catch (error) {
    let errorMessage = "未知错误";
    if (error && typeof error === "object" && "message" in error) {
      errorMessage = (error as { message?: string }).message || errorMessage;
    }
    console.error("Error fetching data:", errorMessage);
    throw new Error(errorMessage); // 重新抛出带有详细信息的新错误
  }
};

// 定义 LoadData 方法
const LoadData = async () => {
  try {
    rows.value = (await fetchData()).map(
      (row: {
        Dataset_ID: any;
        Dataset_name: any;
        Dataset_description: any;
        Dataset_type: any;
        Row_count: any;
        Status: any;
        Uploaded_at: any;
      }) => ({
        id: row.Dataset_ID,
        name: row.Dataset_name,
        description: row.Dataset_description,
        type: row.Dataset_type,
        count: row.Row_count,
        status: row.Status,
        uploadTime: row.Uploaded_at,
      })
    );
  } catch (error) {
    let errorMessageText = "未知错误";
    if (error && typeof error === "object" && "message" in error) {
      errorMessageText = (error as { message?: string }).message || errorMessageText;
    }
    console.error("Error fetching data:", errorMessageText);
    ElMessage.error("数据加载失败：" + errorMessageText);
    errorOccurred.value = true;
    errorMessage.value = errorMessageText; // 修复赋值
  } finally {
    loading.value = false;
  }
};

// 定义 handleCommand 方法
const handleCommand = (newType: string) => {
  selectedModelType.value = newType;
  ElMessage.success(
    `已切换到 ${modelTypes.find((type) => type.value === newType)?.label}`
  );
};

const selectRow = (row: Dataset) => {
  selectedRows.value.push(row);
};

const showMessageDialog = (
  message: string,
  type: "success" | "warning" | "info" | "error"
) => {
  ElMessage({
    message: "提示信息",
    type: "success",
    showClose: false,
  });
};

const trainModel = async () => {
  if (!selectedRows.value.length) {
    showMessageDialog("请先选择一行或多行数据", "warning");
    return;
  }

  const firstSelectedRow = selectedRows.value[0];
  const trainData = {
    model_type: "RandomForest",
    model_name: "ForestModel1",
    model_description: "A random forest model trained on current data.",
    data_type: firstSelectedRow.type,
    dataset_id: firstSelectedRow.id,
  };

  try {
    await axios.post("https://127.0.0.1:5000/train-and-save-model", trainData);
    showMessageDialog("模型训练完成", "success");
    selectedRows.value = [];
  } catch (error) {
    console.error("模型训练失败:", error);
    showMessageDialog("模型训练失败", "error");
  }
};

// 定义 handleCurrentChange 方法
const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
};

// 定义 handleSizeChange 方法
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize;
};

onMounted(() => {
  LoadData();
});

const selectedModelTypeLabel = computed(() => {
  const type = modelTypes.find((t) => t.value === selectedModelType.value);
  return type ? type.label : "请选择数据集进行计算";
});
</script>

<style scoped>
.model-container {
  display: grid;
  gap: 10px; /* 增加元素之间的间隔 */
  padding: 10px; /* 增加整体容器的内边距 */
  background-color: #f9fafb; /* 背景颜色 */
  border-radius: 8px; /* 圆角 */
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); /* 阴影效果 */
}

.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}

/* 移除下拉菜单的边框 */
.el-popper.is-light {
  border: none !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); /* 下拉菜单阴影效果 */
}

.el-table {
  width: 100%;
  margin-top: 10px; /* 调整表格与上方元素的距离 */
  border-radius: 8px; /* 添加圆角 */
}

/* 设置表头背景色 */
:deep( .el-table th) {
  background-color: #61e054 !important; /* 设置你想要的颜色 */
  color: #fff; /* 表头文字颜色 */
}

/* 减少表格单元格的内边距 */
:deep( .el-table td),
:deep( .el-table th) {
  padding: 8px 0;
}

/* 设置奇数行背景色 */
:deep( .el-table__row:nth-child(odd)) {
  background-color: #e4fbe5 !important;
}

/* 禁用项样式 */
:deep( .el-dropdown-menu__item.is-disabled) {
  color: #c0c4cc !important; /* 禁用项文字颜色 */
  cursor: not-allowed !important; /* 禁用项鼠标样式 */
}
</style>
