<script setup lang="tsx">
import { Form, FormSchema } from '../../../../components/Form'
import { useForm } from '../../../../hooks/web/useForm'
import { PropType, reactive, watch, ref, unref, nextTick, toRaw } from 'vue'
import { useValidator } from '../../../../hooks/web/useValidator'
import { ElTree } from 'element-plus'
import { getAuthTree } from '../../../../api/system-config/role'

const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null
  }
})

const treeRef = ref<typeof ElTree>()

const formSchema = ref<FormSchema[]>([
  // {
  //   field: 'roleName',
  //   label: t('role.roleName'),
  //   component: 'Input'
  // },
  // {
  //   field: 'roleCode',
  //   label: '角色编码',
  //   component: 'Input'
  // }
  // {
  //   field: 'status',
  //   label: t('menu.status'),
  //   component: 'Select',
  //   componentProps: {
  //     options: [
  //       {
  //         label: t('userDemo.disable'),
  //         value: 0
  //       },
  //       {
  //         label: t('userDemo.enable'),
  //         value: 1
  //       }
  //     ]
  //   }
  // }
  {
    field: 'menu',
    label: '部门分配',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: () => {
          return (
            <>
              <div class="flex w-full">
                <div class="flex-1">
                  <ElTree
                    ref={treeRef}
                    show-checkbox
                    node-key="id"
                    highlight-current
                    expand-on-click-node={false}
                    check-on-click-node
                    data={treeData.value}
                    props={{ label: 'name' }}
                    onCheck={checktChange}
                  >
                    {{
                      default: (data) => {
                        return <span>{data.data.name}</span>
                      }
                    }}
                  </ElTree>
                </div>
              </div>
            </>
          )
        }
      }
    }
  }
])

//     <div class="flex-1">
// {unref(currentTreeData) && unref(currentTreeData)?.permissionList ? (
//     <ElCheckboxGroup v-model={unref(currentTreeData).meta.permission}>
//       {unref(currentTreeData)?.permissionList.map((v: any) => {
//         return <ElCheckbox value={v.value}>{v.label}</ElCheckbox>
//       })}
//     </ElCheckboxGroup>
// ) : null}
// </div>

// const currentTreeData = ref()
// const nodeClick = (treeData: any) => {
//   console.log(treeData)
//   currentTreeData.value = treeData
// }

const checktChange = (treeData, two) => {
  console.log(treeData)
  console.log(two)
}

const rules = reactive({
  roleName: [required()],
  role: [required()],
  status: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const treeData = ref([])
const getMenuList = async () => {
  console.log(props.currentRow)
  const res = await getAuthTree({ appRoleId: toRaw(props.currentRow)?.appRoleId })
  console.log(res)
  if (res) {
    treeData.value = res.data
    if (!props.currentRow) return
    await nextTick()
    // const checked: any[] = []
    recursiveRoleTree(treeData.value)
    // eachTree(props.currentRow.menu, (v) => {
    //   checked.push({
    //     id: v.id,
    //     permission: v.meta?.permission || []
    //   })
    // })
    // eachTree(treeData.value, (v) => {
    //   const index = findIndex(checked, (item) => {
    //     return item.id === v.id
    //   })
    //   if (index > -1) {
    //     const meta = { ...(v.meta || {}) }
    //     meta.permission = checked[index].permission
    //     v.meta = meta
    //   }
    // })
    // for (const item of checked) {
    //   unref(treeRef)?.setChecked(item.id, true, false)
    // }
    // unref(treeRef)?.setCheckedKeys(
    //   checked.map((v) => v.id),
    //   false
    // )
  }
}
getMenuList()

const recursiveRoleTree = (arr) => {
  arr.forEach((item) => {
    if (item.children && item.children.length > 0) {
      recursiveRoleTree(item.children)
    } else {
      if (item?.checked) {
        unref(treeRef)?.setChecked(item.id, true, false)
      }
    }
  })
}

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    const checkedKeys = unref(treeRef)?.getCheckedKeys() || []
    // const data = filter(unref(treeData), (item: any) => {
    //   return checkedKeys.includes(item.id)
    // })
    formData.menu = checkedKeys || []
    console.log(formData)
    return formData
  }
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
</template>
