import { fetchRoleBgList, unLinkRoleBgAccount, fetchRoleBgStaffListByRoleId } from '@/services/permission'
import { DeleteOutlined } from '@ant-design/icons'
import { PageContainer } from '@ant-design/pro-layout'
import { Input, message, Popconfirm, Table, Tabs } from 'antd'
import { useState } from 'react'
import { useRequest } from '@umijs/max'
import RoleLeftMenu, { RoleType } from './components/RoleLeftMenu'
import PermTabs from './components/PermTabs'
import type { ColumnsType } from 'antd/lib/table'
import ConnectModal from './components/ConnectModal'
const { TabPane } = Tabs

const Role = () => {
  const [state, setState] = useState({
    activeTab: '1',
    currentRoleID: null,
    roleType: '',
    roleStaff: []
  })

  const [menuRoles, setMenuRoles] = useState([])
  const { run: tryGetRoleBgStaffList, loading: staffListLoading } = useRequest(
    (params: { roleID: string; search?: string }) =>
      fetchRoleBgStaffListByRoleId({ pageNo: 1, pageSize: 214000, ...params }),
    {
      manual: true,
      onSuccess: result => {
        setState({ ...state, roleStaff: result.items })
      }
    }
  )
  const { run: tryUnLinkRoleBgAccount } = useRequest(
    (params: API.LinkAccountParams) => unLinkRoleBgAccount(params),
    {
      manual: true,
      onSuccess: async () => {
        message.success('移除成功')
        await tryGetRoleBgStaffList({ roleID: state.currentRoleID })
      }
    }
  )

  const onSelect = (currentRoleID: string, roleType: string) => {
    if (state.currentRoleID === currentRoleID) return
    setState({ ...state, currentRoleID, roleType })
    tryGetRoleBgStaffList({ roleID: currentRoleID })
  }

  const { run: tryFetchRoleBgListByMenu } = useRequest(fetchRoleBgList, {
    onSuccess: result => {
      setMenuRoles(
        result.map(item => ({
          key: item.ID,
          title: item.name,
          roleType: item.roleType
        }))
      )

      result?.length && onSelect?.(state.currentRoleID ?? result[0]?.ID, result[0]?.roleType)
    }
  })

  const delRoleValidFn = (ID: string) => {
    if (state.roleStaff.length) {
      return message.warning('请先移除该角色下的所有用户')
    }
    tryDelRoleBg(ID)
  }
  const columns: ColumnsType<API.MenuByRoleIdItem> = [
    {
      title: '账号',
      dataIndex: 'account',
      width: '15%'
    },
    {
      title: '姓名',
      dataIndex: 'name',
      width: '15%'
    },
    {
      title: '业务主体',
      dataIndex: 'institutionID',
      width: '35%',
      render: (_, record) => record.institution?.name
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: '10%',
      render: (_, record) =>
        ![RoleType.SYSTEM].includes(state.roleType) && (
          <Popconfirm
            title="确定移除吗？"
            okText="确定"
            cancelText="取消"
            onConfirm={() => {
              tryUnLinkRoleBgAccount({ ID: state.currentRoleID, accountID: record.ID })
            }}>
            <span className="text-hex-fd3995 cursor-pointer hover:text-hex-e7026e">
              <DeleteOutlined />
            </span>
          </Popconfirm>
        )
    }
  ]

  const wrapHeight = document.querySelector('.ant-pro-page-container-warp')?.clientHeight || 0

  return (
    <PageContainer title={false}>
      <div className="h-full w-full flex flex-row">
        <RoleLeftMenu
          defaultActiveRole={state.currentRoleID ?? menuRoles[0]?.ID}
          onSelect={onSelect}
          menuRoles={menuRoles}
          showDelIcon={!state.roleStaff.length}
          onReloadStaff={() => tryFetchRoleBgListByMenu()}
          delRoleValidFn={delRoleValidFn}
        />
        <div className="w-6/7 ml-8 bg-white p-4 rounded-20px relative">
          <Tabs
            tabBarExtraContent={{
              right: state.activeTab === '1' && (
                <div className="flex items-center children:mx-1">
                  <Input.Search
                    placeholder="请输入账号或姓名"
                    onSearch={value => tryGetRoleBgStaffList({ roleID: state.currentRoleID, search: value })}
                  />
                  {state.currentRoleID && state.roleType !== RoleType.SYSTEM && (
                    <ConnectModal
                      dataId={state.currentRoleID}
                      onReload={() => tryGetRoleBgStaffList({ roleID: state.currentRoleID })}
                    />
                  )}
                </div>
              )
            }}
            defaultActiveKey="1"
            onChange={key => setState({ ...state, activeTab: key })}>
            <TabPane tab="用户列表" key="1">
              <Table<API.RoleStaffItem>
                loading={staffListLoading}
                columns={columns}
                scroll={{
                  y: document.body.clientHeight - (285 + wrapHeight)
                }}
                dataSource={state.roleStaff}
                rowKey={row => row.ID}
              />
            </TabPane>
            <TabPane tab="功能权限" key="2">
              <PermTabs
                currentPermData={{
                  ID: state.currentRoleID,
                  roleType: state.roleType
                }}
              />
            </TabPane>
          </Tabs>
        </div>
      </div>
    </PageContainer>
  )
}

export default Role
