import { Button, Card, Checkbox, Divider, Empty, Form, message, Modal, Pagination, Popover, Radio, Select, Space, Spin, Tooltip, Typography } from "antd"
import React, { useEffect, useRef, useState } from "react"
import { useAjax } from "@/Hook/useAjax"
import { getMaterialDataListApi } from "@/services/adqV3/cloudNew"
import style from './index.less'
import SelectSearch from "./selectSearch"
import './global.less'
import '../../tencentAdPutIn/index.less'
import { useLocalStorageState, useSize } from "ahooks"
import useFileDrop from "@/Hook/useFileDrop"
import { formatBytes, formatSecondsToTime, getVideoImgUrl } from "@/utils/utils"
import UploadFile from "./uploadFile"
import { useModel } from "umi"
import UploadsTable from "./uploadsTable"
import { DeleteOutlined, PlayCircleOutlined, SortAscendingOutlined } from "@ant-design/icons"
import PlayVideo from "./playVideo"
import { showFieldList } from "./const"
import SelectFolder from "./selectFolder"
import SelectGroupCloudNew from "./selectGroupCloudNew"
import SelectGroupUnitNew from "./selectGroupUnitNew"


const { Text, Paragraph } = Typography;

/**
 * 选择素材
 * @param param0 
 * @returns 
 */
