<!--
 * @Author: xiejiang
 * @Date: 2024-12-01 10:26:11
 * @LastEditors: xiejiang
 * @LastEditTime: 2024-12-05 14:26:50
 * @Description: 新增编辑角色
 * Copyright（c）2024 by 好老师教育科技有限公司 All right Reserved.
-->
<template>
  <Drawer
    :drawer-visible="drawerVisible"
    width="480px"
    :title="title"
    :loading="submitLoading"
    confirm-btn-text="保存"
    :cancel-btn="false"
    @confirm="handleConfirm"
    @close="close"
  >
    <t-form ref="formRef" label-align="top" class="login-form" :rules="rules" :data="formData">
      <t-form-item label="角色名称" name="roleName">
        <t-input maxlength="20" v-model="formData.roleName" placeholder="请输入角色姓名"> </t-input>
      </t-form-item>
      <t-form-item label="角色描述" name="description">
        <t-textarea :maxlength="200" v-model="formData.description" placeholder="请输入角色备注"> </t-textarea>
      </t-form-item>
    </t-form>
  </Drawer>
</template>

<script setup lang="ts" name="user-edit">
import { FormProps, FormInstanceFunctions } from 'tdesign-vue-next'
import { ReqRole, ResRoleList } from '@/api/interface/user-roles/index'
import { postRoleAddUpd } from '@/api/modules/user-roles/index'

const drawerVisible = ref(false)
const submitLoading = ref(false)

const formRef = useTemplateRef<FormInstanceFunctions>('formRef')
const formData = reactive<ReqRole>({
  description: '',
  roleId: '',
  roleName: ''
})

const rules: FormProps['rules'] = {
  roleName: [
    {
      required: true,
      message: '请填写角色名称！',
      trigger: 'blur'
    }
  ]
}

const title = ref('新增角色')
const open = (val: ResRoleList) => {
  drawerVisible.value = true
  if (val) {
    title.value = '编辑角色'
    for (const key in formData) {
      if (Object.prototype.hasOwnProperty.call(val, key)) {
        ;(formData as any)[key] = val[key]
      }
    }
  } else {
    title.value = '新增角色'
  }
}
const close = () => {
  formRef.value?.reset()
  drawerVisible.value = false
}

// 确认
const handleConfirm = () => {
  formRef.value?.validate().then(val => {
    if (val === true) {
      submitLoading.value = true
      postRoleAddUpd(formData)
        .then(() => {
          emit('success')
          close()
        })
        .finally(() => {
          submitLoading.value = false
        })
    }
  })
}

const emit = defineEmits<{
  success: []
}>()

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