import { Cascader, CascaderProps } from '@/components/cascader'
import { useAtomValue } from 'jotai/index'
import { departTreeAtom } from '@/store/system/department.ts'
import { usePageStoreOptions } from '@/store'
import { Spin } from 'antd'
import { useTranslation } from '@/i18n.ts'

export interface DepartmentCascaderProps extends Omit<CascaderProps<any>, 'options'> {
    onChange?: (value: any) => void
}

const displayRender = (labels: string[]) => labels[labels.length - 1]

export const DepartmentCascader = (props: DepartmentCascaderProps) => {

    const { t } = useTranslation()
    const { data = [], isLoading } = useAtomValue(departTreeAtom, usePageStoreOptions())

    const onChange = (value) => {

        props?.onChange?.(value[value.length - 1])
    }

    return (
            <Spin spinning={isLoading} size={'small'}>
                <Cascader changeOnSelect={true} {...props as any}
                          fieldNames={{
                              label: 'name',
                              value: 'id',
                          }}
                          placeholder={t('component.DepartmentCascader.placeholder', '请选择部门')}
                          onChange={onChange}
                          displayRender={displayRender}
                          showCheckedStrategy={Cascader.SHOW_CHILD}
                          options={data as any}>
                </Cascader>
            </Spin>
    )
}