// 文件浏览列表
import Button from 'antd/lib/button';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { classNames } from '../../renderers/Lion/utils/utils';
import { MediaItem } from '../ImageGallery';
import { Tooltip } from 'antd';
import { chunk, cloneDeep } from 'lodash';

import { QuestionCircleOutlined } from '@ant-design/icons';
import { ResizeEvent } from '../../types';
interface IProps {
    unionSelecting: boolean;
    mediaListShow: boolean;
    unionImgShow: boolean;
    mediaList: Array<MediaItem>;
    selectList: Array<number>;
    currentIndex: number;
    handleUnionSelecting: (show: boolean) => void;
    handleMediaListSelect: (index: number) => void;
    handleUnionImgShow: (show: boolean) => void;
    handleSelectAll: (ids: number[]) => void;
    handleSelectReverse: (ids:number[]) => void;
}

const MediaShowList: React.FC<IProps> = props => {
    const {
        mediaList,
        currentIndex,
        unionSelecting,
        selectList,
        mediaListShow,
        unionImgShow,
        handleUnionSelecting,
        handleMediaListSelect,
        handleUnionImgShow,
        handleSelectAll,
        handleSelectReverse
    } = props;
    const scrollContentRef = React.useRef<any>(null);
    const [imgSize, setImgSize] = useState('');
    const [finalImgList, setFinalImgList] = useState(mediaList);
    const [allImgList, setAllImgList] = useState([]);
    const [index, setIndex] = useState(0);
    useEffect(() => {
        document.body.addEventListener(
            ResizeEvent.DIALOGRESIZEENDEVENT,
            handleCalcImgSize
        );
        return () => {
            document.body.removeEventListener(
                ResizeEvent.DIALOGRESIZEENDEVENT,
                handleCalcImgSize
            );
        };
    }, []);
    // useImperativeHandle(ref, () => ({
    //     handleToggle
    // }));
    // useEffect(() => {
    //     const bsInstance = scrollContentRef.current?.bsInstance;
    //     if (bsInstance) {
    //         let content = bsInstance.content;
    //         let elementList = Array.from(content.children);
    //         bsInstance.scrollToElement(
    //             elementList[currentIndex] as HTMLElement,
    //             100,
    //             true,
    //             true
    //         );
    //     }
    // }, [currentIndex, scrollContentRef.current]);

    // useEffect(() => {
    //     const bsInstance = scrollContentRef.current?.bsInstance;
    //     if (bsInstance) bsInstance.refresh();
    // }, [unionSelecting]);

    // const handleScroll = (type: 'left' | 'right') => {
    //     const { scrollLeft, scrollWidth, clientWidth } = scrollContentRef.current;
    //     if (type === 'left' && scrollLeft > 0) {
    //         scrollContentRef.current?.scrollTo({
    //             left: Math.max(scrollLeft - 200, 0),
    //             behavior: 'smooth'
    //         });
    //     }
    //     if (type === 'right' && scrollWidth - clientWidth > scrollLeft) {
    //         scrollContentRef.current?.scrollTo({
    //             left: Math.min(scrollLeft + 200, scrollWidth - clientWidth),
    //             behavior: 'smooth'
    //         });
    //     }
    // };

    const imageList = useMemo(() => {
        if (unionSelecting) {
            return mediaList.filter(item => !item.isNotImg);
        }
        return mediaList;
    }, [unionSelecting, mediaList]);

    const handleToggle = (type: 'prev' | 'next') => {
        const moveIndex = type === 'prev' ? -1 : 1;
        setIndex(index => {
            const nextIndex = index + moveIndex;
            const finalIndex =
                nextIndex < 0 || nextIndex > allImgList.length - 1 ? index : nextIndex;
            setFinalImgList(() => allImgList[finalIndex]);

            return finalIndex;
        });
    };

    const handleCalcImgSize = () => {
        setIndex(0);
        const mediaListWrapper = document.querySelector(
            '.mediaShowListWrapper'
        ) as HTMLElement;
        const unionImgHandler = document.querySelector(
            '.unionImgHandle'
        ) as HTMLElement;
        // const imgListWrapper = document.querySelector('.imgListWrapper.con-main') as HTMLElement;
        // 剩余实际的图片容器空间宽度
        const clientWidth =
            mediaListWrapper.clientWidth - (unionImgHandler ? 208 : 0) - 18 * 2;

        let singleSize = 30 + 8;
        // 单行能容纳的数量
        let ceilCount = Math.ceil(clientWidth / singleSize);
        // 实际单行宽度
        let realWidth = ceilCount * singleSize;

        let floorCount = Math.floor(clientWidth / singleSize);
        let allList = chunk(cloneDeep(mediaList), floorCount * 2) ?? [];
        let newImgList = mediaList.slice(0, floorCount * 2);
        
        /** 如果容器宽度计算出的图片个数 * 初始宽高 >= 容器宽度 则进行赋值small 的className */
        if (realWidth >= clientWidth && mediaList.length > floorCount) {
            singleSize = 24 + 8;
            ceilCount = Math.ceil(clientWidth / singleSize);
            realWidth = ceilCount * singleSize;
            floorCount = Math.floor(clientWidth / singleSize);
            allList = chunk(cloneDeep(mediaList), floorCount * 2) ?? [];
            newImgList = mediaList.slice(0, floorCount * 2);

            setImgSize('small');
        } else {
            setImgSize('');
        }
        setAllImgList(allList);
        setFinalImgList(newImgList);
    };
    
    const handleImgSelectAll = () => {
        const ids = finalImgList.map((item, index) => !item.isNotImg ? `${index}` : undefined).filter(Boolean).map((idx) => Number(idx));
        handleSelectAll(ids);
    }
    const handleImgSelectReverse = () => {
        const ids = finalImgList.map((item, index) => !item.isNotImg && !selectList.includes(index) ? `${index}` : undefined).filter(Boolean).map((idx) => Number(idx));
        handleSelectReverse(ids);
    }
    useEffect(() =>{
        if (allImgList.length > 1) {
            const currentMaxIndex = (allImgList[0]?.length ?? 0) * (index + 1) - 1;
            const perPageLen = allImgList[0]?.length ?? 0;
            // 在currentIndex 小于当前长度最小值的index 或大于当前长度最大值的index 才进行换页
            if (currentIndex > currentMaxIndex) {
                handleToggle('next');
            } else if (currentIndex < (currentMaxIndex - perPageLen + 1)) {
                handleToggle('prev');
            }
        }
    }, [currentIndex]);
    useEffect(() => {
        handleCalcImgSize();
    }, [unionSelecting]);
    return (
        <div
            className={classNames(
                'mediaShowList',
                !((mediaListShow || unionSelecting) && !unionImgShow) &&
                'mediaShowListWrapper_hidden'
            )}
        >
            {!mediaList.length || (unionSelecting && !imageList.length) ? (
                <div>空空如也</div>
            ) : (
                <div className={classNames('mediaShowListWrapper')}>
                    <div
                        className={classNames(
                            'mediaShowListContent'
                            // unionSelecting && "w-50"
                        )}
                    >
                        {/* <div className={classNames('imgList-arrow is-disabled')} onClick={() => handleScroll('left')}> */}
                        <div
                            className={classNames(
                                'imgList-arrow is-disabled',
                                `${allImgList?.length > 1 ? 'show' : ''}`
                            )}
                            onClick={() => handleToggle('prev')}
                        >
                            {/* <Icon icon="prev" className="icon" /> */}
                            <i className="fa fa-chevron-left"></i>
                        </div>
                        <div className="imgListWrapper con-main" ref={scrollContentRef}>
                            <div className={classNames('imgList', 'ul', imgSize)}>
                                {finalImgList?.map((mediaItem: any, mediaIndex: number) => {
                                    const isImg = !mediaItem.isNotImg;
                                    const idx = allImgList.length > 1 ? ((allImgList[0]?.length ?? 0) ) * index + mediaIndex : mediaIndex;
                                    return !unionSelecting || isImg ? (
                                        <div
                                            className={classNames(
                                                'imgWrapper',
                                                'li',
                                                !unionSelecting &&
                                                idx === currentIndex &&
                                                'imgWrapper_selected',
                                                unionSelecting &&
                                                selectList?.includes(idx) &&
                                                'imgWrapper_selected'
                                            )}
                                            onClick={e => {
                                                handleMediaListSelect(idx);
                                            }}
                                            key={mediaIndex}
                                        >
                                            <img src={mediaItem.src} />
                                            {unionSelecting && selectList?.includes(idx) && (
                                                <div className="check-icon">
                                                    <i className="fa fa-check-square"></i>
                                                </div>
                                            )}
                                        </div>
                                    ) : null;
                                })}
                            </div>
                        </div>

                        <div
                            className={classNames(
                                'imgList-arrow is-disabled',
                                `${allImgList?.length > 1 ? 'show' : ''}`
                            )}
                            onClick={() => handleToggle('next')}
                        >
                            <i className="fa fa-chevron-right"></i>
                        </div>
                    </div>
                    {unionSelecting && (
                        <div className="unionImgHandle">
                            <Tooltip
                                title="一张并图最多支持20条，超过20条形成新的并图"
                                placement="top"
                            >
                                <QuestionCircleOutlined
                                    className="item"
                                    style={{ color: '#666' }}
                                />
                            </Tooltip>
                            <Button type="link" size="small" className="item" onClick={handleImgSelectReverse}> 反选 </Button>
                            <Button type="link" size="small" className="item" onClick={handleImgSelectAll} > 全选 </Button>
                            <Button size="small" className="item" onClick={() => { handleUnionSelecting(false); }} > 取消 </Button>
                            <Button size="small" className="item" onClick={() => { handleUnionImgShow(true); }} type="primary" > 确定 </Button>
                        </div>
                    )}
                </div>
            )}
        </div>
    );
};

export default MediaShowList;