import { CloseCircleFilled, FieldTimeOutlined, SearchOutlined } from "@ant-design/icons";
import { Button, Card, Checkbox, Modal, Select, Space, Spin, Image as AntImage, Tooltip, Tag, Pagination, Radio, RadioChangeEvent, message, DatePicker } from "antd";
import { SelectValue } from "antd/es/select";
import React, { useCallback, useEffect, useState } from "react";
import { useModel } from "umi";
import style from './index.less'
const { Option } = Select
import './index1.less'
import AddCom from '../../../materialManageBd/adMaterial/components/addCom'
import moment from "moment";
import CropperImg from '@/components/CropperImg'

interface Props {
    visible: boolean,
    hideModel: () => void,
    num?: number,  // 选择多少
    onChange?: (value: any) => void,
    editData?: any[],
    sliderImgContent?: { content: string, width?: number, height?: number }[],  // 回填数据
    listParams: {
        minWidth?: string,   //最小宽度
        maxWidth?: string,   //最大宽度
        minHeight?: string,  //最小高度
        maxHeight?: string,  //最大高度
        minMediaSize?: number, // 最小媒体大小
        maxMediaSize?: number, // 最大媒体大小
        minVideoLength?: number, // 最小视频时长
        maxVideoLength?: number, // 最大视频时长
        minVideoBitRate?: number, // 最小视频比特率
        maxVideoBitRate?: number, // 最大视频比特率
        type?: 1 | 2,  // 内容类型 1 图片 2 视频
    },
    imgType?: boolean, // 是否是公众号及其它
    isFootlock?: boolean, // 是否是横板视频 
}
const colors = ['magenta', 'red', 'volcano', 'orange', 'gold', 'lime', 'green', 'cyan', 'blue', 'geekblue', 'purple']
function SelectImg(props: Props) {
    let { visible, hideModel, num = 1, onChange, editData = [], sliderImgContent = [], listParams, imgType = false, isFootlock = false } = props
    const { getLabels, getMediasList, getSmDetail } = useModel('useLaunch.useMaterial')
    const [queryForm, setQueryForm] = useState<{
        minWidth?: string,   //最小宽度
        maxWidth?: string,   //最大宽度
        minHeight?: string,  //最小高度
        maxHeight?: string,  //最大高度
        minMediaSize?: number, // 最小媒体大小
        maxMediaSize?: number, // 最大媒体大小
        minVideoLength?: number, // 最小视频时长
        maxVideoLength?: number, // 最大视频时长
        minVideoBitRate?: number, // 最小视频比特率
        maxVideoBitRate?: number, // 最大视频比特率

        pageNum: number,
        pageSize: number,
        isCollect: boolean,
        labelIds: SelectValue,
        novels: string,
        sortRule: SelectValue | undefined,
        singleImg: boolean,  // true 单图  false 组图
        type: number,
        dataType: string,
        beginDate: string | undefined,  // 上传时间
        endDate: string | undefined,  // 结束时间
        upOrder: boolean
    }>({
        isCollect: false,
        labelIds: [],
        novels: '',
        singleImg: true,
        sortRule: 'create_time',
        upOrder: false,
        pageNum: 1,
        pageSize: 8,
        dataType: 'personal',
        type: 1,
        beginDate: undefined,
        endDate: undefined,
        ...listParams
    })
    const [checkedList, setCheckedList] = useState<{ content: string, width?: number, height?: number }[]>([]);
    const [visibleAdd, setVisibleAdd] = useState<boolean>(false)
    const [accData, setAccData] = useState<string>(imgType ? '800*800' : isFootlock ? '640*480' : '800*800')  // 公众号及其它时选择
    const [aspectRatio, setAspectRatio] = useState<string>('1.8')
    const [imgSize, setImgSize] = useState<{ width: number, height: number, size: number }>({ width: 0, height: 0, size: 307200 })
    const { isCollect, labelIds, sortRule, upOrder, pageNum, pageSize, dataType, singleImg, beginDate, endDate } = queryForm
    // 新增裁剪
    const [imgUrl, setImgUrl] = useState<string>('')  // 要裁剪url
    const [cropperShow, setCropperShow] = useState<boolean>(false)

    /** 轮播回填数据 */
    useEffect(() => {
        setCheckedList(sliderImgContent)
    }, [sliderImgContent])

    useEffect(() => {
        if (editData.length > 0) {
            setCheckedList(checkedList)
        }
    }, [editData])

    const hideHandle = useCallback(() => {
        hideModel()
    }, [hideModel])

    // 不能删 
    useEffect(() => {
        setQueryForm(() => ({ ...queryForm, labelIds, ...listParams }))
    }, [listParams])

    const handleOk = useCallback(() => {
        // if (listParams?.type === 1 && num === 1 && checkedList?.length === 1) { // 图片
        //     console.log('图片组-->', checkedList)
        //     let { width, height } = checkedList[0]
        //     if ((width && Number(listParams.maxWidth) < width) || (height && Number(listParams.maxHeight) < height)) {
        //         setImgUrl(checkedList[0]?.content)
        //         setCropperShow(true)
        //     } else {
        //         hideModel()
        //         onChange && onChange(checkedList)
        //     }
        // } else {
        hideModel()
        onChange && onChange(checkedList)
        // }
    }, [hideModel, checkedList, imgUrl, cropperShow, listParams, num])

    useEffect(() => {
        getLabels.run({ pageNum: 1, pageSize: 200 })
    }, [])

    /** 获取列表 */
    useEffect(() => {
        if (Object.keys(queryForm).indexOf('minWidth') !== -1) {
            let param = { ...queryForm, labelIds }
            // if(param.type === 1) { // 改裁剪需要
            //     param.maxWidth && (param.maxWidth = (Number(param.maxWidth) * 3).toString())
            //     param.maxHeight && (param.maxHeight = (Number(param.maxHeight) * 3).toString())
            // }
            getMediasList.run(param)
            if (queryForm && queryForm?.type === 1 && queryForm.minWidth && queryForm.minHeight) {
                setImgSize(() => ({ width: Number(queryForm.minWidth), height: Number(queryForm.minHeight), size: Number(queryForm.maxMediaSize || 0) }))
            }
        }
    }, [queryForm])
    /**分页 */
    const pageChange = useCallback((page: number, pageSize?: number) => {
        setQueryForm({ ...queryForm, pageNum: page, pageSize: pageSize || 20 })
    }, [queryForm])
    /** 清空 */
    const emptyHandle = useCallback(() => {
        setCheckedList([])
    }, [checkedList])

    /** 框选择 */
    const onChangeBox = useCallback((e: boolean, item: any) => {
        if (e && !checkedList?.some((list: any) => list?.content === item?.content)) {
            setCheckedList([...checkedList, item])
        } else {
            let index = checkedList?.findIndex((list: any) => list?.content === item?.content)
            if (index !== -1) {
                checkedList?.splice(index, 1)
                setCheckedList([...checkedList])
            }
        }
    }, [checkedList])

    /** 删除 */
    const clearImg = useCallback((content: string) => {
        let index = checkedList?.findIndex((list: any) => list?.content === content)
        if (index !== -1) {
            checkedList?.splice(index, 1)
            setCheckedList([...checkedList])
        }
    }, [checkedList])

    /** 设置尺寸 */
    const accHandle = useCallback((value: string) => {
        setAccData(value)
        if (value) {
            let [width, height] = value?.split('*')
            setQueryForm({ ...queryForm, labelIds, ...listParams, minWidth: width, maxWidth: width, minHeight: height, maxHeight: height, pageNum: 1 })
        }

    }, [accData, queryForm, listParams])
    /** 设置宽高比 */
    const aspectRatioSet = useCallback((value: string) => {
        setAspectRatio(value)
        if (value) {
            getMediasList.run({ ...queryForm, labelIds, ...listParams, aspectRatio: value })
        }
    }, [aspectRatio, queryForm, listParams])

    /** 组图选择 */
    const selectImgs = useCallback((value: string, item: any, index: number) => {
        let data = checkedList.find((list: any) => list?.content === value)
        if (data) { // 有 就减少
            let dataIndex = checkedList.findIndex((list: any) => list?.content === value)
            checkedList?.splice(dataIndex, 1)
            setCheckedList([...checkedList])
        } else { // 没有 增加
            if (checkedList?.length >= num) {
                message.error(`当前只能选择${num}张`)
                return
            }
            item = { ...item, content: value, mediaFormat: item?.mediaFormat?.split(',')[index], mediaSize: item?.mediaSize?.split(',')[index] }
            setCheckedList([...checkedList, item])
        }
    }, [checkedList])
    /** 获取详情素材详情 */
    const getScDetail = (id?: number) => {
        if (id) {
            getSmDetail.run(id).then((res: any) => {
                if (res) {
                    let data = res?.content?.split(',')?.map((item: any, index: number) => {
                        return {
                            ...res,
                            content: item,
                            mediaSize: res?.mediaSize?.split(',')[index],
                            mediaFormat: res?.mediaFormat?.split(',')[index]
                        }
                    })
                    if (data && data?.length > 0) {
                        setCheckedList([...data])
                    }
                }
            })
        }
    }
    return <Modal
        title={<Space>
            <div>选择图片/视频</div>
            <Button type='dashed' onClick={() => { setVisibleAdd(true) }}>上传</Button>
        </Space>}
        visible={visible}
        onCancel={hideHandle}
        width={1318}
        className={`${style.selectImg} selectImg11`}
        maskClosable={false}
        bodyStyle={{ padding: 0 }}

        footer={<Space>
            <Button onClick={emptyHandle}>清空</Button>
            <Button onClick={hideHandle}>取消</Button>
            <Button onClick={handleOk} type='primary'>确定</Button>
        </Space>}
    >
        {/* 裁剪 */}
        {cropperShow && <CropperImg imgUrl={imgUrl} visible={cropperShow} onClose={() => { setCropperShow(false) }} width={listParams?.minWidth ? Number(listParams?.minWidth) : 800} height={listParams?.minHeight ? listParams?.minHeight !== '0' ? Number(listParams?.minHeight) : Number(listParams?.maxHeight) : 800} />}

        {visibleAdd && <AddCom num={num} imgSize={imgSize} visible={visibleAdd} hideModal={(e) => { setVisibleAdd(false); }} ajax={getMediasList} dataType={dataType} uploadType={listParams?.type === 1 ? 'img' : 'video'}></AddCom>}
        <Space style={{ padding: '10px 0px 10px 20px' }} wrap>
            <Radio.Group value={dataType} onChange={(e: RadioChangeEvent) => { setQueryForm({ ...queryForm, dataType: e.target.value, pageNum: 1 }) }}>
                <Radio.Button value="personal">个人</Radio.Button>
                <Radio.Button value="all">公司全员共享</Radio.Button>
                <Radio.Button value="group">组内共享</Radio.Button>
            </Radio.Group>
            <Select style={{ width: 100 }} value={isCollect ? 'true' : 'false'} onChange={(value: SelectValue) => { setQueryForm({ ...queryForm, isCollect: value === 'true' ? true : false, pageNum: 1 }) }}>
                <Option value="false">全部</Option>
                <Option value="true">我的收藏</Option>
            </Select>
            {imgType && <Select style={{ width: 100 }} value={accData} onChange={(value: string) => { accHandle(value) }}>
                <Option value="800*800">800*800</Option>
                <Option value="640*800">640*800</Option>
                <Option value="800*640">800*640</Option>
                <Option value="800*450">800*450</Option>
            </Select>}
            {isFootlock && <Select style={{ width: 100 }} value={aspectRatio} onChange={(value: string) => { aspectRatioSet(value) }}>
                <Option value="1.8">16:9</Option>
                <Option value="1.4">4:3</Option>
            </Select>}
            <DatePicker style={{ width: 120 }} value={beginDate ? moment(beginDate) : null} onChange={(e: moment.Moment | null) => { setQueryForm({ ...queryForm, beginDate: e ? moment(e).format('YYYY-MM-DD') : undefined, pageNum: 1 }) }} placeholder='开始时间' />
            <DatePicker style={{ width: 120 }} value={endDate ? moment(endDate) : null} onChange={(e: moment.Moment | null) => { setQueryForm({ ...queryForm, endDate: e ? moment(e).format('YYYY-MM-DD') : undefined, pageNum: 1 }) }} placeholder='结束时间' />
            <Select style={{ width: 200 }} maxTagCount='responsive' value={labelIds} onChange={(value: SelectValue) => { setQueryForm({ ...queryForm, labelIds: value, pageNum: 1 }) }} placeholder="选择标签" allowClear mode="multiple">
                {getLabels?.data?.records.map((item: any) => (<Option value={item?.id} key={item?.id}>{item?.label}</Option>))}
            </Select>
            {/* <Search placeholder="请输入小说" style={{ width: 150 }} onSearch={(e) => { setQueryForm({ ...queryForm, novels: e }) }} allowClear /> */}
            <Select style={{ width: 150 }} value={sortRule} onChange={(value: SelectValue) => { setQueryForm({ ...queryForm, sortRule: value, pageNum: 1 }) }} placeholder="选择排序类型" allowClear>
                <Option value="create_time">按照上传时间排序</Option>
            </Select>
            <Select style={{ width: 70 }} value={upOrder ? '1' : '2'} onChange={(value: SelectValue) => { setQueryForm({ ...queryForm, upOrder: value === '1' ? true : false, pageNum: 1 }) }} >
                <Option value="1">升序</Option>
                <Option value="2">降序</Option>
            </Select>
            {queryForm?.type === 1 && <Select style={{ width: 70 }} value={singleImg ? 1 : 0} onChange={(value: SelectValue) => { setQueryForm({ ...queryForm, singleImg: value === 1, pageNum: 1 }) }} >
                <Option value={1}>单图</Option>
                <Option value={0}>组图</Option>
            </Select>}

            <Button type='primary'>搜索 <SearchOutlined /></Button>
        </Space>
        <Spin spinning={getMediasList.loading} size='large'>
            {/* <Checkbox.Group onChange={onChangeCheckbox} value={checkedList} className={style.group}> */}
            <div className={style.group}>
                <div className={style.contentbb}>
                    <div className={style.contentaa}>
                        {
                            getMediasList?.data?.records?.map((item: any, index: number) => {

                                let El = item?.type === 1 ? <div className='imgs'>
                                    {
                                        item?.content?.split(',').length > 1 ? <Tooltip placement="rightTop" color="#FFFFFF" className={style.tooltipTip} title={
                                            <div className={style.tooltipImgs}>
                                                {item?.content?.split(',').map((Imgitem: string, Imgindex: number) => (<div key={Imgitem} className={`${style.tooltipImg} ${checkedList.some((list: any) => list?.content === Imgitem) && style.selected}`} onClick={() => { selectImgs(Imgitem, item, Imgindex) }}><img style={{ width: 50 }} src={Imgitem} /></div>))}
                                            </div>
                                        }>
                                            <div className='imgz'>
                                                {
                                                    item?.content?.split(',').length === 2 ? <div className="con2">
                                                        {item?.content?.split(',').map((item: string, index: number) => (<div key={index}><AntImage src={item} preview={false} /></div>))}
                                                    </div> :
                                                        item?.content?.split(',').length === 3 ? <div className="con3">
                                                            {item?.content?.split(',').map((item: string, index: number) => (<div key={index}><AntImage src={item} preview={false} /></div>))}
                                                        </div> :
                                                            item?.content?.split(',').length === 4 ? <div className="con4">
                                                                {item?.content?.split(',').map((item: string, index: number) => (<div key={index}><AntImage src={item} preview={false} /></div>))}
                                                            </div> :
                                                                item?.content?.split(',').length === 6 ? <div className="con6">
                                                                    {item?.content?.split(',').map((item: string, index: number) => (<div key={index}><AntImage src={item} preview={false} /></div>))}
                                                                </div> :
                                                                    <AntImage src={item?.content?.split(',')[0]} preview={false} />
                                                }
                                            </div>
                                        </Tooltip> :
                                            <div className='imgz'>
                                                {
                                                    <AntImage src={item?.content?.split(',')[0]} preview={false} />
                                                }
                                            </div>
                                    }

                                    <div className='backImg'>
                                        <img src={`${item?.content?.split(',')[0]}`} />
                                    </div>
                                </div> : item?.type === 2 ? <video src={item?.content} style={{ width: 300, height: 170 }} controls /> : null

                                return <div style={{ width: 300 }} key={index} >
                                    {<Card
                                        hoverable
                                        className={`${style.box_card} ${checkedList.some((list: any) => item?.content?.indexOf(list?.content) !== -1) && style.cardSelect}`}
                                        cover={<div className='covercc'>
                                            {El}
                                            {!(item?.content?.split(',').length > 1 && !item?.singleImg) && <div className='boxcc'><Checkbox checked={checkedList.some((list: any) => item?.content?.indexOf(list?.content) !== -1)} onChange={(e) => { onChangeBox(e.target.checked, item) }} disabled={checkedList?.length >= num ? checkedList?.findIndex((itemd: any) => itemd?.content === item?.content) !== -1 ? false : true : false} /></div>}
                                            <div className='boxdd'>
                                                {
                                                    item?.content?.split(',').length > 1 && !item?.singleImg && <div className='zt'>组图</div>
                                                }
                                            </div>
                                        </div>
                                        }
                                        onClick={() => {
                                            if (singleImg) {
                                                let off = !checkedList?.some((list: any) => list?.content === item?.content) && checkedList.length < num
                                                onChangeBox(off, item)
                                            }
                                        }}
                                    >
                                        <Card.Meta
                                            style={{ fontSize: 12, padding: 10 }}
                                            description={
                                                <>
                                                    <div className="bottom">
                                                        <div>
                                                            {item?.createTime &&
                                                                <Tooltip placement="top" title='创建时间'>
                                                                    <Space><FieldTimeOutlined />{item?.createTime.split(' ')[0]}</Space>
                                                                </Tooltip>}
                                                        </div>
                                                        <div className="left">
                                                            {/* {item?.startDate && item?.endDate && <Tooltip placement="top" title='投放时间'>
                                                                <Space><HistoryOutlined />{item?.startDate + '/' + item?.endDate}</Space>
                                                            </Tooltip>} */}
                                                            <div>
                                                                <Tooltip placement="topLeft" color="#FFF" title={
                                                                    <div>
                                                                        {item?.labelInfos?.map((item: any, index: number) => {
                                                                            return <Tag color={colors[index]} key={item?.id} >{item?.label}</Tag>
                                                                        })}
                                                                    </div>
                                                                }>
                                                                    <div className="title">
                                                                        {item?.labelInfos?.map((item: any, index: number) => {
                                                                            if (index > 2) return null
                                                                            return <Tag color={colors[index]} key={item?.id} >{item?.label}</Tag>
                                                                        })}
                                                                    </div>
                                                                </Tooltip>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div className="bottom">

                                                        <div className="left" style={{ color: 'purple' }} onClick={() => { }}>
                                                            {item?.novels && <Tooltip placement="top" title={`小说：${item?.novels}`}>
                                                                {item?.novels?.split(',')[0] + (item?.novels?.split(',')?.length > 1 ? ',...' : '')}
                                                            </Tooltip>}
                                                        </div>
                                                    </div>
                                                    <div className="bottom">
                                                        <div className="right">{item?.creator || '未知'}</div>
                                                        <div className="left">
                                                            <Space>
                                                                {/* <Tooltip placement="top" title='消耗'>
                                                                    <Space style={{ color: "#46BF12" }}><PieChartOutlined />{(item?.consumeAmount || 0)}</Space>
                                                                </Tooltip>
                                                                <Tooltip placement="top" title='点击率'>
                                                                    <Space style={{ color: "#02A7F0" }}><SelectOutlined />{item?.clickRate ? item?.clickRate + '%' : 0}</Space>
                                                                </Tooltip> */}
                                                                {item?.channel && <span className="channer" style={{ backgroundColor: item?.channel === '头条' ? '#f50' : item?.channel === '抖音' ? '#2db7f5' : item?.channel === '广点通' ? '#87d068' : item?.channel === '小程序' ? '#108ee9' : item?.channel === '公众平台流量' ? 'green' : 'orange' }}>{item?.channel || '未知'}</span>}
                                                            </Space>
                                                        </div>
                                                    </div>
                                                </>
                                            }
                                            className={style.meta}
                                        />
                                    </Card>
                                    }
                                </div>
                            })
                        }

                    </div>
                </div>
            </div>
            {/* </Checkbox.Group> */}
        </Spin>
        <div className="pagin"><Pagination size="small" onChange={pageChange} current={pageNum} pageSize={pageSize} pageSizeOptions={['8', '16', '32', '64']} total={getMediasList?.data?.total} showSizeChanger showQuickJumper /></div>
        {checkedList?.length > 0 && listParams?.type === 1 && <div className={style.selected}>
            <div className={style.title}>已选图片{checkedList?.length}/{num}张</div>
            <AntImage.PreviewGroup>
                {
                    checkedList?.map((item: any, index: number) => (
                        <div key={index} className={style.antImg}>
                            <CloseCircleFilled className={style.clear} onClick={() => { clearImg(item?.content) }} />
                            <AntImage
                                className={style.imgAnt}
                                width={80}
                                height={80}
                                src={item?.content}
                            />
                        </div>
                    ))
                }

            </AntImage.PreviewGroup>
        </div>}
    </Modal>
}

export default React.memo(SelectImg)