import React, { useEffect, useMemo, useState } from 'react'
import { Avatar, Card, Col, Popover, Row } from 'antd'
import { RendererEnv } from '../../env'

type Column = { name: string, label: string }

interface IProps {
    id: string
    mailId?: string
    children: React.ReactNode
    env: RendererEnv
}

enum FieldName {
    USER_ID = 'USER_ID',
    USER_NAME = 'USER_NAME',
    GROUP_NAME = 'GROUP_NAME',
    USER_IMAGE = 'USER_IMAGE',
    USER_DEP = 'DEP_NAME',
    USER_TYPE = 'USER_TYPE',
    ORG_ID = 'ORG_ID'
}

export const UserDetailPopover: React.FC<IProps> = (props) => {

    const [visible, setVisible] = useState(false)

    return (
        <Popover
            visible={visible}
            content={<PcContent {...props} />}
            placement='bottomLeft'
            trigger='click'
            destroyTooltipOnHide
            // getPopupContainer={e => e.parentElement ?? document.body}
            onVisibleChange={setVisible}
        >
            {props.children}
        </Popover>
    )

}

const PcContent: React.VFC<{ id: string, mailId?: string, env: RendererEnv }> = ({ id, env }) => {
    const baseUrl = env?.axiosInstance?.defaults?.baseURL || env?.ajaxApi || ''

    const [loading, setLoading] = useState(true)

    const [{ columns, items }, setDataSource] = useState<{ columns: Column[], items: any[] }>({ columns: [], items: [] })

    const isGroup = useMemo(() => items[0]?.[FieldName.USER_TYPE] === 'USER_GROUP' || items[0]?.[FieldName.USER_TYPE] === 'DEPART', [items])

    useEffect(() => {
        getDetail()
    }, [])

    const getDetail = async () => {
        const res = await env.fetcher({ url: `/api/v1/user/info/data?userId=${id}`, method: 'get' }).finally(() => setLoading(false))
        if (res.status == 0 && res.data != null) {
            setDataSource(res.data)
        }
    }

    return (
        <div style={{ maxHeight: 'calc(100vh - 450px)', overflowY: 'auto' }}>
            <Card loading={loading} style={{ width: 350, background: '#f7f8fa', borderRadius: 4 }} bodyStyle={{ padding: '18px 12px' }}>
                <Card.Meta
                    avatar={<Avatar style={{ width: 64, height: 64, backgroundColor: 'white', border: '1px solid #e6e8eb', borderRadius: 6, padding: 6 }} shape='square' src={items[0]?.[FieldName.USER_IMAGE] ? baseUrl + items[0]?.[FieldName.USER_IMAGE] : ''} />}
                    title={<div style={{ fontWeight: 600 }}>{items[0]?.[isGroup ? FieldName.GROUP_NAME : FieldName.USER_NAME]}</div>}
                    description={<span style={{ fontWeight: 500, color: 'rgba(0,0,0,0.6)' }}>{items[0]?.[FieldName.USER_DEP]}</span>}
                />
            </Card>
            {isGroup && (
                <Card loading={loading} style={{ width: 350, background: '#f7f8fa', borderRadius: 4, marginTop: 8 }} bodyStyle={{ padding: '6px 12px' }}>
                    <Row style={{ padding: '8px 0' }}>
                        <Col span={6} className='ellipsis'>组员</Col>
                        <Col span={18}>{items.slice(0, 2).map(item => `${item.USER_NAME}(${item.USER_ID})`).join(',') + (items.length > 2 ? ` 等${items.length}人` : '')}</Col>
                    </Row>
                </Card>
            )}
            <Card loading={loading} style={{ width: 350, background: '#f7f8fa', borderRadius: 4, marginTop: 8 }} bodyStyle={{ padding: '6px 12px' }}>
                {columns.filter(column => !Object.values(FieldName).filter(field => isGroup ? true : field !== FieldName.USER_ID).some(field => field == column.name)).map((column, index, arr) => (
                    <Row style={{ padding: '8px 0', borderBottom: index == arr.length - 1 ? undefined : '1px solid #eee' }}>
                        <Col span={6} className='ellipsis'>{column.label}</Col>
                        <Col span={18}>{items[0]?.[column.name]}</Col>
                    </Row>
                ))}
            </Card>
        </div>
    )

}
