import React, { useEffect, useState } from 'react'
import { Card } from 'antd'
import MenuItem from './MenuItem'

const gridStyle = {
  width: '25%',
  textAlign: 'center',
};

export default props => {
  // 当前 module 的所有 id , 包含 moduleId
  const [allIds, setAllIds] = useState([])
  // 当前 module 的选中列表
  const [checkList, setCheckList] = useState([])
  // 是否全选
  const [checkAll, setCheckAll] = useState(false)
  // 是否选择部分
  const [indeterminate, setIndeterminate] = useState(false)

  // 模块的勾选, 就是全选，全不选的操作
  const handleModuleChange = (moduleId, checked) => {
    const list = checked ? [...allIds] : []
    props.onChange(list)
  }

  const handleMenuCheck = (menuId, checked) => {
    const list = checkList.filter(x => x !== menuId)
    if (checked) {
      list.push(menuId)
    }

    props.onChange(list)
  }

  useEffect(() => {
    //
    const checkedArr = props.value || []
    setCheckList(checkedArr.concat(checkedArr.includes(props.module.menuId) ? [props.module.menuId] : []))
    
    // 不单单是这一个模块的
    const children = props.module.children || []
    if (checkedArr.length >= children.length) {
      setCheckAll(true)
      setIndeterminate(false)
    } else {
      setCheckAll(false)
      setIndeterminate(checkedArr.length > 0)
    }

    const allIdList = [props.module.menuId].concat(children.map(x => x.menuId))
    setAllIds(allIdList)
    
  }, [props.value, props.module])


  return (
    <div style={{marginBottom: 16}}>
      <Card title={<MenuItem checked={checkAll} indeterminate={indeterminate} menu={props.module} onChange={handleModuleChange} />} >
      {
        (props.module.children || []).map(menu => {
          const menuChecked = checkList.includes(menu.menuId)
          return (
            <Card.Grid key={menu.menuId} style={gridStyle}>
              <MenuItem menu={menu} checked={menuChecked} onChange={handleMenuCheck} />
            </Card.Grid>
          )
        })
      }
      </Card>
    </div>
  )
}
