import React, { useEffect, useMemo, useState } from 'react'
import { connect } from 'dva'
import { Row, Col, Card, Spin, Checkbox, Button, Popconfirm, Input, notification } from 'antd'
import { fetch, apis } from '@/utils/request'
import router from 'umi/router'
import ModuleCard from './components/ModuleCard'

const getRoleMenus = fetch(apis.role.buttonAndMenuList)
const saveRoleMenus = fetch(apis.role.updateAuthMenu)

const Role = props => {
  const [loading, setLoading] = useState(false)
  const [roleName, setRoleName] = useState()
  const [checkList, setCheckList] = useState({})

  const roleId = props.location.query.id

  const modules = useMemo(() => {
    if (!props.user || !props.user.menus || !props.user.menus.length) {
      return []
    }

    return props.user.menus.reduce((acc, menu) => {
      const menuRoot = acc[menu.menuRoot] || {}

      const isModule = menu.menuId === menu.menuRoot
      if (isModule) {
        return {
          ...acc,
          [menu.menuRoot]: {
            ...menuRoot,
            ...menu
          }
        }
      } else {
        return {
          ...acc,
          [menu.menuRoot]: {
            ...menuRoot,
            children: (menuRoot.children || []).concat(menu)
          }
        }
      }

    }, {})

  }, [props.user])

  const handleCheck = moduleId => checkArr => {
    checkList[moduleId] = checkArr
    setCheckList({...checkList})
  }

  const handleSubmit = () => {
    if (!roleName) {
      notification.warn({ message: '请填写角色名称' })
      return
    }

    const ids = Object.keys(checkList).reduce((acc, key) => {
      const arr = checkList[key] || []
      return [
        ...acc,
        ...arr
      ]
    }, [])

    setLoading(true)
    saveRoleMenus({data: {
      id: roleId,
      name: roleName,
      sysMenu: ids.map(menuId => ({ menuId })),
      sysButton: []
    }}).then(res => {
      setLoading(false)
      notification.success({ message: '操作成功' })
    }).catch(e => console.error(e) || setLoading(false))
  }

  useEffect(() => {
    if (roleId) {
      setLoading(true)
      getRoleMenus({urlData: {id: roleId}}).then(res => {
        if (res) {
          const roleMenus = res.sysMenuList || []
          setRoleName(res.roleName)
          setCheckList(roleMenus.reduce((acc, menu) => {
            const moduleId = menu.menuRoot // menu.parentCode - 0 === -1 ? menu.menuId : menu.menuRoot
            const menuRoot = acc[moduleId] || []

            return {
              ...acc,
              [moduleId]: menuRoot.concat(menu.menuId)
            }
          }, {}))
        }
        setLoading(false)
      }).catch(e => console.error(e) || setLoading(false))
    }
  }, [roleId])

  return (
    <div>
      <Spin spinning={loading}>
        <Row style={{marginBottom: 32}}>
          <Col span={12}>
            <div style={{display: 'flex'}}>
              <div style={{flex: 'none'}}>角色名称:</div>
              <div style={{flex: 'none', marginLeft: 16}}><Input value={roleName} onChange={e => setRoleName(e.target.value)} placeholder="请填写角色名称" required /></div>
            </div>
          </Col>
          <Col span={12}>
            <div style={{textAlign: 'right'}}>
              <Popconfirm
                title="确定进行提交操作?"
                onConfirm={handleSubmit}
              >
                <Button type="primary" icon="audit">提交</Button>
              </Popconfirm>
              <Button icon="arrow-left" onClick={() => router.go(-1)} style={{marginLeft: 16}}>返回</Button>
            </div>
          </Col>
        </Row>
      {
        Object.keys(modules).map(modlueId => {
          return (
            <ModuleCard
              key={modlueId}
              module={modules[modlueId]}
              value={checkList[modlueId]}
              onChange={handleCheck(modlueId)}
            />
          )
        })
      }
      </Spin>
    </div>
  )
}

export default connect(s => ({user: s.user.currentUser}))(Role)
