<template>
    <div class="app-container p-5">
      <el-form
        :model="queryParams"
        class="main-search"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
      >
        <el-form-item label="桌台编码" prop="tableNumber">
          <el-input
            v-model="queryParams.tableNumber"
            placeholder="请输入桌台编码"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="桌台状态" prop="tableStatus">
          <el-select
            v-model="queryParams.tableStatus"
            placeholder="桌台状态"
            clearable
            style="width: 240px"
          >
            <el-option
              :key="0"
              label="启用"
              :value="0"
            />
            <el-option
              :key="1"
              label="禁用"
              :value="1"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="handleQuery">
            搜索
          </el-button>
          <el-button size="mini" @click="resetQuery">
            重置
          </el-button>
          <el-button
            type="primary"
            plain
            size="mini"
            @click="handleAdd"
          >
            添加新桌台编码
          </el-button>
        </el-form-item>
      </el-form>
  
      <el-table
        ref="tables"
        v-loading="loading"
        :data="list"
        @selection-change="handleSelectionChange"
        :default-sort="defaultSort"
        @sort-change="handleSortChange"
      >
        <el-table-column label="ID" prop="id" width="60">
          <template #default="scope">
            <span>{{ showIdLastFour(scope.row.id) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="桌台编码"
          align="center"
          prop="tableNumber"
        />
        <el-table-column
          label="所属店铺"
          align="center"
          prop="storeName"
        >
          <template #default="scope">
            <span v-if="scope.row.storeName">{{ scope.row.storeName }}</span>
            <span v-else>公共所有</span>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          sortable="custom"
          :sort-orders="['descending', 'ascending']"
          width="180"
        >
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="tableStatus">
          <template #default="scope">
            <el-switch
              v-model="scope.row.tableStatus"
              :active-value="0"
              :inactive-value="1"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleUpdate(scope.row)"
            >
              修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <el-pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
  
      <!-- 添加或修改对话框 -->
      <el-dialog
        :title="title"
        v-model="open"
        class="common-dialog"
        width="800px"
        append-to-body
      >
        <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">

              <el-form-item label="桌台编码" prop="tableNumber">
                <el-input
                  v-model="form.tableNumber"
                  placeholder="请输入桌台编码"
                  maxlength="10"
                />
              </el-form-item>

              <el-form-item label="排序" prop="sort">
                <el-input-number v-model="form.sort" :min="0" />
                <div class="form-tips ml-3">数值越小排名越靠前</div>
              </el-form-item>

              <el-form-item label="状态">
                <el-radio-group v-model="form.tableStatus">
                  <el-radio :key="0" :label="0" :value="0">
                    启用
                  </el-radio>
                  <el-radio :key="1" :label="1" :value="1">
                    禁用
                  </el-radio>
                </el-radio-group>
              </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer text-right">
          <el-button type="primary" @click="submitForm">
            确认
          </el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </el-dialog>
  
      <!-- <FuintQrCode :showDialog="openQrCode" :qr="qr" @closeDialog="closeDialog" /> -->
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, watch } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
//   import FuintQrCode from '@/components/Fuint/QrCode';
  
  // 模拟 API 调用
  const getTableList = (params) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        const mockResponse = {
          data: [
            {
              id: 1,
              tableNumber: 'T001',
              storeName: '店铺 1',
              createTime: '2024-01-01 12:00:00',
              tableStatus: 0
            },
            {
              id: 2,
              tableNumber: 'T002',
              storeName: '',
              createTime: '2024-02-01 12:00:00',
              tableStatus: 1
            }
          ],
          total: 2
        };
        resolve(mockResponse);
      }, 1000);
    });
  };
  
  const updateTableStatus = (id, status) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve();
      }, 1000);
    });
  };
  
  const getTableInfo = (id) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        const mockResponse = {
          data: {
            id: 1,
            tableNumber: 'T001',
            storeId: 1,
            sort: 0,
            maxPeople: 0,
            tableStatus: 0
          }
        };
        resolve(mockResponse);
      }, 1000);
    });
  };
  
  const saveTableUpdate = (data) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve();
      }, 1000);
    });
  };
  
  const addTableInfo = (data) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve();
      }, 1000);
    });
  };
  
  const deleteTableInfo = (id) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve();
      }, 1000);
    });
  };
  
  // 二维码相关
  const qr = ref(null);
  const openQrCode = ref(false);
  
  // 遮罩层
  const loading = ref(true);
  // 标题
  const title = ref('');
  // 选中数组
  const ids = ref([]);
  // 非多个禁用
  const multiple = ref(true);
  // 显示搜索条件
  const showSearch = ref(true);
  // 总条数
  const total = ref(0);
  // 表格数据
  const list = ref([]);
  // 是否显示弹出层
  const open = ref(false);
  // 默认排序
  const defaultSort = ref({ prop: 'id', order: 'descending' });
  // 表单参数
  const form = ref({
    id: '',
    tableNumber: '',
    storeId: '',
    sort: '',
    maxPeople: 0,
    tableStatus: 0
  });
  // 店铺列表
  const storeList = ref([]);
  
  // 查询参数
  const queryParams = ref({
    page: 1,
    pageSize: 10,
    tableNumber: '',
    tableStatus: ''
  });
  
  // 表单校验
  const rules = ref({
    tableNumber: [
      {
        required: true,
        message: '桌台编码为必填项',
        trigger: 'blur'
      },
      {
        min: 2,
        max: 30,
        message: '桌台编码长度需在 2 到 30 之间',
        trigger: 'blur'
      }
    ],
    storeId: [
      {
        required: true,
        message: '所属店铺为必填项',
        trigger: 'blur'
      }
    ]
  });
  
  // 生命周期钩子函数，组件挂载后调用
  onMounted(() => {
    getList();
  });
  
  // 查询列表
  const getList = async () => {
    loading.value = true;
    try {
      const response = await getTableList(queryParams.value);
      list.value = response.data;
      total.value = response.total;
    } catch (error) {
      console.log('获取列表错误', error);
    } finally {
      loading.value = false;
    }
  };
  
  // 搜索按钮操作
  const handleQuery = () => {
    queryParams.value.page = 1;
    getList();
  };
  const queryForm = ref(null)
  
  // 重置按钮操作
  const resetQuery = () => {
    queryForm.value.resetFields();
    handleQuery();
  };
  
  // 状态修改
  const handleStatusChange = (row) => {
    let text = row.tableStatus === 0? '启用' : '禁用';
    const confirmMsg = `确认更改桌台状态为 ${text}，桌台编码为 ${row.tableNumber}？`;
    ElMessageBox.confirm(confirmMsg, '确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        return updateTableStatus(row.id, row.tableStatus);
      })
      .then(() => {
        const successMsg = `状态更改成功，已 ${text}`;
        ElMessage.success(successMsg);
      })
      .catch(() => {
        row.tableStatus = row.tableStatus === 1? 0 : 1;
      });
  };
  
  // 多选框选中数据
  const handleSelectionChange = (selection) => {
    ids.value = selection.map((item) => item.operId);
    multiple.value =!selection.length;
  };
  
  // 排序触发事件
  const handleSortChange = (column, prop, order) => {
    queryParams.value.orderByColumn = column.prop;
    queryParams.value.isAsc = column.order;
    getList();
  };
  
  // 新增按钮操作
  const handleAdd = () => {
    reset();
    open.value = true;
    title.value = '添加新桌台编码';
  };
  const formRef = ref(null)
  
  // 表单重置
  const reset = () => {
    form.value = {
      id: '',
      tableNumber: '',
      description: '',
      storeId: '',
      maxPeople: 0,
      sort: 0,
      tableStatus: 0
    };
    // formRef.value.resetFields();
  };
  
  // 取消按钮
  const cancel = () => {
    open.value = false;
    reset();
  };
  // 提交按钮
  const submitForm = () => {
    formRef.value.validate((valid) => {
      if (valid) {
        let data = {
          categoryId: 0,
          tableNumber: form.value.tableNumber,
          capacity: form.value.maxPeople,
          tableStatus: form.value.tableStatus,
          categoryId: 0,
          categoryName: '1'
        };
        if (form.value.id) {
          data.id = form.value.id;
          saveTableUpdate(data)
            .then(() => {
              ElMessage.success('修改成功');
              open.value = false;
              getList();
            })
            .catch((error) => {
              console.log('修改错误', error);
            });
        } else {
          addTableInfo(data)
            .then(() => {
              ElMessage.success('添加成功');
              open.value = false;
              getList();
            })
            .catch((error) => {
              console.log('添加错误', error);
            });
        }
      }
    });
  };
  
  // 二维码
  const handleQrCode = (row) => {
    qr.value = { page: '/pages/category/index', type: 'table', id: row.id };
    openQrCode.value = true;
  };
  
  // 关闭二维码
  const closeDialog = () => {
    openQrCode.value = false;
  };
  
  // 修改按钮操作
  const handleUpdate = (row) => {
    reset();
    const id = row.id || ids.value;
    getTableInfo(id)
      .then((response) => {
        form.value = response.data;
        open.value = true;
        title.value = '编辑桌台编码';
      })
      .catch((error) => {
        console.log('获取桌台信息错误', error);
      });
  };
  
  // 删除按钮操作
  const handleDelete = (row) => {
    const code = row.tableNumber || form.value.id;
    const confirmMsg = `确认删除桌台编码为 ${code} 的桌台？`;
    ElMessageBox.confirm(confirmMsg, '确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        try {
          await deleteTableInfo(row.id);
          ElMessage.success('删除成功');
          getList();
        } catch (error) {
          console.log('删除错误', error);
        }
      })
      .catch(() => {});
  };
  
  // 展示 ID 的后四位
  const showIdLastFour = (id) => {
    return id.toString().slice(-4);
  };
  
  // 解析时间
  const parseTime = (time) => {
    return time;
  };
  </script>
  
  <style scoped>
  /* 这里可以添加你的样式 */
  </style>