import { addRoleMenu, delRoleMenuByRoleID, updateRoleMenu } from '@/services/permission'
import { isNullOrUnDef } from '@/utils/is'
import { DeleteOutlined, FormOutlined, PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons'
import { ModalForm, ProFormText } from '@ant-design/pro-form'
import type { ProFormInstance } from '@ant-design/pro-form'
import type { TreeDataNode } from 'antd'
import { Button, Input, Tree, message, Popconfirm } from 'antd'
import { useRef, useState } from 'react'
import { useRequest } from '@umijs/max'
const { DirectoryTree } = Tree
import './index.less'

export enum RoleType {
  SYSTEM = 'system', // 超级管理员
  SYSTEM_NORMAL = 'systemNormal', // 普通用户
  NORMAL = 'normal' // 手动添加的角色
}

type RoleLeftMenuProps = {
  defaultActiveRole?: string
  onSelect: (...args) => void
  showDelIcon: boolean
  onReloadStaff: () => void
}

const RoleLeftMenu: React.FC<RoleLeftMenuProps> = ({
  defaultActiveRole,
  onSelect,
  menuRoles,
  showDelIcon,
  onReloadStaff
}) => {
  const formRef = useRef<ProFormInstance>(null)
  const [activeID, setActiveID] = useState<Nullable<string>>(null)

  const { run: tryAddRole } = useRequest((params: API.CreateRoleParams) => addRoleMenu(params), {
    manual: true,
    onSuccess: () => {
      onReloadStaff()
    }
  })

  const { run: tryUpdateRole } = useRequest(
    (params: Partial<API.UpdateRoleParams>) => updateRoleMenu(params),
    {
      manual: true,
      onSuccess: () => {
        message.success('修改成功')
        onReloadStaff()
      }
    }
  )

  const { run: tryDelRole } = useRequest((ID: string) => delRoleMenuByRoleID({ ID }), {
    manual: true,
    onSuccess: () => {
      message.success('删除成功')
      onReloadStaff()
    }
  })
  const handleOnFocus = async (
    e: React.FocusEvent<HTMLInputElement> | React.KeyboardEvent<HTMLElement>,
    oldTitle: string,
    ID: string
  ) => {
    const val = e.currentTarget.value || e.currentTarget.nodeValue
    if (val !== oldTitle) {
      await tryUpdateRole({ ID, name: val })
    }
    setActiveID(null)
  }

  function renderTreeNode(tree) {
    return tree.map((item: TreeDataNode & { roleType: string }) => {
      // 系统管理员，系统用户不能删除、编辑
      const newItem = {
        ...item,
        title: [RoleType.SYSTEM, RoleType.SYSTEM_NORMAL].includes(item.roleType) ? (
          <span className="department-node py-1">{item.title}</span>
        ) : (
          <div className="department-node py-1">
            {item.key === activeID ? (
              <Input
                autoFocus
                defaultValue={item.title}
                bordered={false}
                size="small"
                style={{ width: '70%', backgroundColor: 'white' }}
                onBlur={e => handleOnFocus(e, item.title, item.key)}
                onPressEnter={e => handleOnFocus(e, item.title, item.key)}
              />
            ) : (
              <div className="title">{item.title}</div>
            )}
            <div className="extra">
              <FormOutlined className="pr-2" onClick={() => setActiveID(item.key)} />
              <Popconfirm
                disabled={!showDelIcon}
                title="确认删除吗？"
                onText="确认"
                cancelText="取消"
                onConfirm={() => tryDelRole(item.key)}
                icon={<QuestionCircleOutlined style={{ color: 'red' }} />}>
                <DeleteOutlined
                  onClick={() => {
                    !showDelIcon && message.warning('请先移除该角色下的所有用户')
                  }}
                />
              </Popconfirm>
            </div>
          </div>
        )
      }
      if (newItem.children?.length) {
        newItem.children = renderTreeNode(newItem.children)
      }
      return newItem
    })
  }

  const virtualHeight = document.getElementById('role-list')?.clientHeight

  if (!menuRoles?.length || isNullOrUnDef(defaultActiveRole)) return null
  return (
    <div className="min-w-54 rounded-3xl" style={{ height: 'calc(100vh - 122px)', background: '#ffffff' }}>
      <div className="menu-title flex items-center justify-around">
        <span className="py-4 text-base text-opacity-85">角色列表</span>
        <ModalForm
          title="新建角色"
          width="30%"
          onVisibleChange={visible => !visible && formRef.current?.resetFields()}
          layout="horizontal"
          isKeyPressSubmit
          trigger={
            <Button size="small" type="primary" ghost>
              <PlusOutlined />
              添加
            </Button>
          }
          onFinish={async values => {
            await tryAddRole(values)
            message.success('添加成功')
            return true
          }}>
          <ProFormText name="name" label="角色名称" rules={[{ required: true, message: '请输入角色名' }]} />
        </ModalForm>
      </div>
      <div
        id="role-list"
        className="p-4 bg-white rounded-b-20px"
        style={{ height: 'calc(100% - 1rem*2 - 20px)' }}>
        {menuRoles.length ? (
          <DirectoryTree
            itemHeight={32}
            height={virtualHeight - 32}
            defaultSelectedKeys={[menuRoles[0]?.key]}
            onSelect={(keys, node) => onSelect(keys[0], node.node.roleType)}
            showIcon={false}
            treeData={renderTreeNode(menuRoles)}
          />
        ) : null}
      </div>
    </div>
  )
}

export default RoleLeftMenu
