<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.loginName" 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="注册时间" prop="createAt">
              <el-date-picker clearable v-model="queryParams.createAt" type="date" value-format="YYYY-MM-DD HH:MM:SS" placeholder="请选择创建时间" />
            </el-form-item>

            <el-form-item label="登录时间" prop="lastLoginTime">
              <el-date-picker
                clearable
                v-model="queryParams.lastLoginTime"
                type="date"
                value-format="YYYY-MM-DD HH:MM:SS"
                placeholder="请选择上一次登录时间"
              />
            </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">
          &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" prop="loginName" />
        <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="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="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" width="350" class-name="small-padding fixed-width">
          <template #default="scope">
            <div style="display: flex; justify-content: center; gap: 8px">
              <el-tooltip content="查看" placement="top">
                <el-button link type="primary" icon="View" @click="handleUpdate(scope.row)" v-hasPermi="['business:user:edit']">查看</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>
            </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.loginName" disabled />
        </el-form-item>

        <el-form-item label="用户姓名" prop="loginPass">
          <el-input v-model="form.loginName" disabled />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" disabled />
        </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="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>
  </div>
</template>

<script setup name="User" lang="ts">
import { listUser, getUser, delUser, addUser, updateUser, sendRewardToos } 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;

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 dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

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

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;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  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
    },
    `user_${new Date().getTime()}.xlsx`
  );
};
const handlePhoneInput = (value: string) => {
  editForm.value.phone = value.replace(/[^0-9]/g, '');
};
onMounted(() => {
  getList();
  loadItemOptions();
});

// 下拉选项数据 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 === 1 的项，并映射为 { id, label } 结构
      const list = data
        .filter((item) => item.id !== 1) // ✅ 过滤掉 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
});

// 表单校验规则
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);
  }
};
</script>
