<template>
  <div class="table-container">
    <el-table
      v-loading="loading"
      :data="tableData"
      @selection-change="handleSelectionChange"
      :stripe="stripe"
      :border="border"
      :height="height"
      :max-height="maxHeight"
      v-bind="$attrs"
    >
      <!-- 多选列 -->
      <el-table-column
        v-if="selectionMode === 'multiple'"
        type="selection"
        width="55"
        align="center"
      />

      <!-- 单选列 -->
      <el-table-column
        v-if="selectionMode === 'single'"
        width="55"
        align="center"
      >
        <template #default="scope">
          <el-radio
            v-model="selectedRowKey"
            :label="scope.row[rowKey]"
            @change="handleSingleSelection(scope.row)"
          >
            &nbsp;
          </el-radio>
        </template>
      </el-table-column>

      <!-- 序号列 -->
      <el-table-column
        v-if="showIndex"
        label="序号"
        type="index"
        width="80"
        align="center"
      />

      <!-- 动态列 -->
      <template v-for="column in columns" :key="column.prop || column.label">
        <el-table-column
          :label="column.label"
          :prop="column.prop"
          :align="column.align || 'center'"
          :width="column.width"
          :min-width="column.minWidth"
          :fixed="column.fixed"
          :show-overflow-tooltip="column.showOverflowTooltip !== false"
          :type="column.type === 'index' ? 'index' : undefined"
        >
          <template #default="scope">
            <!-- 序号列 - 使用Element Plus默认序号 -->
            <template v-if="column.type === 'index'">
              {{ scope.$index + 1 }}
            </template>

            <!-- 字典标签 -->
            <template v-else-if="column.type === 'dict'">
              <dict-tag
                :options="column.options"
                :value="scope.row[column.prop]"
              />
            </template>

            <!-- 时间格式化 -->
            <template v-else-if="column.type === 'time'">
              <span>{{
                parseTime(
                  scope.row[column.prop],
                  column.format || "{y}-{m}-{d}"
                )
              }}</span>
            </template>

            <!-- 图片 -->
            <template v-else-if="column.type === 'image'">
              <el-image
                :src="scope.row[column.prop]"
                :preview-src-list="
                  column.previewList || [scope.row[column.prop]]
                "
                :style="{
                  width: column.width || '50px',
                  height: column.height || '50px',
                }"
                fit="cover"
                v-if="scope.row[column.prop]"
              />
            </template>

            <!-- 状态标签 -->
            <template v-else-if="column.type === 'status'">
              <el-tag
                :type="getStatusTagType(scope.row, column)"
                :size="column.tagSize || 'default'"
              >
                {{ getStatusText(scope.row, column) }}
              </el-tag>
            </template>

            <!-- 自定义slot -->
            <template v-else-if="column.type === 'slot'">
              <slot
                :name="column.slotName"
                :row="scope.row"
                :column="column"
                :$index="scope.$index"
              />
            </template>

            <!-- 普通文本 -->
            <template v-else>
              <span :class="column.textClass">{{
                scope.row[column.prop]
              }}</span>
            </template>
          </template>
        </el-table-column>
      </template>

      <!-- 操作列 -->
      <el-table-column
        v-if="actions && actions.length > 0"
        label="操作"
        align="center"
        :width="actionWidth"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <template v-for="action in actions" :key="action.key">
            <el-button
              :link="action.link !== false"
              :type="action.type || 'primary'"
              :icon="action.icon"
              :size="action.size || 'small'"
              :disabled="getActionDisabled(scope.row, action)"
              @click="handleAction(action, scope.row)"
              v-hasPermi="action.permission"
            >
              {{ action.label }}
            </el-button>
            <el-divider
              v-if="
                action.showDivider !== false &&
                action !== actions[actions.length - 1]
              "
              direction="vertical"
            />
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-if="showPagination"
      v-show="total > 0"
      :total="total"
      :page="queryParams.pageNum"
      :limit="queryParams.pageSize"
      @pagination="handlePagination"
    />
  </div>
