<template>
  <div class="dynamic-table-container">
    <!-- 操作按钮区（新增 + 导入导出 + 自定义头部按钮） -->
    <div
      class="tab-handle"
      v-if="!disabled && (showAddButton || showImportExport)"
    >
      <!-- 新增按钮 -->
      <el-button
        v-if="showAddButton"
        type="primary"
        @click="handleAdd"
        :disabled="disabled"
      >
        {{ addButtonText || "新增" }}
      </el-button>

      <!-- 导入导出功能（直接内置） -->
      <div
        v-if="showImportExport && !disabled"
        class="table-import-export"
        style="margin-left: 12px"
      >
        <!-- 导出按钮 -->
        <el-button
          type="primary"
          @click="handleExport"
          :disabled="!modelValue.length"
          :icon="Download"
        >
          导出
        </el-button>

        <!-- 导入按钮 -->
        <el-upload
          ref="uploadRef"
          class="upload-demo"
          action=""
          :auto-upload="false"
          :on-change="handleImport"
          :show-file-list="false"
          style="margin: 0 12px"
        >
          <template #trigger>
            <el-button type="primary" :icon="Upload"> 导入 </el-button>
          </template>
        </el-upload>
      </div>

      <!-- 顶部自定义按钮插槽（可选） -->
      <slot name="header-actions" />
    </div>

    <!-- 表格主体 -->
    <el-table
      :data="modelValue"
      style="width: 100%"
      empty-text="暂无数据"
      border
      :disabled="disabled"
      :scrollbar-always-on="scrollbarAlwaysOn"
    >
      <!-- 序号列 -->
      <el-table-column type="index" fixed="left" width="60" label="序号" />

      <!-- 动态列 -->
      <el-table-column
        v-for="column in columns"
        :key="column.prop"
        :prop="column.prop"
        :label="column.label"
        :min-width="column.minWidth || 140"
        :align="column.align || 'left'"
      >
        <template #default="scope">
          <!-- 普通输入框 -->
          <el-input
            v-if="column.type === 'input'"
            v-model="scope.row[column.prop]"
            :placeholder="column.placeholder"
            :disabled="disabled"
            :maxlength="column.maxlength"
          />

          <!-- 数字输入框 -->
          <el-input
            v-else-if="column.type === 'number'"
            v-model.number="scope.row[column.prop]"
            type="number"
            :placeholder="column.placeholder"
            :disabled="disabled"
            :precision="column.precision"
            :min="column.min"
            :max="column.max"
          />

          <!-- 文本域 -->
          <el-input
            v-else-if="column.type === 'textarea'"
            v-model="scope.row[column.prop]"
            type="textarea"
            :placeholder="column.placeholder"
            :disabled="disabled"
            :rows="column.rows || 3"
            :maxlength="column.maxlength"
            :show-word-limit="column.showWordLimit || false"
          />

          <!-- 下拉选择框 -->
          <el-select
            v-else-if="column.type === 'select'"
            v-model="scope.row[column.prop]"
            :placeholder="column.placeholder"
            :disabled="disabled"
            :multiple="column.multiple || false"
          >
            <el-option
              v-for="item in selectOptions?.[column.optionKey] || []"
              :key="item.key || item.value"
              :label="item.name || item.label"
              :value="item.key || item.value"
            />
          </el-select>

          <!-- 单选框组 -->
          <el-radio-group
            v-else-if="column.type === 'radio'"
            v-model="scope.row[column.prop]"
            :disabled="disabled"
          >
            <el-radio
              v-for="item in selectOptions?.[column.optionKey] || []"
              :key="item.key || item.value"
              :label="item.key || item.value"
              style="margin-right: 12px"
            >
              {{ item.name || item.label }}
            </el-radio>
          </el-radio-group>

          <!-- 时间选择器 -->
          <el-date-picker
            v-else-if="column.type === 'date' || column.type === 'datetime'"
            v-model="scope.row[column.prop]"
            :type="column.type === 'datetime' ? 'datetime' : 'date'"
            :format="column.format || 'YYYY-MM-DD'"
            :value-format="column.valueFormat || 'YYYY-MM-DD'"
            :placeholder="column.placeholder"
            :disabled="disabled"
            style="width: 100%"
          />

          <!-- 文件上传组件 -->
          <FileUploader
            v-else-if="column.type === 'upload'"
            v-model="scope.row[column.prop]"
            :isInline="true"
            :disabled="disabled"
          />
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column
        label="操作"
        fixed="right"
        :width="operationColumnWidth"
        :min-width="operationColumnMinWidth"
        v-if="
          !disabled &&
          (showDeleteButton || operationButtons.length > 0 || $slots.operations)
        "
      >
        <template #default="scope">
          <!-- 默认删除按钮 -->
          <el-button
            v-if="showDeleteButton"
            link
            type="danger"
            size="small"
            @click="handleDelete(scope.$index)"
            :disabled="disabled"
            class="operation-btn"
          >
            删除
          </el-button>

          <!-- 自定义操作按钮 -->
          <el-button
            v-for="(btn, btnIndex) in operationButtons"
            :key="btnIndex"
            :link="btn.link !== false"
            :type="btn.type || 'primary'"
            :size="btn.size || 'small'"
            @click="handleCustomOperation(btn, scope)"
            :disabled="disabled || btn.disabled"
            class="operation-btn"
          >
            {{ btn.text }}
          </el-button>

          <!-- 操作列自定义插槽 -->
          <slot
            name="operations"
            :row="scope.row"
            :index="scope.$index"
            :disabled="disabled"
          />
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { defineProps, defineEmits, ref } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { Download, Upload } from "@element-plus/icons-vue";
import FileUploader from "@/components/FileUploader/index.vue";
import { getTableFileData, exportTableFile } from "@/common/tableFileHandle";

