<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="用户昵称" prop="loginName">
              <el-input v-model="queryParams.nickName" placeholder="请输入用户昵称" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="手机号" prop="phone">
              <el-input v-model="queryParams.phone" placeholder="请输入手机号" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="注册时间">
              <el-date-picker
                v-model="data.queryParams.registerTimeRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>

            <el-form-item label="登录时间">
              <el-date-picker
                v-model="data.queryParams.loginTimeRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['business:user:export']">导出</el-button>
          </el-col>
        </el-row>
      </template>

      <!--      <template #header>
        <el-row :gutter="10" class="mb8">
          &lt;!&ndash;          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['business:user:add']">新增</el-button>
          </el-col>&ndash;&gt;
          &lt;!&ndash;          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['business:user:edit']"
              >修改</el-button
            >
          </el-col>&ndash;&gt;
          &lt;!&ndash;          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['business:user:remove']"
              >删除</el-button
            >
          </el-col>&ndash;&gt;
          &lt;!&ndash;          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['business:user:export']">导出</el-button>
          </el-col>&ndash;&gt;
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>-->

      <el-table v-loading="loading" border :data="userList" @selection-change="handleSelectionChange">
        <!--        <el-table-column type="selection" width="55" align="center" />-->
        <el-table-column label="用户id" align="center" prop="id" v-if="true" />
        <el-table-column label="登录名称" align="center">
          <template #default="scope">
            <span>{{ scope.row.loginName || scope.row.phone }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用户姓名" align="center" prop="realName" />
        <el-table-column label="用户昵称" align="center" prop="nickName" />
        <el-table-column label="用户手机号码" align="center" prop="phone" />
        <el-table-column label="用户等级" align="center" prop="currentLevelCode" />
        <el-table-column label="注册时间" align="center" prop="createAt" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>

        <el-table-column label="最新上线时间" align="center" prop="createAt" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.lastLoginTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="版本" align="center" prop="appVersion" />
        <el-table-column label="积分数" align="center" prop="pointsQuantity" />
        <el-table-column label="门票数" align="center" prop="itemsQuantity" />
        <el-table-column label="比赛数" align="center" prop="tournamentCount" />
        <el-table-column label="账号状态" align="center" prop="statusText" />
        <el-table-column label="注销状态" align="center" prop="deactivateStatus">
          <template #default="scope">
            <el-tag v-if="scope.row.deactivateStatus === 0" type="success">正常</el-tag>
            <el-tag v-else-if="scope.row.deactivateStatus === 1" type="warning">注销中</el-tag>
            <el-tag v-else type="danger">已注销</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="550" class-name="small-padding fixed-width">
          <template #default="scope">
            <div class="action-container">
              <el-tooltip content="查看" placement="top">
                <el-button link type="primary" icon="View" @click="handleUpdate(scope.row)">查看</el-button>
              </el-tooltip>

              <!-- 禁用/启用 按钮 -->
              <el-tooltip :content="scope.row.status === 1 ? '禁用' : '启用'" placement="top">
                <el-button
                  link
                  type="primary"
                  :icon="scope.row.status === 1 ? 'Lock' : 'Unlock'"
                  @click="toggleStatus(scope.row)"
                  v-hasPermi="['business:user:edit']"
                >
                  {{ scope.row.status === 1 ? '禁用' : '启用' }}
                </el-button>
              </el-tooltip>

              <el-tooltip content="删除" placement="top">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:user:remove']">删除</el-button>
              </el-tooltip>

              <el-tooltip content="编辑道具" placement="top">
                <el-button link type="primary" icon="Tools" @click="openGrantDialog(scope.row)" v-hasPermi="['business:user:remove']"
                  >编辑道具</el-button
                >
              </el-tooltip>

              <el-tooltip content="查看流水" placement="top">
                <el-button link type="primary" icon="View" @click="viewPointsLog(scope.row)" v-hasPermi="['business:user:edit']">查看流水</el-button>
              </el-tooltip>

              <el-tooltip content="查看道具" placement="top">
                <el-button link type="primary" icon="View" @click="viewPointsBag(scope.row)" v-hasPermi="['business:user:edit']">查看道具</el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 查看用户详情对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="userFormRef" :model="form" :rules="rules" label-width="80px">
        <!--
        <el-form-item label="用户ID" prop="id">
          <el-input v-model="form.id" disabled />
        </el-form-item>
-->

        <el-form-item label="登录名称" prop="loginName">
          <el-input v-model="form.phone" disabled />
        </el-form-item>

        <el-form-item label="用户姓名" prop="loginPass">
          <el-input v-model="form.realName" disabled />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <div style="display: flex; align-items: center; gap: 8px">
            <el-input v-model="form.phone" disabled />
            <el-button type="primary" size="small" @click="openEditPhoneDialog(form.id, form.phone)">修改</el-button>
          </div>
        </el-form-item>
        <el-form-item label="注册时间" prop="createAt">
          <el-date-picker clearable v-model="form.createAt" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" disabled> </el-date-picker>
        </el-form-item>

        <el-form-item label="上线时间" prop="lastLoginTime">
          <el-date-picker clearable v-model="form.lastLoginTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" disabled> </el-date-picker>
        </el-form-item>

        <el-form-item label="积分数" prop="email">
          <el-input v-model="form.pointsQuantity" disabled />
        </el-form-item>
        <el-form-item label="门票数" prop="nickName">
          <el-input v-model="form.itemsQuantity" disabled />
        </el-form-item>
        <el-form-item label="比赛数" prop="remark">
          <el-input v-model="form.tournamentCount" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <!--          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>-->
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog :title="editDialog.title" v-model="editDialog.visible" width="500px" append-to-body>
      <el-form ref="editUserFormRef" :model="editForm" :rules="rules2" label-width="80px">
        <el-form-item label="用户ID" prop="id" v-show="false">
          <el-input v-model="editForm.id" disabled />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" @input="handlePhoneInput" />
        </el-form-item>

        <el-form-item label="积分数" prop="score">
          <el-input v-model.number="editForm.score" />
        </el-form-item>

        <el-form-item label="门票数" prop="ticketCount">
          <el-input v-model.number="editForm.ticketCount" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitEditForm">确 定</el-button>
          <el-button @click="cancelEdit">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 发放道具弹窗 -->
    <el-dialog v-model="grantDialogVisible" title="操作道具" width="400px">
      <div class="dialog-content">
        <!-- 左侧内容 -->
        <div class="left-content">
          <el-form :model="grantForm" ref="grantFormRef">
            <el-input v-model="grantForm.userId" disabled v-show="false" />
            <el-form-item label="手机号" prop="id">
              <el-input v-model="grantForm.phone" disabled />
            </el-form-item>
            <el-form-item label="道具类型" prop="itemId">
              <!-- 道具选择 -->
              <el-select v-model="grantForm.itemId" placeholder="请选择道具" style="width: 120px; margin-right: 8px">
                <el-option v-for="item in itemOptions" :key="item.id" :label="item.label" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="操作类型" prop="itemId">
              <el-select v-model="grantForm.type" placeholder="请操作类型" style="width: 120px; margin-right: 8px">
                <el-option label="增加" :value="1" />
                <el-option label="扣除" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="数量" prop="quantity">
              <el-input-number v-model="grantForm.quantity" :min="1" :max="999999" />
            </el-form-item>
          </el-form>
        </div>

        <!-- 右侧内容 -->
        <div class="right-content">
          <!-- 这里可以放置其他内容或留空 -->
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="grantDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitGrantForm">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog :title="editPhoneDialog.title" v-model="editPhoneDialog.visible" width="400px" center>
      <div class="dialog-content">
        <!-- 提示信息 -->
        <div class="tip-text">
          此操作将替换原手机号：<strong>{{ editPhoneForm.oldPhone }}</strong
          >，请谨慎操作
        </div>

        <el-form ref="editPhoneFormRef" :model="editPhoneForm" :rules="editPhoneRules" label-width="80px" style="margin-top: 20px">
          <el-form-item label="新手机号" prop="newPhone">
            <el-input v-model="editPhoneForm.newPhone" placeholder="请输入新的手机号" />
          </el-form-item>

          <el-form-item label="验证码" prop="verifyCode">
            <div
              STYLE=" display: flex;
  align-items: center;
  gap: 8px;"
            >
              <el-input v-model="editPhoneForm.verifyCode" placeholder="请输入验证码" style="width: 180px" />
              <el-button type="primary" size="small" style="margin-left: 10px" :disabled="countdown > 0" @click="sendVerifyCode">
                {{ countdown > 0 ? `${countdown}s` : '发送验证码' }}
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editPhoneDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitEditPhone">确认修改</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User" lang="ts">
import { listUser, getUser, delUser, addUser, updateUser, sendRewardToos, getSmsCode, updateUserPhone } from '@/api/system/business/apiUsers';
import { UserVO, UserQuery, UserForm } from '@/api/system/business/apiUsers/types';
import { selectItemsSelList } from '@/api/system/business/items';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
import { parseTime } from '@/utils/dateUtils';
const userList = ref<UserVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const userFormRef = ref<ElFormInstance>();

const initFormData: UserForm = {
  id: undefined,
  loginName: undefined,
  loginPass: undefined,
  phone: undefined,
  createAt: undefined,
  updateAt: undefined,
  sex: undefined,
  email: undefined,
  nickName: undefined,
  remark: undefined,
  captcha: undefined,
  avatar: undefined,
  province: undefined,
  city: undefined,
  area: undefined,
  placeDetail: undefined,
  registerIp: undefined,
  registerDevice: undefined,
  status: undefined,
  isLocked: undefined,
  lastLoginTime: undefined,
  lastLoginIp: undefined
};
const data = reactive<PageData<UserForm, UserQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    loginName: undefined,
    loginPass: undefined,
    phone: undefined,
    createAt: undefined,
    updateAt: undefined,
    sex: undefined,
    email: undefined,
    nickName: undefined,
    captcha: undefined,
    avatar: undefined,
    province: undefined,
    city: undefined,
    area: undefined,
    placeDetail: undefined,
    registerIp: undefined,
    registerDevice: undefined,
    status: undefined,
    isLocked: undefined,
    lastLoginTime: undefined,
    lastLoginIp: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    loginName: [{ required: true, message: '登录名称不能为空', trigger: 'blur' }],
    loginPass: [{ required: true, message: '登录密码不能为空', trigger: 'blur' }]
  }
});

