<template>
  <div>
    <el-button type="primary" @click="openDialog()">新增名单</el-button>

    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 10px"
      v-loading="loading"
    >
      <el-table-column prop="plate_number" label="序号" align="center" min-width="50" />
      <el-table-column prop="plate_number" label="车牌号" align="center"  min-width="100" />
      <el-table-column
        prop="type"
        label="名单类型"
        :formatter="formatType"
        align="center"
        min-width="100"
      />
      <el-table-column
        prop="access_start_time"
        label="开始时间"
        :formatter="formatTime"
        align="center"
        min-width="200"
      />
      <el-table-column
        prop="access_end_time"
        label="结束时间"
        :formatter="formatTime"
        align="center"
        min-width="200"
      />
      <el-table-column label="操作" align="center" width="180">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="editRow(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteRow(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="margin-top: 15px; text-align: right">
      <el-pagination
        v-if="total > 0"
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="车牌号" prop="plate_number">
          <el-input v-model="form.plate_number" />
        </el-form-item>
        <el-form-item label="名单类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option label="白名单" value="whitelist" />
            <el-option label="黑名单" value="blacklist" />
          </el-select>
        </el-form-item>
        <el-form-item label="生效时间" prop="access_start_time">
          <el-date-picker
            v-model="form.access_start_time"
            type="datetime"
            placeholder="选择开始时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="access_end_time">
          <el-date-picker
            v-model="form.access_end_time"
            type="datetime"
            placeholder="选择结束时间"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveRow">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
// ==== 模拟API ====
// 实际项目中你应替换为：
// import { getWhitelist, addWhitelist, updateWhitelist, removeWhitelist } from '@/api/whitelist'
import axios from "axios";

export default {
  data() {
    return {
      tableData: [
        {
          id: 1,
          plate_number: "粤A12345",
          type: "whitelist",
          access_start_time: "2025-10-01 08:00:00",
          access_end_time: "2025-12-31 18:00:00"
        },
        {
          id: 2,
          plate_number: "粤B88888",
          type: "blacklist",
          access_start_time: "2025-09-01 00:00:00",
          access_end_time: "2026-01-01 00:00:00"
        },
        {
          id: 3,
          plate_number: "粤C66666",
          type: "whitelist",
          access_start_time: "2025-10-10 07:30:00",
          access_end_time: "2025-12-10 19:00:00"
        }
      ],
      loading: false,
      total: 0,
      pageSize: 10,
      currentPage: 1,

      dialogVisible: false,
      dialogTitle: "新增名单",
      editId: null,

      form: {
        plate_number: "",
        type: "whitelist",
        access_start_time: "",
        access_end_time: "",
      },

      rules: {
        plate_number: [{ required: true, message: "请输入车牌号", trigger: "blur" }],
        type: [{ required: true, message: "请选择名单类型", trigger: "change" }],
        access_start_time: [{ required: true, message: "请选择开始时间", trigger: "change" }],
        access_end_time: [{ required: true, message: "请选择结束时间", trigger: "change" }],
      },
    };
  },

  mounted() {
    // this.loadData();
  },

  methods: {
    // ===== 获取列表 =====
    async loadData() {
      this.loading = true;
      try {
        const { data } = await axios.get("/api/whitelist", {
          params: { page: this.currentPage, pageSize: this.pageSize },
        });
        this.tableData = data.records;
        this.total = data.total;
      } catch (e) {
        console.error(e);
      } finally {
        this.loading = false;
      }
    },

    // ===== 打开新增弹窗 =====
    openDialog() {
      console.log("openDialog")
      this.dialogTitle = "新增名单";
      this.form = {
        plate_number: "",
        type: "whitelist",
        access_start_time: "",
        access_end_time: "",
      };
      this.editId = null;
      this.dialogVisible = true;
      console.log("openDialog this.dialogVisible", this.dialogVisible)
    },

    // ===== 编辑 =====
    editRow(row) {
      this.dialogTitle = "编辑名单";
      this.form = { ...row };
      this.editId = row.id;
      this.dialogVisible = true;
    },

    // ===== 保存 =====
    async saveRow() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;
        try {
          if (this.editId) {
            await axios.put(`/api/whitelist/${this.editId}`, this.form);
            this.$message.success("修改成功");
          } else {
            await axios.post("/api/whitelist", this.form);
            this.$message.success("新增成功");
          }
          this.dialogVisible = false;
          this.loadData();
        } catch (e) {
          console.error(e);
          this.$message.error("保存失败");
        }
      });
    },

    // ===== 删除 =====
    async deleteRow(row) {
      try {
        await this.$confirm(`确定要删除车牌 ${row.plate_number} 吗？`, "提示", {
          type: "warning",
        });
        await axios.delete(`/api/whitelist/${row.id}`);
        this.$message.success("删除成功");
        this.loadData();
      } catch (e) {
        if (e !== "cancel") this.$message.error("删除失败");
      }
    },

    // ===== 分页 =====
    handlePageChange(page) {
      this.currentPage = page;
      this.loadData();
    },

    // ===== 格式化类型 =====
    formatType(row) {
      return row.type === "whitelist" ? "白名单" : "黑名单";
    },

    // ===== 格式化时间 =====
    formatTime(row, column, cellValue) {
      if (!cellValue) return "";
      const date = new Date(cellValue);
      return date.toLocaleString();
    },
  },
};
</script>
