<template>
  <div class="app-container">
    <!-- 操作按钮区 -->
    <div class="button-group">
      <el-button
        :icon="Plus"
        type="primary"
        @click="openDialog('add')"
        class="custom-button add-button"
        >新增记录</el-button
      >
      <el-button
        :icon="Download"
        type="primary"
        @click="downloadTemplateAction"
        class="custom-button download-button"
        >下载模板</el-button
      >
      <el-button
        :icon="Download"
        type="primary"
        @click="exportDataAction"
        class="custom-button export-button"
        >导出数据</el-button
      >

      <el-upload
        :auto-upload="false"
        :on-change="handleFileSelect"
        accept=".xlsx, .csv"
        class="import-upload"
      >
        <el-button
          :icon="Upload"
          type="primary"
          class="custom-button import-button"
          >导入数据</el-button
        >
      </el-upload>
    </div>

    <!-- 数据表格：仅数字字段NaN显示0，文字字段不处理 -->
    <el-table
      :data="pagedTableDataWithIndex"
      fit
      style="width: 100%"
      @row-click="handleRowClick"
      highlight-current-row
      class="custom-table"
      v-loading="loading"
      table-layout="auto"
    >
      <el-table-column
        key="displayIndex"
        prop="displayIndex"
        label="序号"
        width="80"
        align="center"
      ></el-table-column>
      <el-table-column
        v-for="col in columns.filter((col) => col.key !== 'id')"
        :key="col.key"
        :prop="col.dataKey"
        :label="col.title"
        :min-width="col.title.length * 20 + 40"
        :formatter="formatTableValue"
        align="center"
        header-align="center"
      ></el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template #default="scope">
          <span class="action-buttons">
            <el-tooltip
              class="item"
              effect="dark"
              content="编辑"
              placement="top"
            >
              <el-button
                circle
                :icon="EditPen"
                @click.stop="openDialog('edit', scope.row)"
                class="action-button edit-button"
              ></el-button
            ></el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="删除"
              placement="top"
            >
              <el-button
                circle
                :icon="DeleteFilled"
                @click.stop="deleteItem(scope.row)"
                class="action-button delete-button"
              ></el-button
            ></el-tooltip>
          </span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控制 -->
    <PaginationComponent
      :total="tableData.length"
      :currentPage="currentPage4"
      :pageSize="pageSize4"
      @update:currentPage="currentPage4 = $event"
      @update:pageSize="pageSize4 = $event"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      class="pagination-container"
    />

    <!-- 新增/编辑对话框：优化样式 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="50%"
      :custom-class="['custom-dialog']"
      :close-on-click-modal="false"
      center
    >
      <div class="dialog-header">
        <h2>{{ dialogTitle }}</h2>
        <div class="header-decoration"></div>
      </div>
      <el-form
        ref="formRef"
        :model="formData"
        label-position="top"
        class="custom-dialog-form"
      >
        <el-form-item
          v-for="col in editableColumns"
          :key="col.key"
          :label="col.title"
          class="custom-form-item"
          :rules="[
            {
              required: isTextField(col.dataKey),
              message: `请输入${col.title}`,
              trigger: 'blur',
            },
          ]"
        >
          <el-input
            v-model="formData[col.dataKey]"
            :type="col.inputType || 'text'"
            class="custom-dialog-input"
            :placeholder="`请输入${col.title}`"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" class="custom-cancel-button"
            >取消</el-button
          >
          <el-button
            type="primary"
            @click="submitForm"
            class="custom-submit-button"
            >{{ dialogSubmitButtonText }}</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from "vue";
import {
  DeleteFilled,
  Download,
  Upload,
  Plus,
  EditPen,
} from "@element-plus/icons-vue";
import { ElMessage, ElForm } from "element-plus";
import {
  table,
  updateItem,
  addItem,
  deleteItemApi,
  downloadTemplate,
  exportData,
  importData,
} from "@/API/admin";
import PaginationComponent from "@/components/PaginationComponent.vue";

// 核心：定义字段类型映射（区分文字/数字字段）
const fieldTypeMap: Record<string, "text" | "number"> = {
  longitude: "number",
  latitude: "number",
  company_name: "text",
  company_type: "text",
  county: "text",
  particulate_emission: "number",
};

interface Column {
  key: string;
  dataKey: string;
  title: string;
  width: number;
  inputType?: string;
}

