import { fetchRoleBgStaffListByRoleId, linkRoleBgAccount } from '@/services/api/permission'
import { PlusOutlined } from '@ant-design/icons'
import { ModalForm, ProFormSelect } from '@ant-design/pro-form'
import { Button, message } from 'antd'
import { useEffect, useRef, useState } from 'react'
import type { ProFormInstance } from '@ant-design/pro-form'
import { useRequest } from '@umijs/max'

const ConnectModal = ({ dataId, onReload }) => {
  const formRef = useRef<ProFormInstance>(null)
  const [menuRoles, setMenuRoles] = useState([])
  const { run: tryGetRoleBgStaffList } = useRequest(
    (params: { roleID: string; search?: string }) =>
      fetchRoleBgStaffListByRoleId({ current: 1, pageSize: 214000, ...params }),
    {
      manual: true,
      onSuccess: result => {
        setMenuRoles(result.items)
      }
    }
  )
  const { run: tryConnectRoleBgAccount } = useRequest(
    (params: API.LinkAccountParams) => linkRoleBgAccount(params),
    {
      manual: true,
      onSuccess: async () => {
        await onReload()
      }
    }
  )
  useEffect(() => {
    tryGetRoleBgStaffList()
  }, [])
  return (
    <ModalForm
      formRef={formRef}
      title="添加用户"
      width="30%"
      onVisibleChange={visible => !visible && formRef.current?.resetFields()}
      layout="horizontal"
      trigger={
        <Button size="small" type="primary" ghost>
          <PlusOutlined />
          添加用户
        </Button>
      }
      onFinish={async values => {
        await tryConnectRoleBgAccount({ ...values, ID: dataId })
        message.success('添加成功')
        return true
      }}>
      <ProFormSelect
        label="角色名称"
        name="accountIDs"
        className="w-full"
        options={menuRoles?.map(item => ({ value: item.ID, label: item.name }))}
      />
    </ModalForm>
  )
}

export default ConnectModal
