<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 :before-upload="importDataAction" accept=".xlsx, .csv">
        <el-button
          :icon="Upload"
          type="primary"
          class="custom-button import-button"
          >导入数据</el-button
        >
      </el-upload>
    </div>

    <!-- 数据表格 -->
    <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="formatNumber"
        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%">
      <el-form :model="formData" label-width="120px">
        <el-form-item
          v-for="col in editableColumns"
          :key="col.key"
          :label="col.title"
        >
          <el-input
            v-model="formData[col.dataKey]"
            :type="col.inputType || 'text'"
            class="custom-input"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #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>
      </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 } from "element-plus";
import {
  table,
  updateItem,
  addItem,
  deleteItemApi,
  downloadTemplate,
  exportData,
  importData,
} from "@/API/menus";
import PaginationComponent from "./packaged/PaginationComponent.vue";

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

const columns: Column[] = [
  { key: "id", dataKey: "id", title: "序号", width: 100 },
  { key: "Q_over_b", dataKey: "Q_over_b", title: "Q/ΔpH", width: 180 },
  { key: "pH", dataKey: "pH", title: "初始pH", width: 180 },
  { key: "OM", dataKey: "OM", title: "有机质含量", width: 180 },
  { key: "CL", dataKey: "CL", title: "土壤粘粒", width: 180 },
  { key: "H", dataKey: "H", title: "交换性氢", width: 180 },
  { key: "Al", dataKey: "Al", title: "交换性铝", width: 180 },
];

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

const tableData = ref<any[]>([]);
const selectedRow = ref<any | null>(null);
const dialogVisible = ref(false);
const formData = reactive<any>({});
const dialogMode = ref<"add" | "edit">("add"); // 新增还是编辑模式

const currentPage4 = ref(1);
const pageSize4 = ref(10);

const pagedTableData = computed(() => {
  const start = (currentPage4.value - 1) * pageSize4.value;
  const end = start + pageSize4.value;
  return tableData.value.slice(start, end);
});

const pagedTableDataWithIndex = computed(() => {
  return pagedTableData.value.map((item, index) => ({
    ...item,
    displayIndex: (currentPage4.value - 1) * pageSize4.value + index + 1,
  }));
});

const loading = ref(false);
const currentTableName = "current_reduce";

const fetchTable = async () => {
  try {
    loading.value = true;
    const response = await table({ table: currentTableName });
    tableData.value = response.data.rows;
  } catch (error) {
    console.error("获取数据时出错:", error);
    ElMessage.error("获取数据失败，请检查网络连接或服务器状态");
  } finally {
    loading.value = false;
  }
};

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

const handleRowClick = (row: any) => {
  selectedRow.value = row;
  Object.assign(formData, row);
};

const openDialog = (mode: "add" | "edit", row?: any) => {
  if (mode === "add") {
    selectedRow.value = null;
    editableColumns.forEach((col) => {
      formData[col.dataKey] = "";
    });
  } else if (row) {
    selectedRow.value = row;
    Object.assign(formData, row);
  }
  dialogMode.value = mode;
  dialogVisible.value = true;
};

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];
      if (typeof value === "string" && value.startsWith("displayIndex-")) {
        value = value.replace("displayIndex-", "");
      }
      result[key] = value;
    }
  }
  return result;
}

const submitForm = async () => {
  try {
    const isValid = validateFormData(formData);
    if (!isValid) {
      alert("请检查输入的数据");
      return;
    }
    const dataToSubmit = prepareFormData(formData);
    if (!dataToSubmit.id && dialogMode.value !== "add") {
      alert("无法找到记录ID，请联系管理员");
      return;
    }
    let response;
    if (dialogMode.value === "add") {
      response = await addItem({ table: currentTableName, item: dataToSubmit });
    } else {
      response = await updateItem({
        table: currentTableName,
        item: dataToSubmit,
      });
    }
    dialogVisible.value = false;
    fetchTable();
    alert(dialogMode.value === "add" ? "添加成功" : "修改成功");
  } catch (error) {
    let errorMessage = "未知错误";
    if (error && typeof error === "object" && "response" in error) {
      const response = (error as { response?: { data?: { message?: string } } })
        .response;
      if (
        response &&
        response.data &&
        typeof response.data.message === "string"
      ) {
        errorMessage = response.data.message;
      }
    }
    alert(`提交失败: ${errorMessage}`);
  }
};

