<template>
  <div class="score-table-container">
    <!-- 表头 -->
    <div class="table-header">
      <div class="table-header-item">比较数值1</div>
      <div class="table-header-item">符号</div>
      <div class="table-header-item">比较数值2</div>
      <div class="table-header-item">分数</div>
      <div class="table-header-item">备注</div>
      <div class="table-header-item">操作</div>
    </div>

    <!-- 表格内容 -->
    <div class="table-body">
      <div v-for="(row, index) in tableData" :key="index" class="table-row">
        <!-- 数值1 -->
        <el-input :disabled="row.isDisabled" v-model="row.compareNum1" placeholder="请输入..." class="table-cell-input">
          <template #append>{{ test(props.title) }}</template>
        </el-input>

        <!-- 符号1 -->
        <el-select :disabled="row.isDisabled" v-model="row.symbol" class="table-cell-select">
          <el-option label="=" value="="></el-option>
          <el-option label="≤" value="≤"></el-option>
          <el-option label="<" value="<"></el-option>
          <el-option label="≥" value="≥"></el-option>
          <el-option label=">" value=">"></el-option>
        </el-select>

        <!-- 数值2 -->
        <el-input :disabled="row.isDisabled" v-model="row.compareNum2" class="table-cell-input">
          <template #append>{{ test(props.title) }}</template>
        </el-input>

        <!-- 分数 -->
        <el-input :disabled="row.isDisabled" v-model="row.score" class="table-cell-input" />
        <el-input :disabled="row.isDisabled" v-model="row.remark" class="table-cell-input" />

        <!-- 操作按钮 -->
        <div class="table-cell-action">
          <el-button
            icon="Edit"
            size="small"
            circle
            v-if="row.isDisabled"
            @click="handleEdit(row)"
            class="action-btn edit-btn"
          />

          <el-button
            icon="CircleCheck"
            size="small"
            title="保存"
            circle
            v-if="!row.isDisabled"
            @click="handleSave(row)"
            class="action-btn edit-btn"
          />

          <!-- 最后一行显示添加按钮 -->
          <el-button
            v-if="index === tableData.length - 1"
            icon="Plus"
            size="small"
            circle
            @click="handleAdd"
            class="action-btn add-btn"
          />

          <el-button
            icon="Delete"
            size="small"
            circle
            @click="handleDelete(row, index)"
            class="action-btn del-btn"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { getIndicatorByParentId, deleteIndicator, addIndicator, updateIndicator } from "@/api/evaluate/indicator";

const props = defineProps({
  title: {
    type: String,
    default: "唤醒时间"
  },
  indicatorId: {
    type: Number,
    default: 0
  }
});

// 初始化表格数据
const tableData = ref([]);

// 编辑行
const handleEdit = (row) => {
  row.isDisabled = false
};

const handleSave = (row) => {
  if (row.id) {
    updateIndicator({
      id: row.id,
      compareNum1: row.compareNum1,
      name: props.title,
      symbol: row.symbol,
      compareNum2: row.compareNum2,
      score: row.score,
      remark: row.remark,
      parentId: props.indicatorId
    }).then(res => {
      if (res.code === 200) {
        ElMessage.success("保存成功");
        row.isDisabled = true
      } else {
        ElMessage.error(res.message || "保存失败");
      }
    })
  } else {
    addIndicator({
      compareNum1: row.compareNum1,
      symbol: row.symbol,
      name: props.title,
      level: 4,
      compareNum2: row.compareNum2,
      score: row.score,
      remark: row.remark,
      parentId: props.indicatorId,
      type: 0
    }).then(res => {
      if (res.code === 200) {
        ElMessage.success("保存成功");
        row.id = res.data.id; // 假设返回的新ID在res.data.id中
        row.isDisabled = true
      } else {
        ElMessage.error(res.message || "保存失败");
      }
    })
  }
};

// 添加新行
const handleAdd = () => {
  tableData.value.push({
    id: null,
    compareNum1: "",
    symbol: "≤",
    compareNum2: "",
    score: "",
    remark: "",
    isDisabled: false
  });
};

// 删除行
const handleDelete = (row, index) => {
  if (tableData.value.length <= 1) {
    ElMessage.warning("至少保留一行数据");
    return;
  }
  if (row.id) {
    deleteIndicator(row.id).then(res => {
      if (res.code === 200) {
        ElMessage.success("删除成功");
        tableData.value.splice(index, 1);
      } else {
        ElMessage.error(res.message || "删除失败");
      }
    });
    return;
  } else {
    tableData.value.splice(index, 1);
  }
};

const getIndicatorByParentIdData = async (parentId) => {
  try {
    const res = await getIndicatorByParentId(parentId, 0);
      if (res.code === 200) {
        tableData.value = res.data;

        tableData.value.forEach(row => {
          row.isDisabled = true; // 默认不可编辑
        });

        if (tableData.value.length === 0) {
          // 如果没有数据，初始化一行空数据
          handleAdd();
        }
      }
  } catch (error) {
    console.error("获取指标数据失败:", error);
  }
};

const test = (title) => {
  if (title.includes("时间") || title.includes("时长")) {
    return "ms";
  } else if (title.includes("率")) {
    return "%";
  } else if (title.includes("频度")) {
    return "次/h";
  } else if (title.includes("距离")) {
    return "mm";
  } else if (title.includes("数量")) {
    return "个";
  } else {
    return "";
  }
};

onMounted(() => {
  getIndicatorByParentIdData(props.indicatorId);
});
</script>

<style lang="scss" scoped>
// 全局变量（可抽离到单独的scss文件引入）
$table-border-color: #e5e7eb;
$table-header-bg: #f9fafb;
$table-row-hover-bg: #f5f7fa;
$gap-base: 0.5rem;
$padding-base: 1rem;
$text-sm: 0.875rem;
$font-medium: 500;

// 主容器
.score-table-container {
  border: 1px solid $table-border-color;
  border-radius: 4px;
  overflow: hidden; // 防止圆角溢出

  // 表头样式
  .table-header {
    display: grid;
    grid-template-columns: repeat(6, minmax(0, 1fr));
    gap: $gap-base;
    padding: $gap-base $padding-base;
    background-color: $table-header-bg;
    border-bottom: 1px solid $table-border-color;

    .table-header-item {
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: $text-sm;
      font-weight: $font-medium;
      color: #333;
    }
  }

  // 表体样式
  .table-body {
    .table-row {
      display: grid;
      grid-template-columns: repeat(6, minmax(0, 1fr));
      gap: $gap-base;
      padding: $gap-base * 1.5 $padding-base;
      border-bottom: 1px solid $table-border-color;
      align-items: center;

      // 行hover效果
      &:hover {
        background-color: $table-row-hover-bg;
        transition: background-color 0.2s ease;
      }

      // 最后一行去掉底边框
      &:last-child {
        border-bottom: none;
      }

      // 输入框样式
      .table-cell-input {
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
      }

      // 下拉框样式
      .table-cell-select {
        height: 32px;
        width: 100%;
      }

      // 操作列样式
      .table-cell-action {
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        display: flex;
        align-items: center;
        gap: $gap-base;

        .action-btn {
          transition: all 0.2s ease;

          &:hover {
            transform: scale(1.05);
          }
        }

        .edit-btn {
          color: #409eff;

          &:hover {
            background-color: #ecf5ff;
          }
        }

        .add-btn {
          color: #67c23a;

          &:hover {
            background-color: #f0f9eb;
          }
        }

        .del-btn {
          color: #f56c6c;

          &:hover {
            background-color: #fef0f0;
          }
        }
      }
    }
  }
}
</style>