// 定义Props
const props = defineProps({
  // 核心配置
  modelValue: {
    type: Array,
    required: true,
    default: () => [],
  },
  columns: {
    type: Array,
    required: true,
    default: () => [],
  },
  defaultRow: {
    type: Object,
    required: true,
    default: () => ({}),
  },

  // 基础配置
  addButtonText: {
    type: String,
    default: "新增",
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  selectOptions: {
    type: Object,
    default: () => ({}),
  },
  scrollbarAlwaysOn: {
    type: Boolean,
    default: false,
  },

  // 新增/删除按钮配置
  showAddButton: {
    type: Boolean,
    default: true,
  },
  showDeleteButton: {
    type: Boolean,
    default: true,
  },

  // 导入导出功能配置
  showImportExport: {
    type: Boolean,
    default: false,
  },
  exportName: {
    type: String,
    default: "表格数据",
  },

  // 自定义操作按钮配置
  operationButtons: {
    type: Array,
    default: () => [],
  },
  operationColumnWidth: {
    type: [String, Number],
    default: "auto",
  },
  operationColumnMinWidth: {
    type: [String, Number],
    default: 60,
  },
});

// 定义Emits
const emit = defineEmits([
  "update:modelValue",
  "add",
  "delete",
  "custom-operation",
  "import-success",
]);

// 导入上传组件Ref
const uploadRef = ref(null);

/**
 * 导出数据转换：将select/radio的key值转为文字描述
 * @param {Array} data 原始表格数据
 * @returns {Array} 转换后的导出数据
 */
const convertDataForExport = (data) => {
  if (!data || !data.length) return [];

  return data.map((row) => {
    const newRow = { ...row };
    // 遍历列配置，处理select/radio类型字段
    props.columns.forEach((column) => {
      if (column.type === "select" || column.type === "radio") {
        const prop = column.prop;
        const optionKey = column.optionKey;
        const options = props.selectOptions?.[optionKey] || [];

        if (
          newRow[prop] !== undefined &&
          newRow[prop] !== null &&
          newRow[prop] !== ""
        ) {
          // 处理多选（select multiple）
          if (column.multiple && Array.isArray(newRow[prop])) {
            newRow[prop] = newRow[prop]
              .map((key) => {
                const option = options.find(
                  (item) => (item.key || item.value) === key
                );
                return option ? item.name || item.label : key;
              })
              .join("，"); // 多选用中文逗号分隔
          } else {
            // 单选处理
            const option = options.find(
              (item) => (item.key || item.value) === newRow[prop]
            );
            newRow[prop] = option ? option.name || option.label : newRow[prop];
          }
        }
      }
    });
    return newRow;
  });
};

/**
 * 导入数据转换：将文字描述转回对应的key值
 * @param {Array} data 导入的原始数据
 * @returns {Array} 转换后的表格数据
 */
const convertDataForImport = (data) => {
  if (!data || !data.length) return [];

  return data.map((row) => {
    const newRow = { ...row };
    // 遍历列配置，处理select/radio类型字段
    props.columns.forEach((column) => {
      if (column.type === "select" || column.type === "radio") {
        const prop = column.prop;
        const optionKey = column.optionKey;
        const options = props.selectOptions?.[optionKey] || [];

        if (
          newRow[prop] !== undefined &&
          newRow[prop] !== null &&
          newRow[prop] !== ""
        ) {
          // 处理多选（select multiple）
          if (column.multiple) {
            const textList = newRow[prop]
              .split("，")
              .map((item) => item.trim());
            newRow[prop] = textList.map((text) => {
              const option = options.find(
                (item) => (item.name || item.label) === text
              );
              return option ? option.key || item.value : text;
            });
          } else {
            // 单选处理
            const option = options.find(
              (item) => (item.name || item.label) === newRow[prop]
            );
            newRow[prop] = option ? option.key || option.value : newRow[prop];
          }
        } else {
          // 空值处理为默认空
          newRow[prop] = "";
        }
      }
    });
    return newRow;
  });
};

// 1. 新增行
const handleAdd = () => {
  try {
    const newRow = { ...props.defaultRow };
    const newData = [...props.modelValue, newRow];
    emit("update:modelValue", newData);
    emit("add", newRow);
  } catch (e) {
    console.error("新增行失败:", e);
    ElMessage.error("新增失败，请稍后重试");
  }
};

// 2. 删除行
const handleDelete = (index) => {
  ElMessageBox.confirm("确认删除该项？", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      try {
        const newData = [...props.modelValue];
        newData.splice(index, 1);
        emit("update:modelValue", newData);
        emit("delete", index);
        ElMessage.success("删除成功");
      } catch (e) {
        console.error("删除行失败:", e);
        ElMessage.error("删除失败，请稍后重试");
      }
    })
    .catch(() => {});
};

