import React, {ChangeEventHandler, Component, useEffect, useState} from 'react';
import * as R from 'ramda';
import {Checkbox, Menu, message} from 'antd';
import {YIcon} from '@/icon';
import {SelectorOption, YSelectorProps} from './selector.interface';
import {SelectorStyle, TitleStyle, EmptyStyle, MenuStyle} from './styles';
import { CheckboxChangeEvent } from 'antd/lib/checkbox';


const {SubMenu} = Menu;

const keysMap = (originKeys: Record<string, string>, data: any[], isLeaf= false) => {
  const result = data.map(item => {
    const keys = R.keys(originKeys);
    keys.map((key) => {
      if(item[key]){
        if(R.type(item[key]) === 'Array'){
          item[originKeys[key]] = keysMap(originKeys, item[key], true);
        } else {
          item[originKeys[key]] = item[key];
        }
      } else if(R.type(item[key]) === 'Boolean') {
        item[originKeys[key]] = item[key];
      }
    })
    item = R.omit(keys, item);
    item.isLeaf = isLeaf;
    return item;
  });
  return result;
}

export const YSelector: React.FC<YSelectorProps> = ({dataSource, mapKeys, titles, onChange, max, selected = []}) => {
  const [list, setList] = useState<SelectorOption[][]>(null as unknown as SelectorOption[][]);
  const [column, setColumn] = useState(0);
  const [selecteds, setSelecteds] = useState<string[]>(selected);

  const toggleSelect = (e: CheckboxChangeEvent, data: SelectorOption) => {
    const isSelected = e.target.checked;
    if(!isSelected){
      const index = selecteds.indexOf(data.value);
      selecteds.splice(index, 1);
    } else {
      if(selecteds.length < max){
        selecteds.push(data.value);
      } else {
        message.info(`数量已经达到上限${max}， 不能再选了`)
      }
      
    }
    setSelecteds(selecteds.slice());
    onChange && onChange(selecteds.slice())
  }

  const onClick = (data: SelectorOption, columnIndex: number) => {
    let newList = list;
    if(data.children && data.children.length){
      if(columnIndex >= column) {
        newList.push(data.children);
      } else {
        if(column - columnIndex > 1){
          newList.splice(columnIndex + 1, column - columnIndex);
          newList.push(data.children)
        } else {{
          newList[column] = data.children
        }}
        
      }
      setColumn(columnIndex + 1);
    }
    setList(newList.slice());
  }

  const getOption = (option: SelectorOption, column: number) => {
    const hasChildren = option.children && option.children.length;
    if(hasChildren){
      return (
        <Menu.Item key={option.value} onClick={() => onClick(option, column)}>
          {option.label}
          <YIcon name="RightOutlined" size={10} />
        </Menu.Item>
      )
    } else {
      return (
        <Menu.Item key={option.value}>
          <Checkbox 
            checked={selecteds.indexOf(option.value) >= 0} 
            disabled={option.isSelected} 
            onChange={(e: CheckboxChangeEvent) => toggleSelect(e, option)}
          >{option.label}</Checkbox>
        </Menu.Item>
      )
    }
    
  }

  const initData = (data: any[]) => {
    const res = keysMap(mapKeys, data);
    setList([res]);
  }

  useEffect(() => {
   if(dataSource && dataSource.length){
    initData(dataSource);
   } 
  }, [dataSource]);

  if(!list || !list.length) {
    return (
      <EmptyStyle description="抱歉，暂时没有数据！" />
    )
  }


  return (
    <SelectorStyle>
      {
        list.map((options: SelectorOption[], index: number) => (
          <div key={index}>
            <MenuStyle mode="vertical">
              <TitleStyle>{titles[index]}</TitleStyle>
              {
                options.length && options.map((option: SelectorOption) => getOption(option, index))
              }
            </MenuStyle>
          </div>
        ))
      }
    </SelectorStyle>
  )
}