import { Space, TreeSelect } from 'antd';
import type { TreeSelectProps } from 'antd';
import Level from '../CustomTree/Level';
import { useOptionLevel, useRelation } from '../CustomTree/hooks';
import { memo, useEffect, useMemo, useRef } from 'react';
import { useIntl } from 'umi';
import { findFromTree, formatPostData } from '../utils';

interface CustomTreeSelectProps extends TreeSelectProps {
  width?: string | number;
  isHaveLevel?: boolean;
}
const CustomTreeSelect = (props: CustomTreeSelectProps) => {
  const { formatMessage } = useIntl();
  const checkedValue = useRef<string[]>([]);
  const { width, isHaveLevel = false, treeData, onChange, fieldNames, ...otherProps } = props;
  const key = fieldNames?.value || 'value';
  const { expandedKeys, setDefaultExpandAll, onExpand, defaultExpandAll } = useOptionLevel({
    treeData,
    key,
  });

  const { checkStrictly, setCheckStrictly, getRemain } = useRelation({
    key,
    id: key,
  });

  const formatTreeDate = useMemo(() => {
    // @ts-ignore
    return formatPostData(treeData, (item) => {
      return {
        ...item,
        // children: item.children,
      };
    });
  }, [treeData]);

  useEffect(() => {
    if (checkedValue?.current?.join() !== props.value?.join()) {
      setCheckStrictly(false);
    }
  }, [props.value]);

  return (
    <TreeSelect
      style={{ width: width || '100%' }}
      treeCheckable={true}
      labelInValue={false}
      treeCheckStrictly={true}
      showCheckedStrategy={'SHOW_ALL'}
      treeExpandedKeys={expandedKeys}
      onTreeExpand={onExpand}
      onChange={(val, e, extra) => {
        const remain = getRemain(
          { checked: val?.map((item) => item.value) },
          {
            checked: extra.checked,
            node: findFromTree(formatTreeDate, { [key]: extra.triggerValue }),
          },
        );
        checkedValue.current = remain;
        // @ts-ignore
        onChange?.(remain);
      }}
      treeDefaultExpandAll={true}
      dropdownRender={(menu) => {
        return (
          <>
            <Space direction="vertical" style={{ width: '100%' }}>
              <Level checkStrictly={checkStrictly} setCheckStrictly={setCheckStrictly} />
              {isHaveLevel ? (
                <a onClick={() => setDefaultExpandAll(!defaultExpandAll)}>
                  {defaultExpandAll
                    ? formatMessage({ id: 'component.CustomTreeSelect.ExpandAll.true' })
                    : formatMessage({ id: 'component.CustomTreeSelect.ExpandAll.false' })}
                </a>
              ) : null}
              {menu}
            </Space>
          </>
        );
      }}
      treeData={treeData}
      fieldNames={fieldNames}
      {...otherProps}
    />
  );
};

export default memo(CustomTreeSelect);