// 表字段定义（与fieldTypeMap对应）
const columns: Column[] = [
  { key: "id", dataKey: "id", title: "ID", width: 80 },
  {
    key: "longitude",
    dataKey: "longitude",
    title: "经度坐标",
    width: 150,
    inputType: "number",
  },
  {
    key: "latitude",
    dataKey: "latitude",
    title: "纬度坐标",
    width: 150,
    inputType: "number",
  },
  {
    key: "company_name",
    dataKey: "company_name",
    title: "企业名称",
    width: 200,
    inputType: "text",
  },
  {
    key: "company_type",
    dataKey: "company_type",
    title: "企业类型",
    width: 150,
    inputType: "text",
  },
  {
    key: "county",
    dataKey: "county",
    title: "所属区县",
    width: 200,
    inputType: "text",
  },
  {
    key: "particulate_emission",
    dataKey: "particulate_emission",
    title: "大气颗粒物排放量（吨/年）",
    width: 150,
    inputType: "number",
  },
];

const editableColumns = columns.filter((col) => col.key !== "id");

// 核心变量：统一表名
const currentTableName = "atmo_company";

// 表格数据相关
const tableData = ref<any[]>([]);
const selectedRow = ref<any | null>(null);
const loading = ref(false);
const formRef = ref<InstanceType<typeof ElForm> | null>(null); // 表单引用

// 分页相关
const currentPage4 = ref(1);
const pageSize4 = ref(10);

// 对话框相关
const dialogVisible = ref(false);
const formData = reactive<any>({});
const dialogMode = ref<"add" | "edit">("add");

// 辅助函数：判断是否为文字字段
const isTextField = (dataKey: string): boolean => {
  return fieldTypeMap[dataKey]?.toLowerCase() === "text";
};

const isNumberField = (dataKey: string): boolean => {
  return fieldTypeMap[dataKey]?.toLowerCase() === "number";
};

// 分页和序号处理：仅数字字段处理NaN为0，文字字段保留空
const pagedTableDataWithIndex = computed(() => {
  const start = (currentPage4.value - 1) * pageSize4.value;
  const end = start + pageSize4.value;
  return tableData.value.slice(start, end).map((row, idx) => {
    const processedRow = Object.entries(row).reduce((acc, [key, val]) => {
      // 仅数字字段：NaN/undefined转为0；文字字段：保留原值（空/文字）
      if (isNumberField(key)) {
        acc[key] =
          (typeof val === "number" && isNaN(val)) || val === undefined
            ? 0
            : val;
      } else {
        acc[key] = val === undefined || val === null ? "" : val; // 文字字段空值显示空字符串
      }
      return acc;
    }, {} as any);
    return {
      ...processedRow,
      displayIndex: start + idx + 1,
    };
  });
});

// 获取表格数据：仅数字字段处理NaN为0
const fetchTable = async () => {
  console.log("正在获取表格数据...");
  try {
    loading.value = true;
    const response = await table({ table: currentTableName });
    console.log("获取到的数据:", response);
    
    // 适配后端返回的直接数组格式
    const rawData = Array.isArray(response.data) ? response.data : [];
    
    // 预处理数据：区分字段类型处理
    tableData.value = rawData.map((row: any) =>
      Object.entries(row).reduce((acc: any, [key, val]) => {
        if (isNumberField(key)) {
          acc[key] =
            (typeof val === "number" && isNaN(val)) || val === undefined
              ? 0
              : val;
        } else {
          acc[key] = val === undefined || val === null ? "" : val; // 文字字段空值存空字符串
        }
        return acc;
      }, {})
    );
  } catch (error) {
    console.error("获取数据时出错:", error);
    ElMessage.error("获取数据失败，请检查网络连接或服务器状态");
  } finally {
    loading.value = false;
  }
};

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

// 表格行点击事件：文字字段保留原值，数字字段处理NaN为0
const handleRowClick = (row: any) => {
  console.log("点击行数据:", row);
  selectedRow.value = row;
  Object.assign(
    formData,
    Object.entries(row).reduce((acc: any, [key, val]) => {
      if (isNumberField(key)) {
        acc[key] =
          (typeof val === "number" && isNaN(val)) || val === undefined
            ? 0
            : val;
      } else {
        acc[key] = val === undefined || val === null ? "" : val; // 文字字段空值显示空字符串
      }
      return acc;
    }, {})
  );
};

