<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'

import { createAdmin, getRole, saveAdmin } from '#/api'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '添加',
  },
  diaData: {
    type: Object,
    default: () => ({}),
  },
})
const emits = defineEmits(['update:modelValue', 'onRefresh'])

const show = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emits('update:modelValue', val)
  },
})

const roleOp = ref<
  {
    label: string
    value: string
  }[]
>([])
const _formData = {
  id: null,
  nickName: '',
  account: '',
  password: '',
  career: null,
  roleIds: [],
  email: null,
  status: 0,
}
const formRef = ref<FormInstance | undefined>()
const formData = reactive<Record<string, any>>({
  ..._formData,
})

const rules = reactive<FormRules>({
  nickName: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  account: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
  roleIds: [
    { type: 'array', required: true, message: '角色不能为空', trigger: 'blur' },
  ],
})

function onOpen() {
  onClear()
  if (props.diaData.id) {
    for (const i in formData) {
      formData[i] = props.diaData[i]
    }
    formData.password = null
    formData.roleIds = props.diaData.roleIds.split(',')
  }
}

async function handleSave() {
  await formRef.value?.validate((valid) => {
    if (valid) {
      let fn = createAdmin
      if (formData.id) {
        fn = saveAdmin
      }
      fn(formData).then(() => {
        show.value = false
        onClear()
        emits('onRefresh')
      })
    }
  })
}

function onClear() {
  Object.assign(formData, _formData)
}

onMounted(() => {
  getRole().then((res) => {
    roleOp.value = res.records.map((i: Record<string, any>) => ({
      label: i.name,
      value: i.id,
    }))
  })
})
</script>

<template>
  <el-dialog
    v-model="show"
    width="30vw"
    :title="title"
    class="box"
    destroy-on-close
    @open="onOpen"
  >
    <el-form ref="formRef" label-width="80px" :model="formData" :rules="rules">
      <el-form-item label="用户名" prop="nickName">
        <el-input v-model="formData.nickName" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="账号" prop="account">
        <el-input v-model="formData.account" placeholder="请输入" />
      </el-form-item>
      <!-- password -->
      <el-form-item
        label="密码"
        :prop="diaData.id ? '' : 'password'"
        show-password
      >
        <el-input
          v-model="formData.password"
          type="password"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="职位" prop="career">
        <el-input v-model="formData.career" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="角色" :prop="diaData.id ? '' : 'roleIds'">
        <el-select
          v-model="formData.roleIds"
          placeholder="请选择"
          style="width: 100%"
          multiple
          collapse-tags
          collapse-tags-tooltip
        >
          <el-option
            v-for="item in roleOp"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="formData.email"
          type="password"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="状态">
        <Switch
          v-model="formData.status"
          :inactive-value="1"
          :active-value="0"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="handleSave"> 保存 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped></style>
