import React, { useState, useEffect } from 'react'
import { PlusOutlined, DownOutlined } from '@ant-design/icons'
import { Button, message, Popconfirm, Popover, Input } from 'antd'
import { useRequest } from 'umi'
import {
  createRoleWithMenuId,
  fetchRoleListByMenuId,
  deleteRole,
  updateStaff
} from '@/services/user/api'
import { ModalForm, ProFormText } from '@ant-design/pro-form'

type RoleMenuProps = {
  menuId: string
  onSelect?: (id: string) => void
  itemCount?: number
}

const RoleMenu: React.FC<RoleMenuProps> = ({ menuId, onSelect, itemCount }) => {
  const [state, setState] = useState({
    value: ''
  })
  const [activeId, setActiveId] = useState('')
  const [menuRoles, setMenuRoles] = useState<API.MenuRoleItem[]>([])
  const { run: tryFetchMenuRoles } = useRequest((id: string) => fetchRoleListByMenuId(id), {
    manual: true,
    onSuccess: result => {
      setMenuRoles(result)
    }
  })

  const { run: tryDeleteRole } = useRequest(
    (id: string) => {
      if (activeId === id) {
        setActiveId('')
      }
      return deleteRole({ id })
    },
    {
      manual: true,
      onSuccess: () => {
        tryFetchMenuRoles(menuId)
      }
    }
  )
  const { run: tryUpdateStaff } = useRequest(
    (id: string, name: string) => {
      if (activeId === id) {
        setActiveId('')
      }
      return updateStaff({ id, name })
    },
    {
      manual: true,
      onSuccess: () => {
        message.success('修改成功')
        tryFetchMenuRoles(menuId)
      }
    }
  )

  const onChangeName = value => {
    setState({ ...state, name: value })
  }

  const { run: tryAddRole } = useRequest(
    (params: API.CreateRoleParams) => createRoleWithMenuId(params),
    {
      manual: true,
      onSuccess: () => {
        tryFetchMenuRoles(menuId)
      }
    }
  )
  useEffect(() => {
    tryFetchMenuRoles(menuId)
  }, [])

  const handleItemClick = (id: string) => {
    setActiveId(id)
    if (onSelect) {
      onSelect(id)
    }
  }

  return (
    <div className="h-full w-max-234px rounded-4px">
      <div className="p-4 border-b-1 border-solid border-black border-opacity-10 bg-[#f7f9fa] flex items-center justify-around">
        <span className="text-[0.9375rem]">角色列表</span>

        <ModalForm<{ name: string; backstageMenuId: string }>
          title="添加新的角色"
          width="500px"
          trigger={
            <Button size="small" type="primary" ghost>
              <PlusOutlined />
              创建角色
            </Button>
          }
          onFinish={async values => {
            await tryAddRole(values)
            message.success('添加成功')
            return true
          }}
          initialValues={{ backstageMenuId: menuId }}>
          <ProFormText name="backstageMenuId" hidden />
          <ProFormText name="name" rules={[{ required: true, message: '请输入角色名' }]} />
        </ModalForm>
      </div>
      <div className="p-4 bg-white" style={{ height: 'calc(100% - 1rem*2 - 20px)' }}>
        <ul className="p-0 m-0 list-none text-primary flex flex-col flex-1">
          {menuRoles.map(item => (
            <li
              key={item.id}
              className={[
                'flex justify-between items-center py-2 px-5 cursor-pointer',
                item.id === activeId ? 'scale-up-center' : ''
              ].join(' ')}
              onClick={() => handleItemClick(item.id)}>
              <span>{item.name}</span>
              <Popover
                placement="bottomRight"
                content={
                  <div className="popoverList">
                    <ul>
                      <Popconfirm
                        title={
                          <Input
                            placeholder="角色名称"
                            name="name"
                            onChange={e => onChangeName(e.currentTarget.value)}
                          />
                        }
                        okText="确认"
                        cancelText="取消"
                        onConfirm={() => tryUpdateStaff(item.id, state.name)}
                        icon="">
                        <li>编辑</li>
                      </Popconfirm>
                      <Popconfirm
                        title="确认删除吗？"
                        okText="确认"
                        cancelText="取消"
                        onConfirm={() => {
                          if (itemCount && itemCount !== 0) {
                            return message.warning('请先移除已经关联的员工')
                          }
                          return tryDeleteRole(item.id)
                        }}>
                        <li className="text-red-500">删除</li>
                      </Popconfirm>
                    </ul>
                  </div>
                }
                trigger="click">
                <DownOutlined />
              </Popover>
            </li>
          ))}
        </ul>
      </div>
    </div>
  )
}

export default RoleMenu
