<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { addUser, delUser, updateUser, userList } from '@/apis/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, ref } from 'vue'

onMounted(() => {
  queryUserList()
})
const userDataList = ref<User.User[]>([])
const visible = ref(false)
const userForm = ref<Record<string, string | number | boolean>>({})
const userFormRef = ref()
const queryUserList = () => {
  const params = {
    pageSize: 10,
    pageNum: 1,
  }
  userList(params).then((res) => {
    userDataList.value = res.list
  })
}
const createUser = () => {
  userForm.value = {}
  visible.value = true
}
const editUser = () => {
  if (!selectedList.value || !selectedList.value.length) {
    ElMessage.warning('请选择一条数据进行编辑')
    return
  }
  const userItem = selectedList.value[0]
  userForm.value = {
    username: userItem.username,
    nickname: userItem.nickname,
    deleted: userItem.deleted,
    id: userItem.id,
    isAdmin: userItem.role === 'ADMIN',
    role: userItem.role,
  }
  visible.value = true
  // updateUser()
}
const onDelUser = () => {
  if (!selectedList.value.length) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  ElMessageBox.confirm(
    '确认删除选中的数据吗？',
    '确认提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    const ids = selectedList.value.map(item => item.id)
    delUser(ids.join(',')).then(() => {
      ElMessage.success('删除成功')
      queryUserList()
    })
  })
}

const selectedList = ref<User.User[]>([])
const onSelectionChange = (rows: User.User[]) => {
  selectedList.value = rows
}
const closeDialog = () => {
  visible.value = false
}
const onConfirm = (formRef: FormInstance | undefined) => {
  if (!formRef) {
    return
  }
  formRef.validate((valid) => {
    if (valid) {
      if (userForm.value.id) {
        doEdit()
      }
      else {
        doSave()
      }
    }
    else {
      console.log('error submit!')
    }
  })
}
const doEdit = () => {
  const { username, nickname, isAdmin, id } = userForm.value
  const params = {
    username: username as string,
    nickname: nickname as string,
    role: isAdmin ? 'ADMIN' : 'USER',
    deleted: 'ENABLE',
    id: id as number,
  }
  updateUser(params).then(() => {
    ElMessage.success('保存成功')
    queryUserList()
    closeDialog()
  })
}

const doSave = () => {
  const { username, nickname, password, confirmPassword, isAdmin } = userForm.value
  if (password !== confirmPassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }
  const params: User.AddUser = {
    username: username as string,
    nickname: nickname as string,
    password: password as string,
    role: isAdmin ? 'ADMIN' : 'USER',
    deleted: 'ENABLE',
  }
  addUser(params).then(() => {
    ElMessage.success('保存成功')
    queryUserList()
    closeDialog()
  })
}
</script>

<template>
  <div>
    <div>
      <FtButton type="primary" @click="createUser">
        添加用户
      </FtButton>
      <FtButton type="primary" @click="editUser">
        编辑用户
      </FtButton>
      <FtButton @click="onDelUser">
        删除用户
      </FtButton>
    </div>
    <div>
      <el-table :data="userDataList" stripe style="width: 100%" @selection-change="onSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="50" />
        <el-table-column prop="username" label="登录名" />
        <el-table-column prop="nickname" label="用户名" />
        <el-table-column prop="fixedUser" label="状态">
          <template #default="scoped">
            <span v-if="scoped.row.deleted === 'ENABLE'">正常</span>
            <span v-else>停用</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column prop="updateTime" label="更新时间" />
      </el-table>
    </div>
    <FtDialog v-model="visible" title="添加用户" width="30%" :ok-handle="() => { onConfirm(userFormRef) }" @cancel="closeDialog">
      <div>
        <el-form ref="userFormRef" :model="userForm" label-width="auto" style="max-width: 600px">
          <el-form-item
            label="登录名："
            prop="username"
            :rules="[{
              required: true,
              message: '输入登录名',
              trigger: ['blur', 'change'],
            }]"
          >
            <el-input v-model="userForm.username" placeholder="登录名" />
          </el-form-item>
          <el-form-item
            label="用户名："
            prop="nickname"
            :rules="{
              required: true,
              message: '输入用户名',
              trigger: 'blur',
            }"
          >
            <el-input v-model="userForm.nickname" placeholder="用户名" />
          </el-form-item>
          <div v-if="!userForm.id">
            <el-form-item
              label="密码："
              prop="password"
              :rules="{
                required: true,
                message: '输入密码',
                trigger: 'blur',
              }"
            >
              <el-input v-model="userForm.password" type="password" placeholder="密码" />
            </el-form-item>
            <el-form-item
              label="确认密码："
              prop="confirmPassword"
              :rules="{
                required: true,
                message: '输入密码',
                trigger: 'blur',
              }"
            >
              <el-input v-model="userForm.confirmPassword" type="password" placeholder="确认密码" />
            </el-form-item>
          </div>
          <el-form-item
            label="是否管理员："
          >
            <el-checkbox v-model="userForm.isAdmin" size="small" />
          </el-form-item>
        </el-form>
      </div>
    </FtDialog>
  </div>
</template>

<style lang="css" scoped>
  .footer{
    display: flex;
    justify-content: center;
    width: 35vw;
  }
</style>
