<script setup lang="ts">
import type { FormInstance } from 'antdv-next'
import apiSysRole from '@/api/modules/sysRole'
import apiSysMenu from '@/api/modules/sysMenu'

export interface Props { id?: number | string }
const props = withDefaults(defineProps<Props>(), { id: '' })

const loading = ref(false)
const formRef = useTemplateRef<FormInstance>('formRef')
const form = ref({
  id: props.id as number | string, role_name: '', role_key: '',
  role_sort: 0, status: '0', remark: '',
})

const rules = {
  role_name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  role_key: [{ required: true, message: '请输入角色标识', trigger: 'blur' }],
}

// Menu tree
const menuTree = ref<any[]>([])
const checkedMenuIds = ref<number[]>([])

onMounted(() => {
  apiSysMenu.tree().then((res: any) => { menuTree.value = res.data || [] })
  if (form.value.id !== '') getInfo()
})

function getInfo() {
  loading.value = true
  apiSysRole.detail(form.value.id as number).then((res: any) => {
    loading.value = false
    const d = res.data
    Object.assign(form.value, {
      role_name: d.role_name, role_key: d.role_key,
      role_sort: d.role_sort, status: d.status, remark: d.remark,
    })
    checkedMenuIds.value = d.menu_ids || []
  }).catch(() => { loading.value = false })
}

defineExpose({
  submit() {
    return new Promise<void>((resolve) => {
      formRef.value?.validate().then(() => {
        const data = { ...form.value, menu_ids: checkedMenuIds.value }
        apiSysRole.save(data).then(() => { faToast.success(form.value.id ? '编辑成功' : '新增成功'); resolve() })
      }).catch(() => {})
    })
  },
})

// Flatten tree to options for checkboxes
function flattenTree(tree: any[], prefix = ''): any[] {
  let result: any[] = []
  for (const item of tree) {
    result.push({ value: item.id, label: prefix + item.menu_name })
    if (item.children && item.children.length > 0) {
      result = result.concat(flattenTree(item.children, prefix + '　'))
    }
  }
  return result
}
const menuOptions = computed(() => flattenTree(menuTree.value))
</script>

<template>
  <div v-if="loading" class="flex-center py-12"><ASpin /></div>
  <div v-else>
    <AForm ref="formRef" :model="form" :rules="rules" :label-col="{ span: 5 }">
      <AFormItem label="角色名称" name="role_name"><AInput v-model:value="form.role_name" placeholder="请输入角色名称" /></AFormItem>
      <AFormItem label="角色标识" name="role_key"><AInput v-model:value="form.role_key" placeholder="请输入角色标识" /></AFormItem>
      <AFormItem label="排序" name="role_sort"><AInputNumber v-model:value="form.role_sort" class="w-full" /></AFormItem>
      <AFormItem label="状态" name="status"><ASelect v-model:value="form.status" :options="[{ value: '0', label: '正常' }, { value: '1', label: '停用' }]" /></AFormItem>
      <AFormItem label="备注" name="remark"><ATextarea v-model:value="form.remark" placeholder="请输入备注" :rows="2" /></AFormItem>
    </AForm>
    <div class="mt-4">
      <div class="text-sm font-medium mb-2">菜单权限</div>
      <ACheckboxGroup v-model:value="checkedMenuIds" :options="menuOptions" class="flex flex-col gap-1" />
    </div>
  </div>
</template>