// 打开新增/编辑对话框：文字字段置空，数字字段可选置0
const openDialog = (mode: "add" | "edit", row?: any) => {
  dialogMode.value = mode;
  dialogVisible.value = true;

  if (mode === "add") {
    selectedRow.value = null;
    // 新增时：文字字段置空，数字字段可选置空（根据业务调整）
    editableColumns.forEach((col) => {
      formData[col.dataKey] = isTextField(col.dataKey) ? "" : "";
    });
  } else if (row) {
    selectedRow.value = row;
    // 编辑时：区分字段类型赋值
    Object.assign(
      formData,
      Object.entries(row).reduce((acc: any, [key, val]) => {
        if (isNumberField(key)) {
          acc[key] =
            (typeof val === "number" && isNaN(val)) || val === undefined
              ? 0
              : val;
        } else {
          acc[key] = val === undefined || val === null ? "" : val;
        }
        return acc;
      }, {})
    );
  }
};

// 表单数据预处理：文字字段空字符串转为undefined（适配后端）
function prepareFormData(
  formData: { [x: string]: any },
  excludeKeys = ["displayIndex"]
): { [x: string]: any } {
  const result: { [x: string]: any } = {};
  for (const key in formData) {
    if (!excludeKeys.includes(key)) {
      let value = formData[key];
      // 文字字段：空字符串转为undefined（后端可能需要NULL）；数字字段：保留原值
      if (isTextField(key)) {
        result[key] = value === "" ? undefined : value;
      } else {
        result[key] = value === "" ? undefined : value; // 数字字段空值也转为undefined
      }
    }
  }
  return result;
}

// 表单提交：文字字段必填校验
const submitForm = async () => {
  // 表单校验：文字字段必填
  if (!formRef.value) return;
  
  try {
    const isValid = await formRef.value.validate();
    if (!isValid) return;
  } catch (error) {
    console.error("表单验证失败:", error);
    return;
  }

  try {
    const dataToSubmit = prepareFormData(formData);
    let response;

    if (dialogMode.value === "add") {
      response = await addItem({
        table: currentTableName,
        item: dataToSubmit,
      });
      
      // 添加成功后，直接将新数据添加到本地数组
      if (response.data && response.data.inserted) {
        tableData.value.push(response.data.inserted);
      }
    } else {
      // 更详细的错误检查和日志
      console.log("编辑模式 - selectedRow:", selectedRow.value);
      
      if (!selectedRow.value) {
        ElMessage.error("未选中任何记录，请先选择要编辑的记录");
        return;
      }
      
      // 检查记录是否有 ID 字段
      if (!selectedRow.value.hasOwnProperty('id')) {
        console.error("记录缺少ID字段:", selectedRow.value);
        ElMessage.error("记录格式错误，缺少ID字段");
        return;
      }
      
      if (!selectedRow.value.id) {
        console.error("记录ID为空:", selectedRow.value);
        ElMessage.error("无法找到记录ID，请联系管理员");
        return;
      }
      
      response = await updateItem({
        table: currentTableName,
        id: selectedRow.value.id,
        update_data: dataToSubmit,
      });
      
      // 更新成功后，更新本地数据
      const index = tableData.value.findIndex(item => item.id === selectedRow.value.id);
      if (index > -1) {
        tableData.value[index] = {...tableData.value[index], ...dataToSubmit};
      } else {
        // 如果本地找不到记录，重新获取数据
        console.warn("本地未找到对应记录，重新获取数据");
        fetchTable();
      }
    }

    dialogVisible.value = false;
    ElMessage.success(dialogMode.value === "add" ? "添加成功" : "修改成功");
  } catch (error) {
    console.error("提交表单时发生错误:", error);
    let errorMessage = "未知错误";
    
    // 更详细的错误信息提取
    if (error && typeof error === "object") {
      const err = error as any;
      if (err.response && err.response.data) {
        errorMessage = err.response.data.detail || err.response.data.message || JSON.stringify(err.response.data);
      } else if (err.message) {
        errorMessage = err.message;
      }
    }    
    ElMessage.error(`提交失败: ${errorMessage}`);
  }
};

// 表单验证：文字字段必填，数字字段可选（根据业务调整）
function validateFormData(data: { [x: string]: any }) {
  return editableColumns.every((col) => {
    const value = data[col.dataKey];
    // 文字字段：必填（非空字符串）；数字字段：可选（允许0或空）
    if (isTextField(col.dataKey)) {
      return value !== "" && value !== undefined && value !== null;
    } else {
      return true; // 数字字段可选，空值会被后端处理为NULL
    }
  });
}