// 3. 自定义操作按钮点击
const handleCustomOperation = (btn, scope) => {
  if (btn.click) {
    try {
      btn.click(scope.row, scope.$index);
    } catch (e) {
      console.error("自定义按钮点击事件执行失败:", e);
      ElMessage.error("操作执行失败，请稍后重试");
    }
  }
  emit("custom-operation", btn, scope.row, scope.$index);
};

// 4. 导出表格数据（修改：添加数据转换）
const handleExport = () => {
  try {
    // 先转换数据，再导出
    const exportData = convertDataForExport(props.modelValue);
    exportTableFile(exportData, props.columns, "", props.exportName);
    ElMessage.success("导出成功");
  } catch (e) {
    console.error("导出失败:", e);
    ElMessage.error("导出失败，请稍后重试");
  }
};

// 5. 导入表格数据（修改：添加数据转换）
const handleImport = (file) => {
  uploadRef.value?.clearFiles();

  getTableFileData(file, props.columns)
    .then((rawImportData) => {
      const convertedData = convertDataForImport(rawImportData);
      handleImportSuccess(convertedData);
      ElMessage.success(`导入成功，共${convertedData.length}条数据`);
    })
    .catch((e) => {
      console.error("导入失败:", e);
      ElMessage.error("导入失败，请检查文件格式是否正确");
    });
};

// 6. 导入成功后的数据处理
const handleImportSuccess = (importData) => {
  try {
    const newData = [...props.modelValue, ...importData];
    emit("update:modelValue", newData);
    emit("import-success", importData);
  } catch (e) {
    console.error("导入数据合并失败:", e);
    ElMessage.error("导入数据处理失败，请稍后重试");
  }
};
</script>

<style scoped lang="less">
.dynamic-table-container {
  width: 100%;
}

.tab-handle {
  margin-bottom: 10px;
  text-align: left;
  display: flex;
  align-items: center;

  :deep(.el-button) {
    margin-right: 8px;
  }
}

.table-import-export {
  display: inline-flex;
  align-items: center;

  :deep(.el-button) {
    margin-right: 8px;
  }
}

.operation-btn {
  margin-right: 4px;
}

:deep(.el-table) {
  --el-table-header-text-color: #303133;
  --el-table-row-hover-bg-color: #f8f9fa;
}

:deep(.el-upload) {
  width: 100%;
}

:deep(.el-textarea) {
  width: 100%;
}

:deep(.el-date-picker) {
  width: 100%;
}
</style>
