import EasyvScrollContainer from 'components/EasyvScrollContainer';
import EasyvTree from 'components/EasyvTree';
import React, { forwardRef, useImperativeHandle, useState } from 'react';
import { PasteOneComponentRef, PasteOneComponentType } from './type';
import { getChangedConfigByCheckedKeys } from './util';
import { Utils } from '@easyv/react-gui';
const { mergeStyleConfig } = Utils;
const PasteOneComponent = forwardRef<PasteOneComponentRef, PasteOneComponentType>((props, ref) => {
  const { onChangeCheckedAllStatus, comConfigList = [] } = props;
  const data = comConfigList[0];
  const { componentId, comConfigTreeData, sourceConfig, defaultAllKeys, copyedConfig } = data;
  const [checkedKeys, setCheckedKeys] = useState(defaultAllKeys || []);
  const [halfCheckedKeys, setHalfCheckedKeys] = useState([]);
  useImperativeHandle(
    ref,
    () => ({
      getUpdateConfig: () => {
        const selectedConfig = getChangedConfigByCheckedKeys(copyedConfig, checkedKeys.concat(halfCheckedKeys));
        return checkedKeys.length
          ? [
              {
                componentId,
                updateData: {
                  config: mergeStyleConfig(sourceConfig, selectedConfig)
                }
              }
            ]
          : [];
      },
      onCheckedAll: () => {
        if (checkedKeys.length === defaultAllKeys.length) {
          setCheckedKeys([]);
          setHalfCheckedKeys([]);
          onChangeCheckedAllStatus('全选');
        } else {
          setCheckedKeys(defaultAllKeys);
          setHalfCheckedKeys([]);
          onChangeCheckedAllStatus('取消全选');
        }
      }
    }),
    [checkedKeys, defaultAllKeys, comConfigTreeData, sourceConfig, componentId, halfCheckedKeys, copyedConfig]
  );

  const onCheck = (checkedKeys, info) => {
    setHalfCheckedKeys(info.halfCheckedKeys);
    setCheckedKeys(checkedKeys);
    onChangeCheckedAllStatus(checkedKeys.length === defaultAllKeys.length ? '取消全选' : '全选');
  };
  return (
    <EasyvScrollContainer>
      <EasyvTree defaultExpandAll={false} checkedKeys={checkedKeys} onCheck={onCheck} treeData={comConfigTreeData} selectable={false} />
    </EasyvScrollContainer>
  );
});
export default PasteOneComponent;
