import React, { useEffect } from 'react'
import { Button, message, Tree, TreeSelect, Form, Popconfirm } from 'antd'
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons'
import consts from '@/consts'
import { addDepartment, delDepartment } from '@/services/hr'
import { connect, useAccess } from 'umi'
import { ModalForm, ProFormText } from '@ant-design/pro-form'
import './index.less'
const { DirectoryTree } = Tree

const RoleMenu = props => {
  const { dispatch, departments = [], onSelect, showType } = props
  const hasPerm = useAccess()?.validatePermByType('employee_del_department')
  const newList = [...departments]
  newList.unshift({
    children: [],
    id: '0',
    key: '0',
    isLeaf: false,
    name: '总全公司',
    title: '总全公司'
  })

  const initData = () => {
    dispatch({
      type: 'staff/fetchDepartments'
    })
  }

  const handleDelDepartment = async id => {
    const { code = -1 } = await delDepartment(id)
    if (code === consts.RET_CODE.SUCCESS) {
      message.success('删除成功')
      initData()
    }
  }

  function renderTreeNode(tree) {
    if (!hasPerm) return tree
    return tree.map(item => {
      const newItem = {
        ...item,
        title: (
          <div className="department-node">
            <div>{item.title}</div>
            <div className="extra">
              {showType ? (
                <Popconfirm
                  title="确认删除吗？"
                  onText="确认"
                  cancelText="取消"
                  onConfirm={() => handleDelDepartment(item.id)}>
                  <DeleteOutlined />
                </Popconfirm>
              ) : null}
            </div>
          </div>
        )
      }
      if (newItem.children?.length) {
        newItem.children = renderTreeNode(newItem.children)
      }
      return newItem
    })
  }

  const handleAddDepartment = async values => {
    const { code = -1 } = await addDepartment({ ...values })
    if (code === consts.RET_CODE.SUCCESS) {
      initData()
    }
  }

  useEffect(() => {
    if (!departments.length) {
      initData()
    }
  }, [])

  const saveActiveId = id => {
    if (onSelect) {
      onSelect(id)
    }
  }

  return (
    <div
      className="w-12rem rounded-4px"
      style={{
        height: `calc(100vh - 96px)`
      }}>
      <div className="p-4 pb-3 border-b-1 border-solid border-black border-opacity-10 bg-[#f7f9fa] flex justify-around items-center">
        <span className="text-[0.9375rem]">组织架构</span>
        {hasPerm && showType ? (
          <ModalForm
            title="创建部门"
            width="500px"
            trigger={
              <Button size="small" type="primary" ghost>
                <PlusOutlined />
                创建部门
              </Button>
            }
            onFinish={async values => {
              await handleAddDepartment(values)
              message.success('添加成功')
              return true
            }}>
            <ProFormText name="backstageMenuId" hidden />
            <ProFormText name="name" label="新增部门" rules={[{ message: '请输入部门名称' }]} />
            <Form.Item label="上级部门" name="parentId">
              <TreeSelect
                style={{ width: '100%' }}
                placeholder="请选择上司"
                treeDefaultExpandAll
                treeData={departments}
                allowClear
              />
            </Form.Item>
          </ModalForm>
        ) : null}
      </div>
      <div className="py-4 bg-white" style={{ height: 'calc(100% - 44px)' }}>
        {departments.length ? (
          <DirectoryTree
            multiple
            defaultExpandAll
            defaultSelectedKeys={['0']}
            onSelect={keys => saveActiveId(keys[0])}
            showIcon={false}
            treeData={renderTreeNode(newList)}
          />
        ) : null}
      </div>
    </div>
  )
}

export default connect(({ staff }) => ({
  departments: staff.departments
}))(RoleMenu)
