import { useAjax } from "@/Hook/useAjax"
import { getRemoteMaterialListApi, getRemoteMaterialTotalApi } from "@/services/adqV3/cloudNew"
import React, { useEffect, useRef, useState } from "react"
import style from '../cloudNew/index.less'
import Search from "./search"
import { Button, Card, Checkbox, Divider, Dropdown, Empty, Form, message, Pagination, Popover, Radio, Select, Space, Spin, Statistic, Typography, Image, Tag, Table } from "antd"
import { EyeOutlined, SortAscendingOutlined } from "@ant-design/icons"
import PlayVideo from "../cloudNew/playVideo"
import { formatBytes, formatSecondsToTime } from "@/utils/utils"
import { useLocalStorageState, useSize } from "ahooks"
import { defaultFiledList, fieldData, showFieldList } from "./const"
import Lazyimg from "react-lazyimg-component"
import '../cloudNew/global.less'
import SaveMaterial from "./saveMaterial"
import columns12 from "./tableConfig"
import TablePro from "@/components/TablePro"
const { Text, Paragraph } = Typography;

const Tencent: React.FC = () => {

    /*******************************/
    const ref = useRef<HTMLDivElement>(null);
    const size = useSize(ref);
    const ref1 = useRef<HTMLDivElement>(null);
    const size1 = useSize(ref1);
    const [rowNum, setRowNum] = useState<number>(0)
    const [queryParams, setQueryParams] = useState<CLOUDNEW.GetRemoteMaterialListProps>({ pageNum: 1, pageSize: 50 })
    const [searchParams, setSearchParams] = useState<Partial<CLOUDNEW.GetRemoteMaterialListProps>>({})
    const [checkedFolderList, setCheckedFolderList] = useState<any[]>([])
    const [checkFolderAll, setCheckFolderAll] = useState<boolean>(false);
    const [indeterminateFolder, setIndeterminateFolder] = useState<boolean>(false);
    const [showField, setShowField] = useLocalStorageState<string[]>('show-tencent-field', ['material_data.cost', 'material_data.view_count', 'material_data.valid_click_count', 'material_data.order_pv', 'calculate_material_data.order_rate']);
    const [sortData, setSortData] = useLocalStorageState<{ sortField: string | undefined, sortType: boolean }>('sort-tencent-data', { sortField: undefined, sortType: false });
    const [previewData, setPreviewData] = useState<{ visible: boolean, url?: string }>({ visible: false })
    const [moveData, setMoveData] = useState<{ visible: boolean, data: any[] }>({ visible: false, data: [] })
    const [pageShowType, setPageShowType] = useLocalStorageState<'List' | 'Kanban'>('PAGE_SHOW_TYPE', 'Kanban');
    const [totalData, setTotalData] = useState<any[]>([{ id: 1, preview: '总计' }])

    const getRemoteMaterialList = useAjax((params) => getRemoteMaterialListApi(params))
    const getRemoteMaterialTotal = useAjax((params) => getRemoteMaterialTotalApi(params))
    /*******************************/

    useEffect(() => {
        getList()
    }, [queryParams, searchParams, sortData, showField, pageShowType])

    const getList = () => {
        let params = { ...queryParams, ...searchParams, columns: showField || [] }
        if (pageShowType === 'List') {
            let saveColumns = localStorage.getItem('myAdMonitorConfig1.0.0_云端素材')
            let fieldList = defaultFiledList
            if (saveColumns) {
                fieldList = JSON.parse(saveColumns)?.map((item: { dataIndex: any }) => item.dataIndex).filter((key: string) => !['preview', 'pitcher_name'].includes(key))
            }
            params.columns = fieldList.map(key => fieldData[key as keyof typeof fieldData])
        } else {
            if (sortData?.sortField) {
                params = { ...params, ...sortData }
            }
        }
        getRemoteMaterialList.run(params)
        getRemoteMaterialTotal.run(params).then((res: { data: { id: number; preview: string } }) => {
            if (res) {
                let data: any = res
                data.id = 1
                data.preview = '总计'
                setTotalData([data])
            } else {
                setTotalData([{ id: 1, preview: '总计' }])
            }
        })
    }

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

    // 处理全选按钮状态
    useEffect(() => {
        let data: any[] = getRemoteMaterialList?.data?.records || []
        let dataIds = data.map(item => item.preview_url)
        let selectIds = checkedFolderList.map(item => item.preview_url)
        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, getRemoteMaterialList?.data?.records])

    // 选择
    const onCheckboxChange = (checked: boolean, item: any) => {
        let newCheckedFolderList: any[] = JSON.parse(JSON.stringify(checkedFolderList))
        if (checked) { // 选中
            newCheckedFolderList.push(item)
        } else { // 取消
            newCheckedFolderList = newCheckedFolderList.filter(i => i.preview_url !== item.preview_url)
        }
        setCheckedFolderList(newCheckedFolderList)
    };

    return <div className={style.cloudNew_layout} ref={ref1}>
        {/* 搜索 */}
        <Search
            pageShowType={pageShowType}
            setPageShowType={setPageShowType}
            onSearch={(value) => { setSearchParams(value) }}
        />
        {pageShowType === 'Kanban' ? <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}>
                <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[] = getRemoteMaterialList?.data?.records

                                    if (e.target.checked) { // 全选
                                        newCheckedFolderList.push(...data)
                                        newCheckedFolderList = Array.from(new Set(newCheckedFolderList.map(item => JSON.stringify(item)))).map(item => JSON.parse(item));
                                    } else { // 取消全选
                                        const dataIds = data.map(item => item.preview_url)
                                        newCheckedFolderList = newCheckedFolderList.filter(i => !dataIds.includes(i.preview_url))
                                    }
                                    setCheckedFolderList(newCheckedFolderList)
                                }}
                                indeterminate={indeterminateFolder}
                                checked={checkFolderAll}
                            >全选</Checkbox>
                            <span>已选 <span style={{ color: '#1890FF' }}>{checkedFolderList?.length || 0}</span> 个素材</span>
                            {checkedFolderList.length > 0 && <a style={{ color: 'red' }} onClick={() => setCheckedFolderList([])}>清除所有</a>}
                            {sortData?.sortField && <Text>「排序-{showFieldList.find(item => item.field === sortData.sortField)?.label}-{sortData.sortType ? '正序' : '倒序'}」</Text>}
                        </div>
                        <div className={style.left_bts}>
                            {checkedFolderList.length > 0 && <Button
                                type="primary"
                                onClick={() => {
                                    setMoveData({ visible: true, data: checkedFolderList })
                                }}
                            >保存至素材库</Button>}
                            <Popover
                                content={<div style={{ width: 400 }}>
                                    <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 > 8) {
                                                        message.warn('最多只能选择8个指标')
                                                        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: 180 }}
                                                    placeholder="选择排序指标"
                                                    showSearch
                                                    filterOption={(input, option) =>
                                                        (option?.label as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                                    }
                                                    options={showFieldList.filter(item => showField.includes(item.value)).map(item => ({ label: item.label, value: item.field }))}
                                                    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={getRemoteMaterialList.loading}>
                            <div className={style.content_scroll} ref={ref}>
                                {getRemoteMaterialList?.data?.records?.length > 0 ? <Checkbox.Group value={checkedFolderList?.map(item => item.preview_url)} style={{ width: '100%' }}>
                                    <div className={style.content_scroll_div}>
                                        {getRemoteMaterialList?.data?.records.map((item: any, index: number) => {
                                            const isSelect = checkedFolderList?.map(item => item.preview_url).includes(item.preview_url)
                                            return <div key={(queryParams.pageNum).toString() + (index + 1).toString()} className={style.content_row} style={{ width: rowNum ? (1 / rowNum * 100) + '%' : 230 }}>
                                                <Card
                                                    hoverable
                                                    bodyStyle={{ padding: 0 }}
                                                    className={`${style.content_col}`}
                                                    cover={<div style={{ height: 120, padding: 0 }} className={style.content_cover}>
                                                        <div className={style.checkbox}><Checkbox value={item.preview_url} onChange={(e) => onCheckboxChange(e.target.checked, item)} /></div>
                                                        {item.source === 'video' ? <div className={style.playr}>
                                                            <PlayVideo videoUrl={item.preview_url}>{(onPlay) => <img onClick={(e) => {
                                                                e.stopPropagation(); e.preventDefault()
                                                                onPlay()
                                                            }} src={require('../../../../../public/image/play.png')} alt="" />}</PlayVideo>
                                                        </div> : <div className={style.imgPreview} onClick={(e) => {
                                                            e.stopPropagation()
                                                            setPreviewData({ visible: true, url: item.preview_url })
                                                        }}>
                                                            <Space><EyeOutlined /><span>预览</span></Space>
                                                        </div>}
                                                        <div className={style.file_info}>
                                                            <div>{item.width}*{item.height}</div>
                                                            {item.source === 'video' && item.image_duration_millisecond && <div>{formatSecondsToTime(Math.floor(item.image_duration_millisecond / 1000))}</div>}
                                                        </div>
                                                        <Lazyimg
                                                            animateType="transition"
                                                            src={item.source === 'image' ? item.preview_url : item?.key_frame_image_url}
                                                            className={`${style.coverImg} lazy`}
                                                            animateClassName={['transition-enter', 'transition-enter-active']}
                                                        />
                                                    </div>}
                                                    onClick={() => onCheckboxChange(!isSelect, item)}
                                                >
                                                    <div className={style.body}>
                                                        <Text ellipsis strong style={{ flex: '1 0' }}>{item?.description}</Text>
                                                        <Text style={{ fontSize: 12 }}>{formatBytes(item?.file_size)}</Text>
                                                    </div>
                                                    <Divider style={{ margin: '0 0 4px 0' }} />
                                                    <div style={{ padding: '0 10px 6px' }}>
                                                        <div style={{ display: 'flex', marginBottom: 1 }}>
                                                            <div style={{ maxWidth: 120, display: 'flex' }}><Paragraph ellipsis={{ tooltip: { mouseEnterDelay: 0.5, placement: 'bottom' } }} style={{ fontSize: 12, marginBottom: 0 }}>设计师</Paragraph>：</div>
                                                            <div style={{ flex: '1 0' }}>{item?.create_name || '--'}</div>
                                                        </div>
                                                        {showFieldList.filter(f => showField.includes(f.value)).map(f => {
                                                            return <div key={f.value} style={{ display: 'flex', marginBottom: 1 }}>
                                                                <div style={{ maxWidth: 120, display: 'flex' }}><Paragraph ellipsis={{ tooltip: { mouseEnterDelay: 0.5, placement: 'bottom' } }} style={{ fontSize: 12, marginBottom: 0 }}>{f.label}</Paragraph>：</div>
                                                                <div style={{ flex: '1 0' }}>{f?.isRate ? <Statistic valueStyle={{ fontSize: 12 }} value={item?.[f.field] * 100} precision={2} suffix="%" /> : <Statistic valueStyle={{ fontSize: 12 }} value={item?.[f.field]} />} </div>
                                                            </div>
                                                        })}
                                                    </div>
                                                    <Divider style={{ margin: '0 0 4px 0' }} />
                                                    <div className={style.actions}>
                                                        <div style={{ height: 22, fontSize: 12 }}>
                                                            投手：{item.pitcher_name}
                                                        </div>
                                                        <Dropdown menu={{
                                                            items: [{ label: '保存至素材库', key: '1', onClick: () => { setMoveData({ visible: true, data: [item] }) } }]
                                                        }}>
                                                            <a onClick={e => e.preventDefault()} style={{ fontSize: 11 }}>更多</a>
                                                        </Dropdown>
                                                    </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={getRemoteMaterialList?.data?.total || 0}
                            showSizeChanger
                            showQuickJumper
                            pageSize={getRemoteMaterialList?.data?.size || 20}
                            current={getRemoteMaterialList?.data?.current || 1}
                            onChange={(page: number, pageSize: number) => {
                                ref.current?.scrollTo({ top: 0 })
                                setTimeout(() => setQueryParams({ ...queryParams, pageNum: page, pageSize }), 50)
                            }}
                            showTotal={(total: number) => <span style={{ fontSize: 12 }}>共 {total} 条</span>}
                        />
                    </div>
                </div>
            </div>
        </Card> : <TablePro
            leftChild={<div></div>}
            refreshAjax={getList}
            isZj
            totalData={totalData}
            config={columns12()}
            fixed={{ left: 1, right: 0 }}
            scroll={{ x: 1000, y: size1.height ? size1.height - 270 : 580 }}
            configName='云端素材'
            loading={getRemoteMaterialList.loading}
            ajax={getRemoteMaterialList}
            page={getRemoteMaterialList?.data?.current || 1}
            pageSize={getRemoteMaterialList?.data?.size || 20}
            total={getRemoteMaterialList?.data?.total || 0}
            dataSource={getRemoteMaterialList?.data?.records?.map((item: any, index: number) => ({ ...item, id: Number(queryParams.pageNum.toString() + (index + '')) }))}
            onChange={(pagination: any, _: any, sortData: any) => {
                let { current, pageSize } = pagination
                let newQueryForm = JSON.parse(JSON.stringify(queryParams))
                if (sortData && sortData?.order) {
                    newQueryForm['sortType'] = sortData?.order === 'ascend' ? true : false
                    newQueryForm['sortField'] = sortData?.field
                } else {
                    delete newQueryForm['sortType']
                    delete newQueryForm['sortField']
                }
                newQueryForm.pageNum = current || newQueryForm.pageNum
                newQueryForm.pageSize = pageSize || newQueryForm.pageSize
                setQueryParams({ ...newQueryForm })
            }}
        />}

        {/* 预览 */}
        {previewData.visible && <Image
            width={200}
            style={{ display: 'none' }}
            preview={{
                visible: previewData.visible,
                src: previewData.url,
                onVisibleChange: value => {
                    setPreviewData({ visible: false })
                },
            }}
        />}

        {/* 移动至 */}
        {moveData.visible && <SaveMaterial
            {...moveData}
            onChange={() => {
                setMoveData({ visible: false, data: [] })
            }}
            onClose={() => {
                setMoveData({ visible: false, data: [] })
            }}
        />}
    </div>
}

export default Tencent