<template>
  <popup
    v-model="showDialog"
    :title="popupTitle"
    width="520px"
    :close-on-click-modal="false"
    :confirmLoading="isLoading"
    @confirm="handleSubmit"
  >
    <el-form ref="formRef" :model="formData" label-width="90px" :rules="formRules" v-loading="isLoading">
      <el-form-item label="账号" prop="account">
        <el-input v-model="formData.account" placeholder="请输入账号" clearable />
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <div>
          <material-picker v-model="formData.avatar" :limit="1" />
          <div class="text-base text-info leading-normal mt-1.5">建议尺寸：1:1，支持jpg，jpeg，png格式</div>
        </div>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称" clearable />
      </el-form-item>
      <el-form-item label="角色" prop="role_id" v-if="formData.is_admin != 1">
        <el-select class="flex-1" v-model="formData.role_id" multiple placeholder="请选择角色" clearable>
          <el-option v-for="(item, index) in optionsData" :key="index" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" show-password clearable placeholder="请输入密码" />
      </el-form-item>
      <el-form-item label="确认密码" prop="password_confirm">
        <el-input v-model="formData.password_confirm" show-password clearable placeholder="请输入确认密码" />
      </el-form-item>
      <el-form-item label="管理员状态" prop="disable" v-if="formData.is_admin != 1">
        <el-radio-group v-model="formData.disable">
          <el-radio :value="0">启用</el-radio>
          <el-radio :value="1">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
  </popup>
</template>

<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { adminAdd, adminDetail, adminEdit } from '@/api/permission/admin'
import { roleOptions } from '@/api/permission/role'

// 定义组件事件
const emit = defineEmits<{
  (event: 'success'): void
}>()

// 表单引用
const formRef = shallowRef<FormInstance>()
// 模式：add=新增，edit=编辑
const mode = ref<'add' | 'edit'>('add')
// 加载状态
const isLoading = ref(false)
// 是否显示弹窗
const showDialog = ref(false)
// 初始表单数据
const initialFormData = {
  id: '',
  account: '',
  name: '',
  role_id: [],
  avatar: '',
  password: '',
  password_confirm: '',
  disable: 0,
  is_admin: 0
}
// 表单数据
const formData = reactive<Record<string, any>>({ ...initialFormData })
// 角色列表
const optionsData = ref<any[]>([])
// 表单验证规则
const roleIdValidator = (rule: object, value: string, callback: any) => {
  if (formData.is_admin == 1) {
    callback()
  } else {
    if (formData.role_id.length) {
      callback()
    } else {
      callback(new Error('请选择角色'))
    }
  }
}
const passwordConfirmValidator = (rule: object, value: string, callback: any) => {
  if (formData.password || value) {
    if (!value) callback(new Error('请再次输入密码'))
    if (value !== formData.password) callback(new Error('两次输入密码不一致!'))
  }
  callback()
}
const formRules = computed(() => ({
  account: [
    {
      required: true,
      message: '请输入账号',
      trigger: ['blur', 'change']
    }
  ],
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: ['blur', 'change']
    }
  ],
  role_id: [
    {
      required: true,
      validator: roleIdValidator
    }
  ],
  password: [
    mode.value == 'add'
      ? {
          required: true,
          message: '请输入密码',
          trigger: ['blur', 'change']
        }
      : {}
  ],
  password_confirm: [
    mode.value == 'add'
      ? {
          required: true,
          message: '请输入确认密码',
          trigger: ['blur', 'change']
        }
      : {},
    {
      validator: passwordConfirmValidator,
      trigger: 'blur'
    }
  ]
}))
// 弹窗标题
const popupTitle = computed(() => {
  return mode.value == 'edit' ? '编辑管理员' : '新增管理员'
})

// 打开弹窗
const open = (type: 'add' | 'edit' = 'add') => {
  getRoleLists()
  mode.value = type
  showDialog.value = true
}
// 设置表单数据
const setFormData = async (id?: number) => {
  isLoading.value = true
  resetForm()
  if (id) {
    const data = await adminDetail({ id })
    Object.keys(formData).forEach((key: string) => {
      if (data[key] != undefined) formData[key] = data[key]
    })
  }
  isLoading.value = false
}
// 表单重置
const resetForm = () => {
  Object.assign(formData, initialFormData)
  formRef.value?.resetFields()
}
// 获取角色列表
const getRoleLists = async () => {
  roleOptions().then((res) => {
    optionsData.value = res || []
  })
}
// 提交表单
const handleSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      isLoading.value = true
      const submitEvent = mode.value === 'edit' ? adminEdit : adminAdd
      submitEvent(formData)
        .then(() => {
          isLoading.value = false
          showDialog.value = false
          ElMessage.success('操作成功')
          emit('success')
        })
        .catch(() => {
          isLoading.value = false
        })
    }
  })
}

defineExpose({
  open,
  setFormData
})
</script>