// 删除记录
const deleteItem = async (row: any) => {
  if (!row) {
    ElMessage.warning("请先选择一行记录");
    return;
  }

  try {
    await deleteItemApi({
      table: currentTableName,
      id: row.id,
    });
    
    // 直接从本地数据中删除，避免重新获取全部数据
    const index = tableData.value.findIndex((item) => item.id === row.id);
    if (index > -1) {
      tableData.value.splice(index, 1);
    }
    
    ElMessage.success("记录删除成功");
  } catch (error) {
    console.error("删除记录时发生错误:", error);
    ElMessage.error("删除失败，请重试");
  }
};

// 下载模板
const downloadTemplateAction = async () => {
  try {
    await downloadTemplate(currentTableName);
    ElMessage.success("模板下载成功");
  } catch (error) {
    console.error("下载模板时发生错误:", error);
    ElMessage.error("下载模板失败，请重试");
  }
};

// 导出数据
const exportDataAction = async () => {
  try {
    await exportData(currentTableName);
    ElMessage.success("数据导出成功");
  } catch (error) {
    console.error("导出数据时发生错误:", error);
    ElMessage.error("导出数据失败，请重试");
  }
};

// 处理文件选择（导入数据）
const handleFileSelect = async (uploadFile: any) => {
  const file = uploadFile.raw;
  if (!file) {
    ElMessage.warning("请选择有效的 .xlsx 或 .csv 文件");
    return;
  }
  await importDataAction(file);
};

// 导入数据：区分字段类型处理
const importDataAction = async (file: File) => {
  try {
    const response = await importData(currentTableName, file);
    if (response.success) {
      const { total_data, new_data, duplicate_data } = response;
      ElMessage({
        message: `导入成功！共${total_data}条，新增${new_data}条，重复${duplicate_data}条`,
        type: "success",
        duration: 3000,
      });
      fetchTable(); // 刷新表格，应用字段类型处理逻辑
    }
  } catch (error) {
    let errorMessage = "数据导入失败";
    if (
      error &&
      typeof error === "object" &&
      "message" in error &&
      "response" in error &&
      typeof (error as any).response === "object"
    ) {
      // 适配后端返回的重复记录详情
      if ((error as any).response?.data?.detail) {
        const detail = (error as any).response.data.detail;
        if (detail.duplicates) {
          // 显示重复记录的行号和文字字段内容
          const duplicateMsg = detail.duplicates
            .map(
              (item: any) =>
                `第${item.row_number}行（${Object.entries(item.duplicate_fields)
                  .map(([k, v]) => `${k}=${v || "空"}`)
                  .join("，")}`
            )
            .join("；");
          errorMessage = `导入失败：${detail.message}，重复记录：${duplicateMsg}`;
        } else {
          errorMessage = `导入失败：${detail.message || detail}`;
        }
      } else {
        errorMessage += `: ${(error as unknown as Error).message}`;
      }
    }
    ElMessage.error({
      message: errorMessage,
      duration: 5000, // 长一点的提示时间，让用户看清重复详情
    });
  }
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pageSize4.value = val;
  currentPage4.value = 1;
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  currentPage4.value = val;
};

// 表格值格式化：仅数字字段保留3位小数，文字字段显示原始内容
const formatTableValue = (row: any, column: any, cellValue: any) => {
  const dataKey = column.prop;
  // 文字字段：空值显示空字符串，非空显示原始文字
  if (isTextField(dataKey)) {
    return cellValue === undefined || cellValue === null ? "" : cellValue;
  }
  // 数字字段：NaN/undefined显示0，保留3位小数
  if (isNumberField(dataKey)) {
    if (isNaN(cellValue) || cellValue === undefined || cellValue === null) {
      return 0;
    }
    return typeof cellValue === "number" ? cellValue.toFixed(3) : cellValue;
  }
  // 其他字段：默认显示
  return cellValue;
};

// 对话框标题
const dialogTitle = computed(() => {
  return dialogMode.value === "add"
    ? `新增记录`
    : "编辑记录";
});

// 对话框提交按钮文本
const dialogSubmitButtonText = computed(() => {
  return dialogMode.value === "add" ? "添加" : "保存";
});
</script>

<style scoped>
.app-container {
  padding: 20px 40px;
  min-height: 100vh;
  background-color: #f0f2f5;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.button-group {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  width: 100%;
  margin-bottom: 20px;
}

