import { NewGlobalToken } from "@/Hook/useNewToken"
import { useSize } from "ahooks"
import { Button, Card, Divider, Skeleton, Space, Spin, Tooltip, Typography } from "antd"
import React, { useEffect, useMemo, useRef, useState } from "react"
import style from './index.less'
import TextNews from "../../components/newsMould/textNews"
import LinkNews from "../../components/newsMould/linkNews"
import ImgNews from "../../components/newsMould/imgNews"
import { DeleteOutlined, CopyOutlined } from '@ant-design/icons';
import { GetTemplateListProps, MediaContentProps } from "../../API/weMaterial/weMaterial"
import VideoNews from "../../components/newsMould/videoNews"
import AudioNews from "../../components/newsMould/audioNews"
import MiniprogramNews from "../../components/newsMould/miniprogramNews"
import FileNews from "../../components/newsMould/fileNews"
import InfiniteScroll from 'react-infinite-scroll-component';

interface Props {
    data: any[]
    total: number,
    token: NewGlobalToken
    setQueryForm: React.Dispatch<React.SetStateAction<GetTemplateListProps>>
    loading?: boolean
    loadMore?: () => void
    onChange?: (value: any) => void
    selectData?: any
    setSelectData?: React.Dispatch<React.SetStateAction<any>>
    del?: (id: number, name: string) => void
    copy?: (data: any) => void
    flexNum?: number
    isShow?: boolean
    id?: string
    height?: number
}
const Left: React.FC<Props> = ({ token, loading, data, total, loadMore, onChange, selectData, setSelectData, del, copy, flexNum = 0, isShow = true, id='scrollableDiv', height }) => {

    /************************/
    const ref = useRef<HTMLDivElement>(null);
    const size = useSize(ref);
    const [rowNum, setRowNum] = useState<number>(flexNum)
    const [dataList, setDataList] = useState<any[]>([])
    /************************/

    useEffect(() => {
        setDataList(data || [])
    }, [data])

    // 根据内容宽度计算列数
    useEffect(() => {
        if (size?.width && !flexNum) {
            let rowNum = Math.floor((size?.width - 26) / 260)
            setRowNum(rowNum || 1)
        }
    }, [size?.width])

    // 选中模板
    const selectHndle = (value: any) => {
        setSelectData?.(value)
        onChange?.(value)
    }
    
    const content = useMemo(() => {
        let sourceData: any[] = []
        dataList.forEach((item, index) => {
            sourceData[index % rowNum] ? sourceData[index % rowNum]?.push(item) : sourceData[index % rowNum] = [item]
        })
        
        // 不足
        if (sourceData.length < rowNum) {
            let fewNum = rowNum - sourceData.length
            sourceData = [...sourceData, ...Array(fewNum).fill([]).map(item => item)]
        }
        return <>
            {sourceData.map((item: any[], index) => <div key={index} className={style.content_row} style={{ width: (1 / rowNum * 100) + '%' }}>
                {item?.map((list: any, index) => {
                    let itemonec: MediaContentProps = list?.corpMediaContentVOList[0]
                    return <Card
                        style={selectData?.id === list?.id ? { borderColor: token.colorPrimaryBorderHover } : {}}
                        className={style.left_content_card}
                        key={index}
                        onClick={() => selectHndle(list)}
                        styles={{
                            body: { padding: 10, position: 'relative' },
                            header: { padding: '5px 10px' },
                        }}
                        title={<Space direction="vertical" size={0} style={{ width: '100%' }}>
                            <Typography.Title style={{ margin: 0 }} level={5} ellipsis>{list?.mediaTitle}</Typography.Title>
                            <Typography.Text type="secondary">{list?.createName} {list?.createTime}</Typography.Text>
                        </Space>}
                    >
                        <div className={style.content} style={{ width: '100%', backgroundColor: token.colorFillTertiary, borderRadius: token.borderRadius }}>
                            {
                                itemonec?.mediaType === 'text' ? <TextNews style={{ marginBottom: 0 }} ellipsis={{ rows: 3 }} strong msg={(itemonec as any)?.textContent || ''} />
                                    : itemonec?.mediaType === 'link' ? <LinkNews content={{ url: itemonec.linkUrl as string, title: itemonec.linkTitle as string, desc: itemonec.linkDesc as string, cover: itemonec.linkPicurl as string }} />
                                        : itemonec?.mediaType === 'image' ? <ImgNews src={itemonec?.imageUrl} />
                                            : itemonec?.mediaType === 'video' ? <VideoNews src={itemonec?.videoUrl} />
                                                : itemonec?.mediaType === 'voice' ? <AudioNews url={itemonec?.voiceUrl} times={itemonec.mediaPlayTime} />
                                                    : itemonec?.mediaType === 'miniprogram' ? <MiniprogramNews {...itemonec} />
                                                        : itemonec?.mediaType === 'file' ? <FileNews fileName={itemonec?.fileName} fileSize={itemonec.mediaSize} fileUrl={itemonec.fileUrl} />
                                                            : null
                            }
                        </div>
                        <div className={style.tips}>
                            <Typography.Text type="secondary" style={{ width: '68%' }} ellipsis={{ tooltip: true }}>标签: {list?.mediaTagNames?.toString()}</Typography.Text>
                            <Typography.Text type="secondary">共{list?.corpMediaContentVOList?.length}条</Typography.Text>
                        </div>
                        {isShow && <div className={style.action} onClick={(e) => { e.stopPropagation(); }} >
                            <div style={{
                                backgroundColor: token.colorPrimaryBgHover,
                                borderRadius: token.borderRadius
                            }}>
                                {/* <div><Tooltip title='群发'><Button type="link" icon={<SendOutlined />}></Button></Tooltip></div> */}
                                <div><Tooltip title='复制'><Button type="link" icon={<CopyOutlined />} onClick={()=> copy?.(list)}></Button></Tooltip></div>
                                <div><Tooltip title='删除'><Button type="link" icon={<DeleteOutlined />} onClick={() => { del?.(list?.id, list?.mediaTitle) }}></Button></Tooltip></div>
                            </div>
                        </div>}
                    </Card>
                })}
            </div>)}
        </>
    }, [rowNum, size, dataList, selectData])


    const loadMoreData = () => {
        if (dataList.length === total) {
            return
        }
        loadMore?.()
    }

    return <div className={style.left_root}>
        <div className={style.left_content} id={id} ref={ref}>
            <InfiniteScroll
                key={id}
                dataLength={dataList.length}
                next={loadMoreData}
                hasMore={dataList.length < total}
                loader={<div style={{ display: 'flex', marginTop: 10 }}>
                    {Array(rowNum).fill('').map((item, index) => <div key={index} className={style.content_row} style={{ width: (1 / rowNum * 100) + '%', padding: '0 5px', boxSizing: 'border-box' }}>
                        <Skeleton.Input active style={{ width: '100%' }} />
                    </div>)}
                </div>}
                endMessage={<Divider plain>It is all, nothing more 🤐</Divider>}
                scrollableTarget={id}
                height={height}
            >
                <div className={style.memo_content}>
                    {content}
                </div>
            </InfiniteScroll>
        </div>
        {loading && <div className={style.content_spin}><Spin /></div>}
    </div>
}

export default React.memo(Left)