const editForm = ref<UserForm>({
  id: undefined,
  phone: '',
  ticketCount: '',
  score: ''
});
const rules2 = ref({
  phone: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号格式',
      trigger: 'blur'
    }
  ]
});
const submitEditForm = async () => {
  try {
    await updateUser(editForm.value); // 调用更新接口
    proxy?.$modal.msgSuccess('编辑成功');
    editDialog.visible = false;
    getList(); // 刷新列表
  } catch (error) {
    console.error(error);
  }
};

const cancelEdit = () => {
  editDialog.visible = false;
};

const handleEdit = async (row: UserVO) => {
  const userId = row.id;
  const res = await getUser(userId);
  editForm.value = { ...res.data }; // 把数据赋值给可编辑表单
  editDialog.visible = true;
  editDialog.title = '编辑';
};

const { queryParams, form, rules } = toRefs(data);

/** 查询【请填写功能名称】列表 */
const getList = async () => {
  loading.value = true;
  const res = await listUser(queryParams.value);
  userList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  userFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  const timeRange = data.queryParams.loginTimeRange;
  if (timeRange && timeRange.length === 2) {
    data.queryParams.loginBeginTime = timeRange[0];
    data.queryParams.loginEndTime = timeRange[1];
  } else {
    data.queryParams.loginBeginTime = null;
    data.queryParams.loginEndTime = null;
  }
  const timeRange2 = data.queryParams.registerTimeRange;
  if (timeRange2 && timeRange2.length === 2) {
    data.queryParams.registerBeginTime = timeRange2[0];
    data.queryParams.registerEndTime = timeRange2[1];
  } else {
    data.queryParams.registerBeginTime = null;
    data.queryParams.registerEndTime = null;
  }
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  // 重置时间范围选择器
  data.queryParams.registerTimeRange = '';
  data.queryParams.loginTimeRange = '';
  data.queryParams.nickName = '';
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: UserVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加【请填写功能名称】';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: UserVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getUser(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '查看【用户详情】';
};

