<!-- 用户管理 -->
<template>
  <div class="app-container">
    <!-- 用户列表 -->
    <el-card shadow="never" class="table-container">
      <template #header>
        <div class="flex justify-between">
          <div>
            <el-button type="primary" @click="openDialog()"
              ><i-ep-plus />新增用户</el-button
            >
          </div>
          <!-- <div>
            <el-form ref="queryFormRef" :model="queryParams" :inline="true">
              <el-form-item label="用户信息" prop="keywords">
                <el-input
                  v-model="queryParams.keywords"
                  placeholder="用户名/手机号码"
                  clearable
                  style="width: 200px"
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleQuery"
                  ><i-ep-search />搜索</el-button
                >
                <el-button @click="resetQuery">
                  <i-ep-refresh />
                  重置</el-button
                >
              </el-form-item>
            </el-form>
          </div> -->
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="pageData"
        @selection-change="handleSelectionChange"
      >
        <el-table-column key="id" label="编号" align="left" prop="user_id" />
        <el-table-column label="用户名" align="left" prop="user_name" />
        <el-table-column label="角色编号" align="left" prop="user_role" />
        <el-table-column label="角色名称" align="left" prop="user_role_name" />
        <el-table-column label="操作" align="center" fixed="right" width="320">
          <template #default="scope">
            <el-button type="primary" size="small" text @click="resetPassword(scope.row)"
              ><i-ep-refresh-left />修改密码</el-button
            >
            <el-button type="primary" size="small" text @click="openDialogEdit(scope.row)"
              ><i-ep-edit />修改角色</el-button
            >
            <el-button
              type="primary"
              text
              size="small"
              @click="handleDelete(scope.row.user_id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.page_num"
        v-model:limit="queryParams.page_size"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 弹窗 -->
    <el-dialog v-model="formVisible" :title="title" width="680">
      <!-- 用户新增/编辑表单 -->
      <el-form
        ref="formRef"
        v-loading="formLoading"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="user_name">
          <el-input
            v-model="form.user_name"
            :disabled="form.user_id != null"
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item label="用户角色" prop="user_role">
          <el-select v-model="form.user_role" placeholder="请选择用户角色">
            <el-option
              v-for="item in listOpt.roleList"
              :key="item.key"
              :label="item.name"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="登录密码" prop="user_password" v-if="form.user_id == null">
          <el-input
            v-model="form.user_password"
            type="password"
            placeholder="请输入登录密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="password" v-if="form.user_id == null">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入确认密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import md5 from 'js-md5';
import UserAPI from "@/api/myUser";

const router = useRouter();

const title = ref(""); //  加载状态
const loading = ref(false); //  加载状态
const total = ref(0); // 数据总数
const pageData = ref([]); // 分页数据
const removeIds = ref([]); // 删除ID集合 用于批量删除
const queryFormRef = ref(ElForm); // 查询表单
const queryParams = reactive({
  page_num: 1,
  page_size: 10,
});
const form = reactive({
  user_id: null,
  user_name: null,
  user_role: null,
  user_password: null,
});
const formRef = ref(ElForm); // 表单
const formLoading = ref(false); //  加载状态
const formVisible = ref(false); //  加载状态
// 校验规则
const rules = reactive({
  user_name: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
  user_role: [{ required: true, message: "用户角色不能为空", trigger: "change" }],
  user_password: [{ required: true, message: "登录密码不能为空", trigger: "blur" }],
  password: [{ required: true, message: "确认密码不能为空", trigger: "blur" }],
});

// 基础数据列表
let listOpt = reactive({
  roleList: [
    {
      id: 1,
      key: "super",
      name: "超级管理员",
    },
    {
      id: 2,
      key: "sys_admin",
      name: "系统管理员",
    },
    {
      id: 3,
      key: "data_admin",
      name: "数据管理员",
    },
    {
      id: 4,
      key: "user",
      name: "普通用户",
    },
  ],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  UserAPI.list(queryParams)
    .then((res) => {
      pageData.value = res.data.data.user_list;
      total.value = res.data.data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.page_num = 1;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 重置密码 */
function resetPassword(row: { [key: string]: any }) {
  ElMessageBox.prompt("请输入用户「" + row.user_name + "」的新密码", "重置密码", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then(({ value }) => {
    if (!value || value.length < 6) {
      // 检查密码是否为空或少于6位
      ElMessage.warning("密码至少需要6位字符，请重新输入");
      return false;
    }
    UserAPI.updatePassword(row.user_id, { password: md5(value) }).then((res) => {
      if (res.data.code == 0) {
        ElMessage.success("密码重置成功，新密码是：" + value);
      } else {
        ElMessage.error("密码重置失败！" + res.data.message);
      }
    });
  });
}

/**
 * 打开弹窗
 */
function openDialog() {
  reset();
  title.value = "新增用户";
  formVisible.value = true;
}

/**
 * 打开弹窗
 */
function openDialogEdit(row: { [key: string]: any }) {
  reset();
  title.value = "修改用户角色";
  form.user_id = row.user_id;
  form.user_name = row.user_name;
  form.user_role = row.user_role;
  formVisible.value = true;
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  formVisible.value = false;
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  formRef.value.validate((valid: any) => {
    if (valid) {
      if (form.user_id) {
        //修改角色
        formLoading.value = true;
        UserAPI.updateAuth(form.user_id, form)
          .then((res) => {
            if (res.data.code == 0) {
              ElMessage.success("保存成功");
              formVisible.value = false;
              handleQuery();
            }
          })
          .finally(() => {
            formLoading.value = false;
          });
      } else {
        //新增用户时判断密码是否一致
        if (form.user_password != form.password) {
          ElMessage.error("两次密码不一致");
          return false;
        }
        formLoading.value = true;
        form.password = md5(form.password);
        form.user_password = md5(form.user_password);
        UserAPI.add(form)
          .then((res) => {
            if (res.data.code == 0) {
              ElMessage.success("保存成功");
              formVisible.value = false;
              handleQuery();
            }
          })
          .finally(() => {
            formLoading.value = false;
          });
      }
    }
  });
}, 3000);

/** 重置查询 */
function reset() {
  form.user_id = null;
  form.user_name = null;
  form.user_role = null;
  form.user_password = null;
}

/** 删除用户 */
function handleDelete(id?: number) {
  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    UserAPI.deleteUser(id).then((res) => {
      if (res.data.code == 0) {
        ElMessage.success("删除成功");
        handleQuery();
      } else {
        ElMessage.error("删除失败");
      }
    });
  });
}

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