<template>
  <div class="userDiv">
    <div class="userActionDiv">
      <el-button type="warning" size="default" @click="handleAddAccountButtonClick">添加</el-button>
    </div>
    <div class="userTableDiv">
      <el-table :data="showTableData" style="width: 100%" table-layout="auto">
        <el-table-column fixed prop="id" label="ID" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="relName" label="真实姓名" />
        <el-table-column label="状态">
          <template #default="scope">
            <el-switch :model-value="scope.row.status" @click="handleChangeUserStatus(scope.$index)" />
          </template>
        </el-table-column>
        <el-table-column prop="roleId" label="权限等级" />
        <el-table-column fixed="right" label="操作">
          <template #default="scope">
            <el-button
              v-if="getToken() !== scope.row.id"
              link
              type="primary"
              size="small"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
            <el-button link type="primary" size="small" @click="handleExchange(scope.row)">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="userPaginationDiv">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="totalUserCount"
        :current-page="nowPage"
        @update:current-page="handleChangePage"
      />
    </div>
    <el-dialog v-model="addAccountDialogShow" :title="getDialogTitle()" width="30%" align-center>
      <el-form ref="addAccountFormRef" :model="addAccountData" status-icon :rules="addAccountRules" label-width="120px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addAccountData.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!modifyMode">
          <el-input v-model="addAccountData.password" show-password autocomplete="off" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addAccountData.email" autocomplete="off" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="relName">
          <el-input v-model="addAccountData.relName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="权限等级" prop="roleId">
          <el-input v-model.number="addAccountData.roleId" type="number" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addAccountDialogShow = false">取消</el-button>
          <el-button type="primary" @click="handleAddAccount">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from "vue"
import { IAccount } from "@/views/user/types"
import { ElMessage, FormInstance, FormRules } from "element-plus"
import { IRegisterRequestData } from "@/api/register/types/register"
import { registerApi } from "@/api/register"
import { changeUserStatusApi, delUserApi, exChangeUserDataApi, getAllUsersApi } from "@/api/users"
import { getToken } from "@/utils/cache/cookies"

const showTableData = ref<IAccount[]>([])
const totalUserCount = ref<number>(1)
const nowPage = ref<number>(1)
const addAccountDialogShow = ref<boolean>(false)
const addAccountData = ref<IRegisterRequestData>({ username: "", password: "", email: "", relName: "", roleId: 0 })
const addAccountRules: FormRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" },
    { pattern: "[A-Za-z0-9_-一-龥]+", message: "用户名不符合要求" }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 8, max: 16, message: "长度在 8 到 16 个字符", trigger: "blur" }
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { pattern: "\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}", message: "邮箱不符合要求" }
  ],
  relName: [
    { required: true, message: "请输入真实姓名", trigger: "blur" },
    { min: 2, max: 4, message: "长度在 2 到 4 个字符", trigger: "blur" },
    { pattern: "[A-Za-z0-9_-一-龥]+", message: "真实姓名不符合要求" }
  ],
  roleId: [
    { required: true, message: "请输入权限等级", trigger: "blur" },
    { type: "number", message: "权限等级必须为数字", trigger: "blur" }
  ]
}
const addAccountFormRef = ref<FormInstance>()
const modifyMode = ref<IAccount>()
const handleDelete = (account: IAccount) => {
  delUserApi(account.id)
    .then((response) => {
      ElMessage.success("删除成功，请刷新！")
      console.log(response)
    })
    .catch(() => {
      ElMessage.error("删除失败，请重试！")
    })
}
const handleExchange = (account: IAccount) => {
  addAccountDialogShow.value = true
  modifyMode.value = account
  addAccountData.value.password = ""
  addAccountData.value.username = account.username
  addAccountData.value.email = account.email
  addAccountData.value.relName = account.relName
  addAccountData.value.roleId = account.roleId
}
const handleAddAccountButtonClick = () => {
  addAccountDialogShow.value = true
  modifyMode.value = undefined
  addAccountData.value.password = ""
  addAccountData.value.username = ""
  addAccountData.value.email = ""
  addAccountData.value.relName = ""
  addAccountData.value.roleId = 0
}
const handleAddAccount = () => {
  if (!addAccountFormRef.value?.validate()) {
    ElMessage.error("数据存在错误！")
    return
  }
  if (modifyMode.value) {
    modifyMode.value.username = addAccountData.value.username
    modifyMode.value.email = addAccountData.value.email
    modifyMode.value.relName = addAccountData.value.relName
    modifyMode.value.roleId = addAccountData.value.roleId
    exChangeUserDataApi({
      id: modifyMode.value.id,
      username: modifyMode.value.username,
      email: modifyMode.value.email,
      relName: modifyMode.value.relName,
      roleId: modifyMode.value.roleId
    })
      .then(() => {
        ElMessage.success("修改成功")
        addAccountDialogShow.value = false
      })
      .catch(() => {
        ElMessage.error("修改失败！")
      })
    return
  }
  addAccountDialogShow.value = false
  registerApi(addAccountData.value)
    .then((_) => {
      ElMessage.success("添加成功！")
      handleChangePage()
    })
    .catch((err) => {
      ElMessage.error("添加用户失败！，原因：" + err.message)
    })
}
const handleChangePage = () => {
  getAllUsersApi(nowPage.value)
    .then((response) => {
      showTableData.value = response.data.data.info
      totalUserCount.value = response.data.data.total
    })
    .catch(() => {
      ElMessage.error("获取用户数据失败！")
    })
}
const getDialogTitle = (): string => {
  if (modifyMode.value) {
    return "修改用户"
  }
  return "添加用户"
}
const handleChangeUserStatus = (index: number) => {
  if (getToken() !== showTableData.value[index].id) {
    const userData = showTableData.value[index]
    if (userData) {
      showTableData.value[index].status = !showTableData.value[index].status
      changeUserStatusApi(showTableData.value[index].id, showTableData.value[index].status)
        .then(() => {
          ElMessage.success("修改成功")
        })
        .catch((err) => {
          console.log(err)
          ElMessage.error("修改失败！")
        })
    }
  } else {
    ElMessage.error("用户不能修改自己的状态！")
  }
}
onMounted(() => {
  handleChangePage()
})
</script>

<style scoped>
.userDiv {
  width: calc(100% - 20px);
  height: calc(100% - 20px);
  margin: 10px 10px 10px 10px;
}
.userTableDiv {
  width: 100%;
  height: calc(90% - 20px);
  margin-top: 10px;
}
.userActionDiv {
  height: 5%;
  width: max-content;
  min-height: 32px;
}
.userPaginationDiv {
  height: 5%;
  margin-top: 10px;
  min-height: 32px;
}
</style>