const toggleStatus = (row) => {
  const newStatus = row.status === 1 ? 0 : 1;
  const confirmText = newStatus === 0 ? '禁用' : '启用';
  row.status = newStatus;
  // 弹出确认框
  ElMessageBox.confirm(`确认要${confirmText}用户【${row.nickName || row.loginName}】吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      // 调用 API 接口更新状态
      updateUser(row).then((response) => {
        if (response.code === 200) {
          ElMessage.success(confirmText + '成功');
          // 刷新列表
          handleQuery();
        } else {
          ElMessage.error('操作失败：' + response.msg);
        }
      });
    })
    .catch(() => {
      // 取消操作
    });
};

/** 提交按钮 */
const submitForm = () => {
  userFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateUser(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addUser(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: UserVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除【用户管理】编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delUser(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'business/user/export',
    {
      ...queryParams.value
    },
    `用户管理${parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')}.xlsx`
  );
};
const handlePhoneInput = (value: string) => {
  editForm.value.phone = value.replace(/[^0-9]/g, '');
};
onMounted(() => {
  getList();
  loadItemOptions();
});
onUnmounted(() => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
  }
});
// 关闭弹窗时清除倒计时
/*watch(
  () => editPhoneDialog.visible,
  (newVal) => {
    if (!newVal && countdownTimer.value) {
      clearInterval(countdownTimer.value);
      countdownTimer.value = null;
      countdown.value = 0;
    }
  }
);*/
// 下拉选项数据 selectBlingStructuresInfo
const itemOptions = ref<{ id: number; label: string }[]>([]);