</template>

<script setup name="Table">
import { ref, computed, watch } from "vue";
import { parseTime } from "@/utils/ruoyi";
// import { useDict } from '@/stores/modules/dict' // 不需要，父组件传递
import Pagination from "@/components/Pagination/index.vue";

const props = defineProps({
  // 表格数据
  data: {
    type: Array,
    default: () => [],
  },
  // 表格列配置
  columns: {
    type: Array,
    default: () => [],
  },
  // 操作按钮配置
  actions: {
    type: Array,
    default: () => [],
  },
  // 加载状态
  loading: {
    type: Boolean,
    default: false,
  },
  // 总数
  total: {
    type: Number,
    default: 0,
  },
  // 查询参数
  queryParams: {
    type: Object,
    default: () => ({
      pageNum: 1,
      pageSize: 10,
    }),
  },
  // 是否显示多选
  showSelection: {
    type: Boolean,
    default: false,
  },
  // 是否显示序号
  showIndex: {
    type: Boolean,
    default: false,
  },
  // 是否显示分页
  showPagination: {
    type: Boolean,
    default: true,
  },
  // 表格属性
  stripe: {
    type: Boolean,
    default: true,
  },
  border: {
    type: Boolean,
    default: false,
  },
  height: {
    type: [String, Number],
    default: null,
  },
  maxHeight: {
    type: [String, Number],
    default: null,
  },
  // 操作列宽度
  actionWidth: {
    type: [String, Number],
    default: "auto",
  },
  // 选择模式：'single' | 'multiple' | 'none'
  selectionMode: {
    type: String,
    default: "none",
    validator: (value) => ["single", "multiple", "none"].includes(value),
  },
  // 当前选中的行
  selectedRows: {
    type: Array,
    default: () => [],
  },
  // 选择键字段名
  rowKey: {
    type: String,
    default: "id",
  },
});

const emit = defineEmits(["selection-change", "action", "getList"]);

// 计算属性
const tableData = computed(() => props.data);

// 单选相关
const selectedRowKey = ref(null);

// 监听选中行变化
watch(
  () => props.selectedRows,
  (newRows) => {
    if (props.selectionMode === "single" && newRows.length > 0) {
      selectedRowKey.value = newRows[0][props.rowKey];
    } else if (props.selectionMode === "single" && newRows.length === 0) {
      selectedRowKey.value = null;
    }
  },
  { immediate: true }
);

// 单选处理
const handleSingleSelection = (row) => {
  emit("selection-change", [row]);
};

// 多选处理
const handleSelectionChange = (selection) => {
  emit("selection-change", selection);
};

// 执行操作
const handleAction = (action, row) => {
  emit("action", action, row);
};

// 获取操作按钮禁用状态
const getActionDisabled = (row, action) => {
  if (typeof action.disabled === "function") {
    return action.disabled(row);
  }
  return action.disabled || false;
};

// 获取状态标签类型
const getStatusTagType = (row, column) => {
  if (typeof column.statusType === "function") {
    return column.statusType(row);
  }

  const value = row[column.prop];
  if (column.statusMap) {
    return column.statusMap[value]?.type || "info";
  }

  // 默认状态映射
  const statusMap = {
    0: "info",
    1: "success",
    2: "warning",
    3: "danger",
  };
  return statusMap[value] || "info";
};

// 获取状态文本
const getStatusText = (row, column) => {
  if (typeof column.statusText === "function") {
    return column.statusText(row);
  }

  const value = row[column.prop];
  if (column.statusMap) {
    return column.statusMap[value]?.text || value;
  }

  return value;
};

// 获取列表数据
const getList = () => {
  emit("getList");
};

// 处理分页事件
const handlePagination = (pagination) => {
  // 更新queryParams中的分页参数
  props.queryParams.pageNum = pagination.page;
  props.queryParams.pageSize = pagination.limit;
  // 触发getList事件
  emit("getList");
};
</script>

<style scoped>
.table-container {
  width: 100%;
}

.el-table {
  width: 100%;
}
</style>
