<script setup lang="ts">
import { StrAnyObj } from '@/typings'
import { editDataScopeApi, getDataScopeApi } from '@/api/system/role'
import AForm from '@/components/AForm/index.vue'
import { FormConfigType } from '@/components/AForm/type'
import DeptTreeSelect from '@/views/components/DeptTreeSelect/index.vue'

const dialogTitle = ref<string>('')
const dialogVisible = ref<boolean>(false)

const deptIdRef = ref<InstanceType<typeof DeptTreeSelect>>()

const formRef = ref<InstanceType<typeof AForm>>()
const formData = ref<StrAnyObj>({})

const formConfig: FormConfigType[] = [
  {
    prop: 'dataScope',
    label: '权限范围',
    type: 'select',
    clearable: false,
    option: [
      { key: 1, label: '全部' },
      { key: 2, label: '自定义' },
      { key: 3, label: '本部门及下级部门' },
      { key: 4, label: '本部门' },
      { key: 5, label: '本人' }
    ]
  },
  {
    prop: 'roleDept',
    label: '数据权限',
    type: 'slot',
    show: () => formData.value.dataScope === 2
  }
]

function open(data: StrAnyObj) {
  dialogVisible.value = true
  dialogTitle.value = `【${data.name}】分配数据权限`
  getDataScopeApi({ id: data.id }).then((resp) => {
    formData.value = resp
  })
  nextTick(() => deptIdRef.value?.load())
}

function formSubmit() {
  editDataScopeApi(formData.value).then(() => {
    ElMessage.success('修改成功')
    dialogVisible.value = false
  })
}

function formClosed() {
  formData.value = {}
}

defineExpose({ open })
</script>

<template>
  <a-dialog v-model="dialogVisible" :title="dialogTitle" @submit="formSubmit" @closed="formClosed">
    <a-form ref="formRef" v-model="formData" :config="formConfig" :span="24">
      <template #roleDept>
        <dept-tree-select ref="deptIdRef" v-model="formData.selectDeptIdList" :multiple="true" />
      </template>
    </a-form>
  </a-dialog>
</template>
