import React, {Component, useEffect, useState} from 'react';
import {Button} from 'antd';
import {YIcon} from '@/icon';
import {YModal} from '@/modal';
import {YSelector} from '@/selector';
import {useDesktop} from './useDesktop';
import {useDesktopStore} from './useDesktopStore';
import {SortableComponent} from './desktop.sort';
import { 
  BlockStyle,
  BlockToolStyle,
  BlockContextStyle,
  FeatureListStyle,
} from './desktop.styles';



export const YDesktop: React.FC = () => {
  const [editDisable, setEditDisable] = useState(true);
  const {initMenus, toggleSelected, addFunctions} = useDesktop();
  const [state] = useDesktopStore();
  const [total, setTotal] = useState(0);
  const [visible, setVisible] = useState(false);


  const toggleEdit = () => {
    setEditDisable(!editDisable);
  }

  const onChange = (selected: string[]) => {
    toggleSelected(selected);
    setTotal(selected.length);
  }

  const showMenuModal = () => {
    initMenus();
    setVisible(true)
  }

  const hideMenuModal = () => {
    setVisible(false)
  }

  const addFunction = async () => {
    const res = await addFunctions(state.selected);
    if(res){
      hideMenuModal();
    }
  }

  return (
    <div>
      <BlockStyle>
        
        <BlockContextStyle>
         
          <BlockToolStyle>
            <h3>常用功能</h3>
            <Button type={editDisable ? 'text' : 'link'} onClick={toggleEdit}>
              <YIcon name="SettingOutlined" size="10" />
              <span>{editDisable ? '常用配置' : '退出配置'}</span>
            </Button>
          </BlockToolStyle>
          <FeatureListStyle>
            <SortableComponent editDisable={editDisable} onAdd={showMenuModal} />
          </FeatureListStyle>
          <YModal 
              title={`添加常用功能 (${state.selected.length}/12)`} 
              size="large" 
              bodyStyle={{padding: '0'}}
              onOk={addFunction}
              onCancel={hideMenuModal}
              visible={visible}
            >
              {
                state.menus.length ? (
                <YSelector 
                  dataSource={state.menus} 
                  mapKeys={{
                  'cloudCategoryId': 'value', 
                  'cloudCategoryName': 'label', 
                  'moduleList': 'children',
                  'moduleId': 'value',
                  'moduleName': 'label',
                  'resourceList': 'children',
                  'resourceId': 'value',
                  'resourceName': 'label',}}
                  titles={['云分类', '云模块', '菜单']}
                  onChange={onChange}
                  max={12}
                  selected={state.selected}
                />
              ) : null
              }
            </YModal>
        </BlockContextStyle>
      </BlockStyle>
    </div>
  )
};