const SelectCloudNew: React.FC<CLOUDNEW.SelectCloudNewProps> = ({ visible, defaultParams, num, sliderImgContent, isGroup, onChange, onClose, accountCreateLogs, putInType }) => {

    /************************************/
    const { initialState } = useModel('@@initialState');
    const ref = useRef<HTMLDivElement>(null);
    const size = useSize(ref);
    const [checkedFolderList, setCheckedFolderList] = useState<any[]>([])
    const [checkFolderAll, setCheckFolderAll] = useState<boolean>(false);
    const [indeterminateFolder, setIndeterminateFolder] = useState<boolean>(false);
    const [rowNum, setRowNum] = useState<number>(0)
    const [SCKType, setSCKType] = useState<'1' | '2'>('1')

    const [queryParams, setQueryParams] = useState<CLOUDNEW.GetMaterialDataListProps>({ pageNum: 1, pageSize: 20 })
    const [searchParams, setSearchParams] = useState<Partial<CLOUDNEW.GetMaterialDataListProps>>({})
    const [uploadVisible, setUploadVisible] = useState<boolean>(false)
    const [showField, setShowField] = useLocalStorageState<string[]>('show-field', ['material.create_time', 'material_data_day.cost', 'material_data_day.ctr', 'material_data_day.conversions_rate', 'material_data_day.dynamic_creative_count']);
    const [sortData, setSortData] = useLocalStorageState<{ sortField: string | undefined, sortType: boolean }>('sort-data', { sortField: undefined, sortType: false });
    const [active, setActive] = useState<number>()
    const [isShowAll, setIsShowAll] = useState<boolean>(false)

    const getMaterialDataList = useAjax((params) => getMaterialDataListApi(params))
    /************************************/

    useEffect(() => {
        if (sliderImgContent && sliderImgContent?.length > 0) {
            setCheckedFolderList(sliderImgContent as any || [])
        }
    }, [])

    useEffect(() => {
        let params = { ...searchParams, ...defaultParams, ...queryParams }
        if (sortData?.sortField) {
            params = { ...params, ...sortData }
        }
        if (params?.sizeList?.length) {
            params.sizeQueries = params.sizeList.map(item => {
                const [width, height, relation] = item.split('*')
                return { width: Number(width), height: Number(height), relation: relation || '=' }
            })
        }
        delete params?.sizeList
        if (isShowAll) {
            delete params?.sizeQueries
        }
        getMaterialDataList.run(params)
    }, [queryParams, defaultParams, searchParams, sortData, showField, isShowAll])

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

    // 处理全选按钮状态
    useEffect(() => {
        let data: any[] = getMaterialDataList?.data?.records || []
        let dataIds = data.map(item => item.id)
        let selectIds = checkedFolderList.map(item => item.id)
        if (selectIds.length === 0 || dataIds.length === 0) {
            setCheckFolderAll(false)
            setIndeterminateFolder(false);
        } else if (dataIds.every((element) => selectIds.includes(element))) {
            setCheckFolderAll(true)
            setIndeterminateFolder(false);
        } else if (dataIds.some((element) => selectIds.includes(element))) {
            setCheckFolderAll(false)
            setIndeterminateFolder(true);
        } else {
            setCheckFolderAll(false)
            setIndeterminateFolder(false);
        }
    }, [checkedFolderList, getMaterialDataList?.data?.records])

    const handleOk = () => {
        if (isGroup && num && checkedFolderList && num > checkedFolderList?.length) {
            message.error(`当前选择了组图${num}图，当前选择了${checkedFolderList.length}个图片`)
            return
        }
        onChange?.(checkedFolderList)
    }

    // 选择
    const onCheckboxChange = (checked: boolean, item: any) => {
        let newCheckedFolderList: any[] = JSON.parse(JSON.stringify(checkedFolderList))
        if (active || active === 0) {
            if (checked) { // 选中
                newCheckedFolderList[active] = { ...item, materialType: 0 }
            } else { // 取消
                message.warning('请选择其他图片替换')
                return
            }
        } else {
            if (checked) { // 选中
                newCheckedFolderList.push({ ...item, materialType: 0 })
            } else { // 取消
                newCheckedFolderList = newCheckedFolderList.filter(i => i.id !== item.id)
            }
        }
        setCheckedFolderList(newCheckedFolderList)
    };

    // 获取拖拽的文件
    const [fileList, setFileList] = useState<FileList>()
    const [uploadsVisible, setUploadsVisible] = useState<boolean>(false)
    const { isDragOver, dropAreaProps } = useFileDrop((fileList) => {
        setFileList(fileList)
        setUploadsVisible(true)
    });

    return <Modal
        title={<div className={'SCK_header'}>
            {[{ label: '素材库', value: '1' }, { label: '账户组媒体素材', value: '2' }, { label: '业务单元素材', value: '3' }].map(item => <div
                className={item.value === SCKType ? 'selected' : ''}
                key={item.value}
                onClick={() => {
                    setSCKType(item.value as any)
                    // setCheckedFolderList([])
                }}>
                {item.label}
            </div>)}
            {SCKType === '1' && <div><a style={{ marginLeft: 20, fontWeight: 'normal' }} onClick={() => setUploadVisible(true)}>上传素材</a></div>}
        </div>}
        open={visible}
        onCancel={onClose}
        width={1400}
        maskClosable={false}
        footer={<div className={style.divFooter}>
            {checkedFolderList.length > 0 ? <>
                <div className={style.selectedCloud}>
                    <div style={{ width: checkedFolderList.length * 58 + (checkedFolderList.length - 1) * 8 }}>
                        {checkedFolderList.map((item, index) => <div key={item.id + '_' + index} className={`${style.selectedCloud_col} ${active === index ? style.active : ''}`} onClick={() => isGroup && setActive(index)}>
                            <div className={style.cz}>
                                {item.material_type === 'video' && <PlayVideo videoUrl={item.oss_url}>{(onPlay) => <a onClick={onPlay}><PlayCircleOutlined /></a>}</PlayVideo>}
                                <a style={{ color: 'red' }} onClick={() => setCheckedFolderList(data => data.filter(i => i.id !== item.id))}><DeleteOutlined /></a>
                            </div>
                            <img src={item.material_type === 'image' ? item.oss_url : item.materialType === 1 ? item.key_frame_image_url : getVideoImgUrl(item.oss_url)} className={style.coverImg} alt="" />
                        </div>)}
                    </div>
                </div>
                {!!active && <a style={{ color: 'red' }} onClick={() => setActive(undefined)}>清除单独修改</a>}
                <a style={{ color: 'red' }} onClick={() => setCheckedFolderList([])}>清除所有</a>
            </> : <div></div>}
            <Space>
                <Button onClick={onClose}>取消</Button>
                <Button type="primary" onClick={handleOk} disabled={checkedFolderList.length === 0}>确定</Button>
            </Space>
        </div>}
        className={`modalResetCss selectModal SCK`}
        bodyStyle={{ backgroundColor: '#f1f4fc', height: 700, overflow: 'hidden', padding: '10px' }}
    >
        {SCKType === '1' ? <div className={style.select_cloudNew_layout}>
            {/* 搜索 */}
            <SelectSearch
                sizeQueries={defaultParams?.sizeQueries}
                onSearch={(value) => {
                    ref.current?.scrollTo(0, 0)
                    setSearchParams(value)
                }}
            />

            <Card
                style={{ height: '100%', flex: '1 0', overflow: 'hidden' }}
                bodyStyle={{ padding: 0, overflow: 'auto hidden', height: '100%' }}
                className="cardResetCss buttonResetCss"
                bordered
            >
                <div className={style.cloudNew}>
                    {/* 选择文件夹 */}
                    <SelectFolder selectedKeys={queryParams?.folderId} onChange={(value) => { setQueryParams({ ...queryParams, folderId: value, pageNum: 1 }) }} />
                    <div className={style.material} style={{ height: '100%' }}>
                        <div className={style.operates}>
                            <div className={style.left_bts}>
                                <Checkbox
                                    onChange={(e) => {
                                        let newCheckedFolderList: any[] = JSON.parse(JSON.stringify(checkedFolderList))
                                        const data: any[] = getMaterialDataList?.data?.records

                                        if (e.target.checked) { // 全选
                                            const selectIds = newCheckedFolderList.map(item => item.id)
                                            const remainData = data.filter(item => !selectIds.includes(item.id))
                                            const remainDataLength = remainData.length
                                            const remainNum = num - newCheckedFolderList.length
                                            if (remainNum > remainDataLength) {
                                                newCheckedFolderList.push(...remainData.map(item => ({ ...item, materialType: 0 })))
                                            } else {
                                                newCheckedFolderList.push(...remainData.splice(0, remainNum).map(item => ({ ...item, materialType: 0 })))
                                            }
                                            newCheckedFolderList = Array.from(new Set(newCheckedFolderList.map(item => JSON.stringify(item)))).map(item => JSON.parse(item));
                                        } else { // 取消全选
                                            const dataIds = data.map(item => item.id)
                                            newCheckedFolderList = newCheckedFolderList.filter(i => !dataIds.includes(i.id))
                                        }
                                        setCheckedFolderList(newCheckedFolderList)
                                    }}
                                    disabled={checkedFolderList?.length >= num || !!active || active === 0 || isShowAll}
                                    indeterminate={indeterminateFolder}
                                    checked={checkFolderAll}
                                >全选</Checkbox>
                                <span>已选 <span style={{ color: '#1890FF' }}>{checkedFolderList?.length || 0}</span>/{num} 个素材</span>
                                {checkedFolderList.length > 0 && <a style={{ color: 'red' }} onClick={() => setCheckedFolderList([])}>清除所有</a>}
                                {sortData?.sortField && <Text>「排序-{showFieldList.find(item => item.value === sortData.sortField)?.label}-{sortData.sortType ? '正序' : '倒序'}」</Text>}
                            </div>
                            <div className={style.left_bts}>
                                <Checkbox onChange={(e) => setIsShowAll(e.target.checked)} checked={isShowAll}>
                                    <Tooltip title="勾选只展示，不支持选择投放">
                                        <span style={{ fontSize: 12 }}>显示所有{defaultParams?.materialType === 'video' ? '视频' : '图片'}素材</span>
                                    </Tooltip>
                                </Checkbox>
                                <Popover
                                    content={<div style={{ width: 320 }}>
                                        <Form
                                            labelCol={{ span: 5 }}
                                            labelAlign="left"
                                            colon={false}
                                        >
                                            <Form.Item label={<strong>展示指标</strong>}>
                                                <Select
                                                    placeholder="选择展示指标"
                                                    showSearch
                                                    filterOption={(input, option) =>
                                                        (option?.label as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                    }
                                                    mode="multiple"
                                                    options={showFieldList}
                                                    value={showField}
                                                    onChange={(value) => {
                                                        if (value.length > 6) {
                                                            message.warn('最多只能选择6个指标')
                                                            return
                                                        }
                                                        if (value.length < 1) {
                                                            message.warn('最少选择1个指标')
                                                            return
                                                        }
                                                        setSortData({ ...sortData, sortField: undefined })
                                                        setShowField(value as any)
                                                    }}
                                                />
                                            </Form.Item>
                                            <Form.Item label={<strong>排序</strong>}>
                                                <Space>
                                                    <Select
                                                        style={{ width: 125 }}
                                                        placeholder="选择排序指标"
                                                        showSearch
                                                        filterOption={(input, option) =>
                                                            (option?.label as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                        }
                                                        options={showFieldList.filter(item => showField.includes(item.value) && item.value !== 'description')}
                                                        value={sortData.sortField}
                                                        allowClear
                                                        onChange={(value) => {
                                                            setSortData({ ...sortData, sortField: value as any })
                                                        }}
                                                    />
                                                    <Radio.Group value={sortData.sortType} onChange={(e) => setSortData({ ...sortData, sortType: e.target.value })} buttonStyle="solid">
                                                        <Radio.Button value={true}>正序</Radio.Button>
                                                        <Radio.Button value={false}>倒序</Radio.Button>
                                                    </Radio.Group>
                                                </Space>
                                            </Form.Item>
                                        </Form>
                                    </div>}
                                    trigger={['click']}
                                    title={<strong>自定义展示指标与排序</strong>}
                                    placement="bottomRight"
                                >
                                    <Button icon={<SortAscendingOutlined />}>自定义展示指标与排序</Button>
                                </Popover>
                            </div>
                        </div>
                        <div className={`${style.content} content_global`}>
                            <Spin spinning={getMaterialDataList.loading}>
                                <div className={style.content_scroll} ref={ref} {...dropAreaProps}>
                                    {isDragOver && <div className={`${style.placeholder} ${isDragOver ? style.dragOver : ''}`}><span>拖动文件到这里</span></div>}
                                    {getMaterialDataList?.data?.records?.length > 0 ? <Checkbox.Group value={checkedFolderList?.filter((_, index) => (active || active === 0) ? index === active : true)?.map(item => item.id)} style={{ width: '100%' }}>
                                        <div className={style.content_scroll_div}>
                                            {getMaterialDataList?.data?.records.map((item: any) => {
                                                const isSelect = checkedFolderList?.filter((_, index) => (active || active === 0) ? index === active : true)?.map(item => item.id).includes(item.id)
                                                const disabled = ((active || active === 0) ? false : (checkedFolderList.length >= num && !isSelect)) || isShowAll
                                                return <div key={item.id} className={style.content_row} style={{ width: rowNum ? (1 / rowNum * 100) + '%' : 200 }}>
                                                    <Card
                                                        hoverable
                                                        bodyStyle={{ padding: 0 }}
                                                        style={{ cursor: disabled ? 'not-allowed' : 'pointer' }}
                                                        className={`${style.content_col}`}
                                                        cover={<div style={{ height: 120, padding: 0 }} className={style.content_cover}>
                                                            <div className={style.checkbox}><Checkbox disabled={disabled} value={item.id} onChange={(e) => onCheckboxChange(e.target.checked, item)} /></div>
                                                            {item.material_type === 'video' && <div className={style.playr}>
                                                                <PlayVideo videoUrl={item.oss_url}>{(onPlay) => <img onClick={(e) => {
                                                                    e.stopPropagation(); e.preventDefault()
                                                                    onPlay()
                                                                }} src={require('../../../../../public/image/play.png')} alt="" />}</PlayVideo>
                                                            </div>}
                                                            <div className={style.file_info}>
                                                                <div>{item.width}*{item.height}</div>
                                                                {item.material_type === 'video' && <div>{formatSecondsToTime(Math.floor(item.video_duration))}</div>}
                                                            </div>
                                                            <img src={item.material_type === 'image' ? item.oss_url : getVideoImgUrl(item.oss_url)} className={style.coverImg} alt="" />
                                                        </div>}
                                                        onClick={() => !disabled && onCheckboxChange(!isSelect, item)}
                                                    >
                                                        <div className={style.body}>
                                                            <Text ellipsis strong style={{ flex: '1 0' }}>{item?.material_name}</Text>
                                                            <Text style={{ fontSize: 12 }}>{formatBytes(item?.file_size)}</Text>
                                                        </div>
                                                        <Divider style={{ margin: '0 0 4px 0' }} />
                                                        <div style={{ padding: '0 10px 6px' }}>
                                                            {showField.map(field => {
                                                                switch (field) {
                                                                    case 'material.create_time':
                                                                        return <Paragraph key={field} style={{ fontSize: 12, marginBottom: 1 }}>创建时间：{item?.create_time}</Paragraph>
                                                                    case 'material_data_day.cost':
                                                                        return <Paragraph key={field} style={{ fontSize: 12, marginBottom: 1 }}>消耗：{(item?.cost === null || item?.cost === undefined) ? '--' : item?.cost}</Paragraph>
                                                                    case 'material_data_day.order_pv':
                                                                        return <Paragraph key={field} style={{ fontSize: 12, marginBottom: 1 }}>下单次数：{(item?.order_pv === null || item?.order_pv === undefined) ? '--' : item?.order_pv}</Paragraph>
                                                                    case 'material_data_day.order_cost':
                                                                        return <Paragraph key={field} style={{ fontSize: 12, marginBottom: 1 }}>下单成本：{(item?.order_cost === null || item?.order_cost === undefined) ? '--' : item?.order_cost}</Paragraph>
                                                                    case 'material_data_day.ctr':
                                                                        return <Paragraph key={field} style={{ fontSize: 12, marginBottom: 1 }}>点击率：{(item?.ctr === null || item?.ctr === undefined) ? '--' : (item?.ctr * 100).toFixed(2) + '%'}</Paragraph>
                                                                    case 'material_data_day.conversions_rate':
                                                                        return <Paragraph key={field} style={{ fontSize: 12, marginBottom: 1 }}>目标转化率：{(item?.conversions_rate === null || item?.conversions_rate === undefined) ? '--' : (item?.conversions_rate * 100).toFixed(2) + '%'}</Paragraph>
                                                                    case 'material_data_day.adgroup_count':
                                                                        return <Paragraph key={field} style={{ fontSize: 12, marginBottom: 1 }}>广告关联数：{(item?.adgroup_count === null || item?.adgroup_count === undefined) ? '--' : item?.adgroup_count}</Paragraph>
                                                                    case 'material_data_day.dynamic_creative_count':
                                                                        return <Paragraph key={field} style={{ fontSize: 12, marginBottom: 1 }}>创意关联数：{(item?.dynamic_creative_count === null || item?.dynamic_creative_count === undefined) ? '--' : item?.dynamic_creative_count}</Paragraph>
                                                                    default:
                                                                        return null
                                                                }
                                                            })}
                                                            {showField.includes('description') && <Paragraph style={{ fontSize: 12, marginBottom: 1 }} ellipsis={{ tooltip: true }}>备注：{item.description || '--'}</Paragraph>}
                                                        </div>
                                                    </Card>
                                                </div>
                                            })}
                                        </div>
                                    </Checkbox.Group> : <div style={{ height: '100%', width: '100%', alignContent: 'center' }}><Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /></div>}
                                </div>
                            </Spin>
                        </div>
                        <div className={style.fotter}>
                            <Pagination
                                size="small"
                                total={getMaterialDataList?.data?.total || 0}
                                showSizeChanger
                                showQuickJumper
                                pageSize={getMaterialDataList?.data?.size || 20}
                                current={getMaterialDataList?.data?.current || 1}
                                onChange={(page: number, pageSize: number) => {
                                    ref.current?.scrollTo(0, 0)
                                    setQueryParams({ ...queryParams, pageNum: page, pageSize })
                                }}
                                pageSizeOptions={[10, 15, 20, 50, 100]}
                            />
                        </div>
                    </div>
                </div>
            </Card>
        </div> : SCKType === '2' ? <SelectGroupCloudNew
            num={num}
            defaultParams={defaultParams}
            checkedFolderList={checkedFolderList}
            setCheckedFolderList={setCheckedFolderList}
            accountCreateLogs={accountCreateLogs}
            putInType={putInType}
            active={active}
        /> : <SelectGroupUnitNew
            num={num}
            defaultParams={defaultParams}
            checkedFolderList={checkedFolderList}
            setCheckedFolderList={setCheckedFolderList}
            accountCreateLogs={accountCreateLogs}
            putInType={putInType}
            active={active}
        />}


        {/* 上传素材 */}
        {uploadVisible && <UploadFile
            userId={(initialState?.currentUser?.userId || 0) as number}
            visible={uploadVisible}
            onChange={() => {
                setUploadVisible(false)
                getMaterialDataList.refresh()
            }}
            onClose={() => {
                setUploadVisible(false)
            }}
        />}

        {/* 拖动上传 */}
        {uploadsVisible && <UploadsTable
            userId={(initialState?.currentUser?.userId || 0) as number}
            visible={uploadsVisible}
            fileList={fileList}
            isPermission={true}
            onClose={() => {
                setUploadsVisible(false)
                setFileList(undefined)
            }}
            onChange={() => {
                setUploadsVisible(false)
                setFileList(undefined)
                getMaterialDataList.refresh()
            }}
        />}
    </Modal>
}

export default React.memo(SelectCloudNew)