// 加载报名条件选项
const loadItemOptions = async () => {
  try {
    const res = await selectItemsSelList();
    if (res.code === 200) {
      // 使用 unknown 中间类型进行类型转换
      const data = res.data as unknown as { id: number; name: string }[];

      // 过滤掉 id === 2 的项，并映射为 { id, label } 结构
      const list = data
        .filter((item) => item.id !== 2) // ✅ 过滤掉 id 为 1 的选项
        .map((item) => ({
          id: item.id,
          label: item.name
        }));

      itemOptions.value = list;
    } else {
      alert('加载失败：' + res.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
  }
};

// 弹窗是否显示
const grantDialogVisible = ref(false);
// 表单数据
const grantForm = ref({
  itemId: null,
  quantity: 1,
  phone: null,
  userId: null,
  type: 1
});

// 表单校验规则
const grantRules = {
  itemId: [{ required: true, message: '请选择道具类型', trigger: 'change' }],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
  ]
};
const currentUser = ref(null);
// 打开弹窗
const openGrantDialog = (row) => {
  currentUser.value = row;
  grantForm.value.phone = row.phone;
  grantForm.value.userId = row.id;
  grantForm.value.itemId = null;
  grantForm.value.quantity = 1;
  grantDialogVisible.value = true;
};

const submitGrantForm = async () => {
  try {
    if (grantForm.value.itemId == null) {
      return proxy?.$modal.msgWarning('请选择对应道具');
    }
    if (grantForm.value.quantity == null) {
      return proxy?.$modal.msgWarning('请选择对应道具数量');
    }
    await sendRewardToos(grantForm.value); // 调用更新接口
    proxy?.$modal.msgSuccess('操作成功');
    grantDialogVisible.value = false;
    getList(); // 刷新列表
  } catch (error) {
    console.error(error);
  }
};
const router = useRouter(); // 获取 router 实例
// 查看积分流水
const viewPointsLog = (row: UserVO) => {
  // 跳转到积分流水页面，并传递用户ID作为查询参数
  router.push({
    path: '/pay/itemsLog',
    query: {
      userId: row.id,
      t: Date.now() // 添加时间戳确保URL变化，触发页面刷新
    }
  });
};
const viewPointsBag = (row: UserVO) => {
  // 跳转到积分流水页面，并传递用户ID作为查询参数
  router.push({
    path: '/pay/playerItems',
    query: {
      userId: row.id,
      t: Date.now() // 添加时间戳确保URL变化，触发页面刷新
    }
  });
};
// 弹窗状态和表单数据
const editPhoneDialog = reactive({
  visible: false,
  title: '修改手机号'
});

const editPhoneForm = reactive({
  id: null,
  oldPhone: '',
  newPhone: '',
  verifyCode: ''
});
const openEditPhoneDialog = (userId: string | number, phone: string) => {
  editPhoneForm.id = userId;
  editPhoneForm.oldPhone = phone;
  editPhoneForm.newPhone = '';
  editPhoneForm.verifyCode = '';
  editPhoneDialog.visible = true;
};
const editPhoneRules = {
  newPhone: [
    { required: true, message: '请输入新手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  verifyCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
};

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const editDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 倒计时相关
const countdown = ref(0); // 当前倒计时秒数
const countdownTimer = ref<NodeJS.Timeout | null>(null);

// 发送验证码
const sendVerifyCode = async () => {
  if (!editPhoneForm.newPhone) {
    ElMessage.warning('请先填写新手机号');
    return;
  }
  if (countdown.value > 0) {
    // 正在倒计时中，不允许重复发送
    return;
  }
  try {
    await getSmsCode(editPhoneForm.newPhone);
    ElMessage.success('验证码已发送');

    // 启动倒计时（60秒）
    startCountdown(60);
  } catch (error) {
    ElMessage.error('发送失败，请重试');
  }
};
// 启动倒计时
const startCountdown = (seconds: number) => {
  countdown.value = seconds;

  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
  }

  countdownTimer.value = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      if (countdownTimer.value) {
        clearInterval(countdownTimer.value);
        countdownTimer.value = null;
      }
    }
  }, 1000);
};
const editPhoneFormRef = ref<ElFormInstance>();
// 提交修改
const submitEditPhone = async () => {
  try {
    // 1. 表单校验
    await editPhoneFormRef.value?.validate();

    const formData: Partial<UserForm> = {
      id: editPhoneForm.id,
      phone: form.value.phone,
      newPhone: editPhoneForm.newPhone,
      verifyCode: editPhoneForm.verifyCode
    };
    await updateUserPhone(formData).finally(() => (buttonLoading.value = false));

    ElMessage.success('手机号修改成功');
    editPhoneDialog.visible = false;

    // 更新主表单中的 phone 字段
    form.value.phone = editPhoneForm.newPhone;
  } catch (error) {
    console.error(error);
  }
};
</script>
<style scoped>
.action-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  min-width: 100%;
  max-width: none;
  overflow-x: auto;
  overflow-y: hidden;
  white-space: nowrap;
  padding: 0 8px;
}
</style>
