import React, { useEffect, useRef, useState } from "react"
import '../../tencentAdPutIn/index.less'
import { Button, Card, DatePicker, Input, message, Pagination, Popconfirm, Select, Space, Tabs } from "antd"
import { delComponentApi, getCreativeComponentDataListApi, GetCreativeComponentProps } from "@/services/adqV3/global"
import './index.less'
import { DeleteOutlined, PlusOutlined, SyncOutlined } from "@ant-design/icons"
import { useAjax } from "@/Hook/useAjax"
import SelectAdAccount from "@/components/SelectAdAccount"
import { COMMON_POTENTIAL_STATUS_ENUM, COMPONENT_GENERATION_TYPE_ENUM, DEFAULT_COMPONENT_SUB_IMAGE_TYPE, DEFAULT_COMPONENT_SUB_SHOW_IMAGE, DEFAULT_COMPONENT_SUB_SHOW_TEXT, DEFAULT_COMPONENT_SUB_SHOW_VIDEO, DEFAULT_COMPONENT_SUB_VIDEO_TYPE } from "./const"
import moment from "moment"
import { useDebounce, useSize } from "ahooks"
import AddComponents from "./addComponents"
import { DefaultOptionType } from "antd/lib/select"
import TablePro from "@/components/TablePro"
import columns12 from "./tableConfig"
import ShareComponent from "./shareComponent"
import ShareDetails from "./shareDetails"
import SyncCloudComponent from "../../material/cloudNew/syncCloudComponent"

/**
 * 创意组件
 * @returns 
 */