.custom-button {
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  padding: 10px 18px;
  transition: transform 0.3s ease, background-color 0.3s ease;
  min-width: 130px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.download-button,
.export-button,
.add-button,
.import-button {
  background-color: #67c23a;
}

.download-button:hover,
.export-button:hover,
.import-button:hover,
.add-button:hover {
  background-color: #85ce61;
  transform: scale(1.05);
}

.custom-table {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  background-color: #fff;
  margin-top: 10px;
}

:deep(.el-table th) {
  background: linear-gradient(180deg, #61e054, #4db944);
  color: #fff;
  font-weight: bold;
  text-align: center;
  padding: 14px 0;
  font-size: 14px;
}

:deep(.el-table__row:nth-child(odd)) {
  background-color: #e4fbe5;
}

:deep(.el-table__row:nth-child(even)) {
  background-color: #ffffff;
}

:deep(.el-table td) {
  padding: 12px 10px;
  text-align: center;
  border-bottom: 1px solid #ebeef5;
}

.action-button {
  font-size: 16px;
  margin-right: 5px;
  border-radius: 50%;
  transition: transform 0.3s ease, background-color 0.3s ease;
}

.edit-button {
  background-color: #409eff;
  color: #fff;
}

.edit-button:hover {
  background-color: #66b1ff;
  transform: scale(1.1);
}

.delete-button {
  background-color: #f56c6c;
  color: #fff;
}

.delete-button:hover {
  background-color: #f78989;
  transform: scale(1.1);
}

.el-form-item__label {
  width: 150px;
  font-weight: bold;
}

.el-form-item__content {
  margin-left: 150px;
}

.pagination-container {
  margin-top: 30px;
  text-align: center;
}

.action-buttons {
  display: flex;
  justify-content: center;
}

/* ================= 弹框样式优化 ================= */
:deep(.el-dialog) {
  border-radius: 16px !important;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15) !important;
  background: linear-gradient(145deg, #ffffff, #f5f9ff);
  border: 1px solid #e0e7ff;
}

/* 弹框头部样式 */
.dialog-header {
  position: relative;
  padding: 20px 24px 10px;
  text-align: center;
  background: linear-gradient(90deg, #4db944, #61e054);
}

.dialog-header h2 {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: #fff;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

.header-decoration {
  height: 4px;
  background: linear-gradient(90deg, #3a9a32, #4fc747);
  border-radius: 2px;
  margin-top: 12px;
  width: 60%;
  margin-left: auto;
  margin-right: auto;
}

/* 表单容器样式 */
.custom-dialog-form {
  padding: 25px 40px 15px;
}

/* 表单项样式优化 */
.custom-form-item {
  margin-bottom: 22px !important;
}

:deep(.el-form-item__label) {
  display: block;
  text-align: left;
  margin-bottom: 8px !important;
  font-size: 15px;
  font-weight: 600;
  color: #4a5568;
  padding: 0 !important;
  line-height: 1.5;
}

/* 输入框样式优化 */
:deep(.custom-dialog-input .el-input__inner) {
  height: 44px !important;
  padding: 0 16px !important;
  font-size: 15px;
  border: 1px solid #cbd5e0 !important;
  border-radius: 10px !important;
  background-color: #f8fafc;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
}

:deep(.custom-dialog-input .el-input__inner:hover) {
  border-color: #a0aec0 !important;
}

:deep(.custom-dialog-input .el-input__inner:focus) {
  border-color: #4db944 !important;
  box-shadow: 0 0 0 3px rgba(77, 185, 68, 0.15) !important;
  background-color: #fff;
}

/* 弹框底部按钮容器 */
.dialog-footer {
  display: flex;
  gap: 16px;
  justify-content: center;
  padding: 15px 40px 25px;
}

/* 按钮基础样式 */
.custom-cancel-button,
.custom-submit-button {
  min-width: 120px;
  height: 44px;
  border-radius: 10px;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  letter-spacing: 0.5px;
  border: none;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* 取消按钮样式优化 */
.custom-cancel-button {
  background: linear-gradient(145deg, #f7fafc, #edf2f7);
  color: #4a5568;
}

.custom-cancel-button:hover {
  background: linear-gradient(145deg, #e2e8f0, #cbd5e0);
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
}

/* 提交按钮样式优化 */
.custom-submit-button {
  background: linear-gradient(145deg, #4db944, #61e054);
  color: white;
  position: relative;
  overflow: hidden;
}

.custom-submit-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    90deg,
    transparent,
    rgba(255, 255, 255, 0.3),
    transparent
  );
  transition: 0.5s;
}

.custom-submit-button:hover::before {
  left: 100%;
}

.custom-submit-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 15px rgba(77, 185, 68, 0.4);
}

/* 彻底隐藏文件信息相关元素 */
:deep(.import-upload .el-upload-list) {
  display: none !important;
}
</style>