import * as React from 'react';
import { useState, useEffect, ErrorInfo, useMemo, Component } from 'react';
// import { Radio, Select, Box, Input } from '@alifd/next';
import { SettingTarget, CustomView } from '@alilc/lowcode-types';
import { event, project } from '@alilc/lowcode-engine';
import { Transfer, Button, Tree } from '@alifd/next';

const TreeNode = Tree.Node;
/**
 * 获取AutoComplete数据源
 * @param  {String}
 * @return {Array}
 */
const getVarableList = (): any[] => {
  const schema = project.exportSchema();
  console.log(123123, schema.componentsTree)
  const stateMap = schema.componentsTree[0]?.state;
  const dataSource = [];
  for (const key in stateMap) {
    if (Object.prototype.hasOwnProperty.call(stateMap, key) && key) {
      let thisvalue = stateMap[key]["value"]
      console.log(21312321, stateMap)
      let childobj = {}
      if (thisvalue && thisvalue.indexOf("{") == 0) {
        // thisvalue.replace(/\n/gm, '').split(,)
        childobj = JSON.parse(thisvalue.replace(/\n/gm, ''))
        //console.log(2312321, JSON.parse(thisvalue.replace(/\r\n/g,"").replace("\n","") ))
      }

      dataSource.push({
        label: key,
        key: key,
        value: key,
        children: Object.keys(childobj).length > 0 ? Object.keys(childobj).map(v => {
          return {
            label: v,
            key: v,
            value: `${key}.${v}`,
          }
        })
          : []
      });
    }
  }
  return dataSource
};
const treeDataSource = getVarableList()

const transferDataSource: Array = [];
function flatten(list = []) {
  list.forEach((item) => {
    transferDataSource.push(item);
    flatten(item.children);
  });
}
flatten(treeDataSource);

interface PageDataSetterProps {
  field?: SettingTarget;
  // 兼容 vision engine
  defaultValue: string;
  prop?: SettingTarget;
  onChange: Function;
  actions: string[];
  value: string;
  type: string;
  url?: 'string';
  responseFormatter?: Function;
}

const PageDataSetter = ({ field: propsField, prop, onChange, actions, value, type }: PageDataSetterProps) => {
  const field = propsField || prop;
  const [selected, setSelected] = useState([]);
  // const handleChange = (value, data, extra) => {
  //   setSelected(value);
  //   onChange(value)
  //   console.log(21234234, value, data, extra)
  // };
  useEffect(() => { 
    if(value){
      setSelected(value.selected); 
    }
 
  }, []);
  useEffect(()=>{
    onChange({
      selected
    })
  },[selected])
  const onCheck = (keys, info) => { };

  const getTreeDataSource = (dataSource = [], value) => {
    return dataSource.map(({ children, ...props }) => (
      <TreeNode
        {...props}
        disabled={props.disabled || value.includes(props.value)}
        key={props.value}
      >
        {getTreeDataSource(children, value)}
      </TreeNode>
    ));
  };

  return (
    <div>
      <Transfer
        defaultValue={selected}
        value={selected}
        dataSource={transferDataSource} 
        // onChange={handleChange}
        listStyle={{ width: '100px', height: '192px' }}
      >
        {({ position, onChange, value }) => {
          console.log("value,",value)
          if (position === 'left') {
            return (
              <Tree
                checkable
                editable
                style={{ padding: '4px' }}
                // checkedKeys={value}
                onCheck={(keys, extra) => {
                  const newValues = extra.checkedNodes.map((item) => item.props.value);
                  setSelected(keys)
                  onChange(position, newValues);
                }}
              >
                {getTreeDataSource(treeDataSource, selected)}
              </Tree>
            );
          }
        }}
      </Transfer>
    </div>
  );
};

PageDataSetter.defaultProps = {
  value: undefined,
  type: 'string',
  defaultValue: '',
  hasClear: false,
  placeholder: '请点击选择 Icon',
  onChange: () => undefined,
};

export default class extends Component<PageDataSetterProps> {
  render() {
    return <PageDataSetter {...this.props} />;
  }
}
