<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="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="" />
        <el-table-column label="门票数" align="center" prop="" />
        <el-table-column label="比赛数" align="center" prop="" />
        <el-table-column label="账号状态" align="center" prop="statusText" />

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <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']"
              ></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>

          </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.email" disabled />
        </el-form-item>
        <el-form-item label="门票数" prop="nickName">
          <el-input v-model="form.nickName" disabled />
        </el-form-item>
        <el-form-item label="比赛记录" prop="remark">
          <el-input v-model="form.remark" 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>
  </div>
</template>

<script setup name="User" lang="ts">
import { listUser, getUser, delUser, addUser, updateUser } from '@/api/system/business/apiUsers';
import { UserVO, UserQuery, UserForm } from '@/api/system/business/apiUsers/types';

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 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 { 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`
  );
};

onMounted(() => {
  getList();
});
</script>
