import { Key, useEffect, useState } from 'react'
import { LockFlag } from '#/enum'
import { toast } from 'sonner'
import { deleteUser, getUserListPage } from '@/api/services/user'
import { Button, Card, Col, Popconfirm, Row, Tag } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import type { ProColumns } from '@ant-design/pro-components'
import { ProTable } from '@ant-design/pro-components'
import { AddModal, AddModalProps } from './components/AddModal'
import DeptTreeSelect from './components/DeptTreeSelect'
import { IconButton, Iconify } from '@/components/icon'

const nameColorList = ['#71BC78', '#5BB4EB', '#F28CAE', '#ED9848', '#DB93DB']

export default function RolePage() {
  const [searchForm, setSearchForm] = useState({})
  const [page, setPage] = useState({ total: 0, currentPage: 1, pageSize: 20 })
  const [tableData, setTableData] = useState<API.UserListPageResult>([])
  const [isLoading, setIsLoading] = useState(false)

  const onDeptTreeSelect = (values: Key[]) => {
    setSearchForm((prev) => ({ ...prev, deptId: values[0] }))
  }

  const getList = async () => {
    setTableData([])
    setIsLoading(true)
    const res = await getUserListPage(
      Object.assign(
        {
          current: page.currentPage,
          size: page.pageSize
        },
        searchForm
      )
    )
    if (res) {
      setTableData(res.data.records)
      setPage((prev) => ({ ...prev, total: res.data.total }))
    }
    setIsLoading(false)
  }
  useEffect(() => {
    getList()
  }, [searchForm, page.currentPage, page.pageSize])

  const [addUserModalProps, setAddUserModalProps] = useState<AddModalProps>({
    show: false,
    onCancel: () => {
      setAddUserModalProps((prev) => ({ ...prev, show: false }))
    },
    getList: () => {
      getList()
    }
  })

  const editFn = (record: API.UserListPageResultItem) => {
    console.log(record)
  }
  const deleteFn = async (row: API.UserListPageResultItem) => {
    const res = await deleteUser(row.userId)
    if (res) {
      getList()
      toast.success('删除成功', {
        position: 'top-center'
      })
    }
  }

  const columns: ProColumns<API.UserListPageResultItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: 50
    },
    {
      title: '用户名',
      dataIndex: 'username',
      width: 160,
      render: (_, record, index) => {
        return (
          <div className='flex'>
            <div
              className='w-[40px] h-[40px] rounded-full mr-[8px] text-[#fff] text-center leading-[40px] text-[16px]'
              style={{ backgroundColor: nameColorList[index % 5] }}>
              <span>{record?.username?.slice(0, 1)?.toUpperCase() || '-'}</span>
            </div>
            <div className='ml-2 flex flex-col'>
              <span className='text-sm'>{record.username}</span>
              <span className='text-xs text-text-secondary'>{record.phone}</span>
            </div>
          </div>
        )
      }
    },
    {
      title: '姓名',
      dataIndex: 'realName',
      width: 100
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      width: 120,
      hideInTable: true
    },
    {
      title: '角色',
      dataIndex: 'roleList',
      width: 120,
      search: false,
      render: (_, record) => {
        return record.roleList.length === 1 ? (
          <Tag color='processing'>{record.roleList[0].roleName}</Tag>
        ) : (
          <div className='overflow-hidden text-ellipsis whitespace-nowrap'>
            {record.roleList.map((item) => {
              return (
                <Tag color='processing' key={item.roleId}>
                  {item.roleName}
                </Tag>
              )
            })}
          </div>
        )
      }
    },
    {
      title: '状态',
      dataIndex: 'lockFlag',
      width: 80,
      search: false,
      render: (lockFlag) => (
        <Tag
          color={
            lockFlag === LockFlag.OK
              ? 'success'
              : lockFlag === LockFlag.LOCKED
                ? 'error'
                : lockFlag === LockFlag.DELETED
                  ? 'default'
                  : ''
          }>
          {lockFlag === LockFlag.OK
            ? '正常'
            : lockFlag === LockFlag.LOCKED
              ? '锁定'
              : lockFlag === LockFlag.DELETED
                ? '删除'
                : ''}
        </Tag>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      width: 120,
      search: false
    },
    {
      title: '操作',
      key: 'operation',
      align: 'center',
      width: 100,
      search: false,
      render: (_, record) => (
        <div className='flex w-full justify-center text-gray-500'>
          <IconButton
            onClick={() => {
              editFn(record)
            }}>
            <Iconify icon='mdi:card-account-details' size={18} />
          </IconButton>
          <IconButton onClick={() => {}}>
            <Iconify icon='solar:pen-bold-duotone' size={18} />
          </IconButton>
          <Popconfirm
            title='确定删除？'
            okText='确定'
            cancelText='取消'
            placement='left'
            onConfirm={() => {
              deleteFn(record)
            }}>
            <IconButton>
              <Iconify icon='mingcute:delete-2-fill' size={18} className='text-error' />
            </IconButton>
          </Popconfirm>
        </div>
      )
    }
  ]

  return (
    <Card bordered={false}>
      <Row gutter={16}>
        <Col span={5}>
          <DeptTreeSelect onSelect={onDeptTreeSelect} />
        </Col>
        <Col span={19}>
          <ProTable<API.UserListPageResultItem>
            headerTitle='用户管理'
            cardBordered
            rowKey='userId'
            loading={isLoading}
            columns={columns}
            dataSource={tableData}
            pagination={{
              current: page.currentPage,
              pageSize: page.pageSize,
              total: page.total,
              showSizeChanger: true,
              showQuickJumper: true,
              onChange: (page) => {
                setPage((prev) => ({ ...prev, currentPage: page }))
              },
              onShowSizeChange: (_current, size) => {
                setPage((prev) => ({ ...prev, pageSize: size }))
              }
            }}
            search={{
              labelWidth: 'auto'
            }}
            onSubmit={(params) => {
              setSearchForm(() => ({ ...params }))
            }}
            toolBarRender={() => [
              <Button
                key='button'
                icon={<PlusOutlined />}
                onClick={() => {
                  setAddUserModalProps((prev) => ({ ...prev, show: true }))
                }}
                type='primary'>
                新增
              </Button>
            ]}
            options={{
              fullScreen: true,
              reload: () => {
                getList()
              }
            }}
            columnsState={{
              persistenceKey: 'system-auth-user-list-column',
              persistenceType: 'localStorage'
            }}
          />
        </Col>
      </Row>
      <AddModal {...addUserModalProps} />
    </Card>
  )
}