function validateFormData(data: { [x: string]: undefined }) {
  for (let key in data) {
    if (data[key] === "" || data[key] === undefined) {
      return false;
    }
  }
  return true;
}

const deleteItem = async (row: any) => {
  if (!row) {
    ElMessage.warning("请先选择一行记录");
    return;
  }
  try {
    const condition = { id: row.id };
    await deleteItemApi({ table: "current_reduce", condition });
    const index = tableData.value.findIndex((item) => item.id === row.id);
    if (index > -1) {
      tableData.value.splice(index, 1);
    }
    fetchTable();
  } catch (error) {
    console.error("删除记录时发生错误:", error);
  }
};

const downloadTemplateAction = async () => {
  try {
    await downloadTemplate("current_reduce");
  } catch (error) {
    console.error("下载模板时发生错误:", error);
  }
};

const exportDataAction = async () => {
  try {
    await exportData("current_reduce");
  } catch (error) {
    console.error("导出数据时发生错误:", error);
  }
};

// 导入
const importDataAction = async (file: File) => {
  try {
    const response = await importData("reduce", file); // 传递 dataset_type 的值（如 'reduce'）
    if (response && response.data) {
      const { total_data, new_data, duplicate_data, message } = response.data;
      ElMessage({
        message: `导入结果: ${message} 新增总数：${total_data}, 成功新增：${new_data}, 数据重复：${duplicate_data}`,
        type: "success",
      });
      fetchTable(); // 假设存在 fetchTable 方法刷新表格
    }
  } catch (error) {
    let errorMessage = "数据导入失败";
    if (error && typeof error === "object" && "response" in error) {
      const response = (error as { response?: { data?: { message?: string } } })
        .response;
      if (response && response.data && typeof response.data.message === "string") {
        errorMessage += `: ${response.data.message}`;
      }
    }
    ElMessage.error(errorMessage);
  }
};

const handleFileChange = (event: Event) => {
  const target = event.target as HTMLInputElement;
  if (target.files && target.files.length > 0) {
    importDataAction(target.files[0]);
  }
};


const handleSizeChange = (val: number) => {};
const handleCurrentChange = (val: number) => {};

const formatNumber = (row: any, column: any, cellValue: any) => {
  if (typeof cellValue === "number") {
    return cellValue.toFixed(3);
  }
  return cellValue;
};

const dialogTitle = computed(() => {
  return dialogMode.value === "add" ? "新增记录" : "编辑记录";
});

const dialogSubmitButtonText = computed(() => {
  return dialogMode.value === "add" ? "添加" : "保存";
});
</script>

<style scoped>
.app-container {
  padding: 15px 40px;
  min-height: 100vh;
  background-color: #f0f2f5;
  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;
}
.custom-input .el-input__inner {
  border-radius: 6px;
  border: 1px solid #dcdcdc;
  transition: border-color 0.3s ease;
  padding: 10px;
  font-size: 14px;
}
.custom-input .el-input__inner:focus {
  border-color: #409eff;
}
.custom-cancel-button,
.custom-submit-button {
  border: none;
  border-radius: 6px;
  font-size: 14px;
  padding: 10px 20px;
  transition: transform 0.3s ease, background-color 0.3s ease;
  min-width: 100px;
}
.custom-cancel-button {
  background-color: #f4f4f5;
  color: #606266;
}
.custom-cancel-button:hover {
  background-color: #e4e7ed;
  transform: scale(1.05);
}
.custom-submit-button {
  background-color: #409eff;
  color: #fff;
}
.custom-submit-button:hover {
  background-color: #66b1ff;
  transform: scale(1.05);
}
.pagination-container {
  margin-top: 30px;
  text-align: center;
}
.action-buttons {
  display: flex;
  justify-content: center;
}
</style>