const ManageComponent: React.FC = () => {

    /*************************************/
    const [queryParams, setQueryParams] = React.useState<GetCreativeComponentProps>({ pageNum: 1, pageSize: 20, activeKey: 'IMAGE' })
    const [idSting, setIdSting] = useState<string>();
    const debouncedIdSting = useDebounce(idSting, { wait: 500 });
    const [componentIdSting, setComponentIdSting] = useState<string>();
    const debouncedComponentIdStingSting = useDebounce(componentIdSting, { wait: 500 });
    const ref = useRef<HTMLDivElement>(null);
    const size = useSize(ref);
    const ref1 = useRef<HTMLDivElement>(null);
    const size1 = useSize(ref1);
    const [tableHeaderHeight, setTableHeaderHeight] = useState<number>(0)
    const [addVisible, setAddVisible] = useState<boolean>(false)
    const [loading, setLoading] = useState<boolean>(true)
    const [adAccount, setAdccount] = useState<any>()
    const [shareData, setShareData] = useState<{ visible: boolean, data: any }>({ visible: false, data: null })
    const [shareDetailsData, setShareDetailsData] = useState<{ visible: boolean, data: any }>({ visible: false, data: null })
    const [putInType, setPutInType] = useState<'NOVEL' | 'GAME'>('NOVEL')
    const [selectedRows, setSelectedRows] = useState<any[]>([])

    const getCreativeComponentList = useAjax((params) => getCreativeComponentDataListApi(params))
    const delComponent = useAjax((params) => delComponentApi(params))
    /*************************************/

    useEffect(() => {
        if (queryParams?.adAccountId) {
            const { activeKey, componentSubType, ...params } = queryParams
            if (debouncedIdSting) {
                params[activeKey === 'IMAGE' ? 'imageId' : 'videoId'] = debouncedIdSting.split(/[,，\n\s]+/ig).filter((item: any) => item)
            } else {
                delete params?.[activeKey === 'IMAGE' ? 'imageId' : 'videoId']
            }
            if (debouncedComponentIdStingSting) {
                params['componentId'] = debouncedComponentIdStingSting.split(/[,，\n\s]+/ig).filter((item: any) => item)
            } else {
                delete params?.['componentId']
            }
            getCreativeComponentList.run({ ...params, componentSubType: componentSubType && componentSubType?.length > 0 ? componentSubType : (activeKey === 'IMAGE' ? DEFAULT_COMPONENT_SUB_SHOW_IMAGE : activeKey === 'VIDEO' ? DEFAULT_COMPONENT_SUB_SHOW_VIDEO : DEFAULT_COMPONENT_SUB_SHOW_TEXT) })
        }
    }, [queryParams, debouncedIdSting, debouncedComponentIdStingSting])

    useEffect(() => {
        // 1. 通过选择器获取目标元素
        const element = document.querySelector('.ant-table-header');
        if (!element) return;

        // 2. 创建 ResizeObserver
        const observer = new ResizeObserver((entries) => {
            for (const entry of entries) { // 遍历 entries 数组
                const observedHeight = entry.contentRect.height; // 提取 contentRect
                setTableHeaderHeight(observedHeight)
            }
        });

        // 3. 开始观察
        observer.observe(element);

        // 4. 清理函数
        return () => {
            observer.unobserve(element);
            observer.disconnect();
        };
    }, [])

    const handleDel = (id: number[], accountId: number) => {
        const hide = message.loading('正在删除...', 0)
        delComponent.run({ componentId: id, adAccountId: accountId }).then(res => {
            hide()
            if (res?.length === 0) {
                message.success('删除成功')
                getCreativeComponentList.refresh()
            } else {
                message.error(res?.join('、'))
            }
        }).catch(() => hide())
    }

    const share = (data: any) => {
        setShareData({ visible: true, data })
    }

    const shareDetails = (data: any) => {
        setShareDetailsData({ visible: true, data })
    }

    return <div className="manageComponent">
        <Card
            className="cardResetCss"
            bodyStyle={{ paddingBottom: 0, paddingTop: 0 }}
        >
            <Space>
                <Tabs
                    items={[
                        { label: '图片', key: 'IMAGE', children: false },
                        { label: '视频', key: 'VIDEO', children: false },
                        // { label: '文案', key: 'TEXT', children: false },
                    ]}
                    activeKey={queryParams?.activeKey}
                    onChange={(e) => {
                        setQueryParams({
                            ...queryParams,
                            activeKey: e
                        })
                    }}
                    style={{ marginRight: 40 }}
                />
                <SelectAdAccount
                    isReturnFirstValue
                    value={queryParams?.adAccountId ? [queryParams.adAccountId] : undefined}
                    type="radio"
                    onChange={(value, data) => {
                        setAdccount(data)
                        setPutInType(data?.adUnitType || 'NOVEL')
                        setLoading(false)
                        setQueryParams({
                            ...queryParams,
                            adAccountId: value as number,
                        })
                    }}
                    allowClear={false}
                    initialValues={{ adUnitAccount: 1 }}
                />
                <Button icon={<SyncOutlined />} type="link" onClick={() => { getCreativeComponentList.refresh() }} loading={getCreativeComponentList.loading}></Button>
                <Popconfirm
                    title="确定删除?"
                    onConfirm={() => { handleDel(selectedRows.map(item => item.componentId), queryParams?.adAccountId as number) }}
                    disabled={selectedRows.length === 0}
                >
                    <Button icon={<DeleteOutlined />} type="primary" danger size="small" disabled={selectedRows.length === 0} loading={delComponent.loading}>删除</Button>
                </Popconfirm>
                {/* 同步组件 */}
                <SyncCloudComponent
                    accountId={queryParams?.adAccountId as number}
                />
                <span style={{ color: 'red' }}>平台只支持选择业务单元的组件创建广告</span>
            </Space>
        </Card>
        <Card
            className="cardResetCss"
            style={{ flex: 1, overflow: 'hidden' }}
            bodyStyle={{
                height: '100%',
                overflow: 'hidden',
                display: 'flex',
                flexDirection: 'column',
                width: '100%',
                padding: 0
            }}
        >

            <div className="manageComponent-content" ref={ref}>
                <TablePro
                    leftChild={<div className="manageComponent-header" ref={ref1}>
                        <Button icon={<PlusOutlined />} type="primary" onClick={() => { setAddVisible(true) }}>新建组件</Button>
                        <Input
                            style={{ width: 100 }}
                            value={queryParams?.componentCustomName}
                            placeholder="组件名称"
                            allowClear
                            onChange={(e) => setQueryParams({ ...queryParams, componentCustomName: e.target.value, pageNum: 1 })}
                        />
                        <Input.TextArea
                            style={{ width: 160 }}
                            value={idSting}
                            rows={1}
                            placeholder="素材ID（多个，,空格换行）"
                            allowClear
                            onChange={(e) => setIdSting(e.target.value)}
                        />
                        <Input.TextArea
                            style={{ width: 160 }}
                            value={componentIdSting}
                            rows={1}
                            placeholder="组件ID（多个，,空格换行）"
                            allowClear
                            onChange={(e) => setComponentIdSting(e.target.value)}
                        />
                        <Select
                            showSearch
                            placeholder="二级组件类型"
                            filterOption={(input, option) =>
                                ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                            }
                            style={{ minWidth: 120 }}
                            maxTagCount={1}
                            mode="multiple"
                            allowClear
                            value={queryParams?.componentSubType}
                            onChange={(e) => {
                                setQueryParams({ ...queryParams, componentSubType: e, pageNum: 1 })
                            }}
                            options={(queryParams?.activeKey === 'IMAGE' ? DEFAULT_COMPONENT_SUB_IMAGE_TYPE : DEFAULT_COMPONENT_SUB_VIDEO_TYPE) as DefaultOptionType[]}
                        />
                        <Select
                            showSearch
                            placeholder="已删除？"
                            filterOption={(input, option) =>
                                ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                            }
                            style={{ width: 100 }}
                            value={queryParams?.isDeleted}
                            allowClear
                            onChange={(e) => {
                                setQueryParams({ ...queryParams, isDeleted: e, pageNum: 1 })
                            }}
                            options={[
                                { label: '已删除', value: true },
                                { label: '未删除', value: false }
                            ]}
                        />
                        <Select
                            showSearch
                            placeholder="组件潜力"
                            filterOption={(input, option) =>
                                ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                            }
                            style={{ minWidth: 100 }}
                            maxTagCount={1}
                            mode="multiple"
                            value={queryParams?.potentialStatus}
                            onChange={(e) => {
                                setQueryParams({ ...queryParams, potentialStatus: e, pageNum: 1 })
                            }}
                            options={Object.keys(COMMON_POTENTIAL_STATUS_ENUM).map(key => ({ label: COMMON_POTENTIAL_STATUS_ENUM[key as keyof typeof COMMON_POTENTIAL_STATUS_ENUM], value: key }))}
                        />
                        <Select
                            showSearch
                            placeholder="来源"
                            filterOption={(input, option) =>
                                ((option?.label ?? '') as any).toLowerCase().includes(input.toLowerCase())
                            }
                            style={{ minWidth: 75 }}
                            maxTagCount={1}
                            mode="multiple"
                            value={queryParams?.generationType}
                            onChange={(e) => {
                                setQueryParams({ ...queryParams, generationType: e, pageNum: 1 })
                            }}
                            options={Object.keys(COMPONENT_GENERATION_TYPE_ENUM).map(key => ({ label: COMPONENT_GENERATION_TYPE_ENUM[key as keyof typeof COMPONENT_GENERATION_TYPE_ENUM], value: key }))}
                        />
                        <DatePicker.RangePicker
                            placeholder={['创建时间开始', '创建时间结束']}
                            style={{ width: 250 }}
                            value={queryParams?.createTimeMin && queryParams?.createTimeMax ? [moment(queryParams?.createTimeMin), moment(queryParams?.createTimeMax)] as any : undefined}
                            onChange={(_, option) => setQueryParams({ ...queryParams, createTimeMin: option[0], createTimeMax: option[1], pageNum: 1 })}
                        />
                        <DatePicker.RangePicker
                            placeholder={['消耗时间开始', '消耗时间结束']}
                            style={{ width: 250 }}
                            value={queryParams?.costStartTime && queryParams?.costEndTime ? [moment(queryParams?.costStartTime), moment(queryParams?.costEndTime)] as any : undefined}
                            onChange={(_, option) => setQueryParams({ ...queryParams, costStartTime: option[0], costEndTime: option[1], pageNum: 1 })}
                        />
                    </div>}
                    refreshAjax={() => getCreativeComponentList.refresh()}
                    rowKey="componentId"
                    config={columns12(handleDel, share, shareDetails)}
                    fixed={{ left: 1, right: 0 }}
                    scroll={{ x: 1000, y: (size?.height || 0) - ((size1?.height || 33) + (tableHeaderHeight || 45) + 20) }}
                    configName='创意组件'
                    loading={getCreativeComponentList.loading || loading}
                    ajax={getCreativeComponentList}
                    page={getCreativeComponentList?.data?.current || 1}
                    pageSize={getCreativeComponentList?.data?.size || 20}
                    total={getCreativeComponentList?.data?.total || 0}
                    dataSource={getCreativeComponentList.data?.records?.map((item: any) => ({ ...item, adUnitAccount: adAccount?.adUnitAccount })) || []}
                    pagination={false}
                    onChange={(pagination: any, _: any, sortData: any) => {
                        let { current, pageSize } = pagination
                        let newQueryForm = JSON.parse(JSON.stringify(queryParams))
                        if (sortData && sortData?.order) {
                            newQueryForm['sortAsc'] = sortData?.order === 'ascend' ? true : false
                            newQueryForm['sortColumn'] = sortData?.field
                        } else {
                            delete newQueryForm['sortAsc']
                            delete newQueryForm['sortColumn']
                        }
                        newQueryForm.pageNum = current || newQueryForm.pageNum
                        newQueryForm.pageSize = pageSize || newQueryForm.pageSize
                        setQueryParams({ ...newQueryForm })
                    }}
                    rowSelection={{
                        selectedRowKeys: selectedRows.map(item => item.componentId),
                        getCheckboxProps: (record: any) => ({
                            disabled: record?.isDeleted
                        }),
                        onSelect: (record: { componentId: number }, selected: boolean) => {
                            if (selected) {
                                selectedRows.push({ ...record })
                                setSelectedRows([...selectedRows])
                            } else {
                                let newSelectAccData = selectedRows.filter((item: { componentId: number }) => item.componentId !== record.componentId)
                                setSelectedRows([...newSelectAccData])
                            }
                        },
                        onSelectAll: (selected: boolean, selectedRowss: { componentId: number }[], changeRows: { componentId: number }[]) => {
                            if (selected) {
                                let newSelectAccData = [...selectedRows]
                                changeRows.forEach((item: { componentId: number }) => {
                                    let index = newSelectAccData.findIndex((ite: { componentId: number }) => ite.componentId === item.componentId)
                                    if (index === -1) {
                                        let data: any = { ...item }
                                        newSelectAccData.push(data)
                                    }
                                })
                                setSelectedRows([...newSelectAccData])
                            } else {
                                let newSelectAccData = selectedRows.filter((item: { componentId: number }) => {
                                    let index = changeRows.findIndex((ite: { componentId: number }) => ite.componentId === item.componentId)
                                    if (index !== -1) {
                                        return false
                                    } else {
                                        return true
                                    }
                                })
                                setSelectedRows([...newSelectAccData])
                            }
                        }
                    }}
                />
            </div>
            <div className="manageComponent-footer">
                <Pagination
                    size="small"
                    total={getCreativeComponentList?.data?.totalRow || 0}
                    showSizeChanger
                    showQuickJumper
                    pageSize={getCreativeComponentList?.data?.pageSize || 30}
                    current={getCreativeComponentList?.data?.pageNumber || 1}
                    showTotal={(total: number) => <span style={{ fontSize: 12 }}>共{total}条</span>}
                    onChange={(page: number, pageSize: number) => {
                        ref.current?.querySelector('.ant-table-body')?.scrollTo({ top: 0 })
                        setTimeout(() => setQueryParams({ ...queryParams, pageNum: page, pageSize }), 50)
                    }}
                />
            </div>
        </Card>

        {/* 新建 */}
        {addVisible && <AddComponents
            type={queryParams?.activeKey as any}
            putInType={putInType}
            accountId={queryParams?.adAccountId as number}
            visible={addVisible}
            onChange={() => {
                setAddVisible(false);
                getCreativeComponentList.refresh();
            }}
            onClose={() => setAddVisible(false)}
        />}

        {/* 组件共享 */}
        {shareData?.visible && <ShareComponent
            {...shareData}
            adAccountData={adAccount}
            onChange={() => {
                setShareData({ visible: false, data: null })
                getCreativeComponentList.refresh()
            }}
            onClose={() => {
                setShareData({ visible: false, data: null })
            }}
        />}

        {/* 组件共享详情 */}
        {shareDetailsData?.visible && <ShareDetails
            {...shareDetailsData}
            onClose={() => {
                setShareDetailsData({ visible: false, data: null })
            }}
        />}
    </div>
}

export default ManageComponent