<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #menu="{ model, field }">
        <BasicTree
          v-model:value="model[field]"
          :treeData="treeData"
          :defaultExpandLevel="1"
          :fieldNames="{ title: 'label', key: 'id' }"
          checkable
          toolbar
          title="菜单分配"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue'
  import { BasicForm, useForm } from '/@/components/Form/index'
  import { formSchema } from './role.data'
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer'
  import { BasicTree, TreeItem } from '/@/components/Tree'
  import { getPermissions, addRoles, getRolesInfo, editRoles } from '/@/api/sys/user'
  const emits = defineEmits(['success', 'register'])
  const isUpdate = ref(false)
  const treeData = ref<TreeItem[]>([])
  const getTitle = computed(() => (!isUpdate.value ? '新增角色' : '编辑角色'))
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
  })
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields()
    setDrawerProps({ confirmLoading: false })
    // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
    if (unref(treeData).length === 0) {
      treeData.value = (await getPermissions()) as any as TreeItem[]
    }
    isUpdate.value = data?.isUpdate
    if (unref(isUpdate)) {
      const res = await getRolesInfo(data.id)
      await setFieldsValue({
        ...res,
        permission_ids: res.permissions,
      })
    }
  })

  const handleSubmit = async () => {
    try {
      const values = await validate()
      setDrawerProps({ confirmLoading: true })
      if (values.id) {
        // 修改
        await editRoles(values.id, values)
      } else {
        // 新增
        await addRoles(values)
      }
      closeDrawer()
      emits('success')
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }
</script>
