import { App, Button, Drawer, Row } from "antd"
import React, { useEffect, useState } from "react"
import style from './index.less'
import Left from "./left"
import Center from "./center"
import Right from "./right"
import { SwapRightOutlined } from '@ant-design/icons';
import Submit from "./submit"

interface Props {
    groupList: { label: string, value: number }[]
    corpList: { corpName: string, corpId: string, corpUserList: { corpUserName: string, corpUserId: string }[] }[]
    visible?: boolean
    onChange?: () => void
    onClose?: () => void
    initialValues?: any
}

export const DispatchMiniPageCreate = React.createContext<TASK_MINI_PAGE_CREATE.DispatchMiniPageCreate | null>(null);

const DrawerMini: React.FC<Props> = ({ visible, onChange, onClose, groupList, corpList, initialValues }) => {


    /**************************************/
    const { message } = App.useApp();
    const [pageSpecs, setPageSpecs] = useState<TASK_MINI_PAGE_CREATE.PageSpecsProps>({
        bgColor: '#FFFFFF',
        pageType: 'LANDING_PAGE',
        pageElementsSpecList: [{ elementType: 'empty' }]
    })
    const [dragging, setDragging] = useState<string | null>(null);
    const [draggingCon, setDraggingCon] = useState<string | null>(null);

    const [sVisible, setSVisible] = useState<boolean>(false)
    /**************************************/
    console.log('pageSpecs-------------------->', pageSpecs)

    useEffect(() => {
        if (initialValues?.pageSpecs) {
            setPageSpecs(initialValues.pageSpecs)
        }
    }, [initialValues])

    const installActive = (e: React.MouseEvent<HTMLDivElement, MouseEvent>, index: number) => {
        e.stopPropagation();
        e.preventDefault();
        const { pageElementsSpecList, globalElementsSpecList } = pageSpecs
        const newPageElementsSpecList = pageElementsSpecList?.map(item => ({ ...item, comptActive: false }))
        let newGlobalElementsSpecList = globalElementsSpecList?.map(item => ({ ...item, comptActive: false })) || []
        if (index === 99999) {
            newGlobalElementsSpecList = newGlobalElementsSpecList.map(item => item.elementType === 'FLOAT_BUTTON' ? { ...item, comptActive: true } : item)
        } else {
            newPageElementsSpecList[index].comptActive = true
        }
        setPageSpecs({ ...pageSpecs, pageElementsSpecList: newPageElementsSpecList, globalElementsSpecList: newGlobalElementsSpecList })
    }

    // 设置顶部素材链接
    const setTopUrl = (url: string) => {
        const { pageElementsSpecList } = pageSpecs
        const newPageElementsSpecList = JSON.parse(JSON.stringify(pageElementsSpecList))
        newPageElementsSpecList[0].url = url
        setPageSpecs({ ...pageSpecs, pageElementsSpecList: newPageElementsSpecList })
    }

    // 设置顶部短视频素材链接
    const setTopShortVideoUrl = (url: string, videoInfo: { width: number, height: number, videoLength: number }, index: number) => {
        const { pageElementsSpecList } = pageSpecs
        const newPageElementsSpecList = JSON.parse(JSON.stringify(pageElementsSpecList))
        if (index === -1) {
            // Handle the case where we want to add a new video item
            const data = newPageElementsSpecList[0].data || [];
            data.push({ url, duration: videoInfo.videoLength || 0 });
            newPageElementsSpecList[0].data = data;
        } else {
            newPageElementsSpecList[0].data[index].url = url
            newPageElementsSpecList[0].data[index].duration = videoInfo?.videoLength || 0
        }

        setPageSpecs({ ...pageSpecs, pageElementsSpecList: newPageElementsSpecList })
    }

    // 设置内容
    const setCompt = (key: string, value: any) => {
        const { pageElementsSpecList } = pageSpecs
        const newPageElementsSpecList = JSON.parse(JSON.stringify(pageElementsSpecList))
        let selectSpec = newPageElementsSpecList?.find((item) => item.comptActive)
        if (selectSpec) {
            selectSpec[key] = value
            setPageSpecs({ ...pageSpecs, pageElementsSpecList: newPageElementsSpecList })
        }
    }

    // 设置全局组件内容
    const setGlobal = (key: string, value: any) => {
        const { globalElementsSpecList } = pageSpecs
        const newGlobalElementsSpecList = JSON.parse(JSON.stringify(globalElementsSpecList))
        let selectSpec = newGlobalElementsSpecList?.find((item) => item.comptActive)
        if (selectSpec) {
            selectSpec[key] = value
            setPageSpecs({ ...pageSpecs, globalElementsSpecList: newGlobalElementsSpecList })
        }
    }

    // 下一步
    const handleNext = () => {
        const { pageElementsSpecList, globalElementsSpecList } = pageSpecs
        if (pageElementsSpecList?.some(item => {
            if (item.elementType === 'empty') {
                message.error('请添加顶部组件')
                return true
            } else if (item.elementType === 'TOP_IMAGE' || item.elementType === 'TOP_VIDEO') {
                if (item.url) {
                    return false
                } else {
                    message.error('顶部组件请上传素材')
                    return true
                }
            } else if (item.elementType === 'TOP_SHORT_VIDEO') {
                if (item?.data?.every(i => i.url)) {
                    if (item?.url && item?.tipText) {
                        return false
                    } else {
                        message.error('请完善转化链接和提示语')
                        return true
                    }
                } else {
                    message.error('顶部短视频组件请上传素材')
                    return true
                }
            } else if (item.elementType === 'IMAGE') {
                if (item.url) {
                    return false
                } else {
                    message.error('图片组件请上传素材')
                    return true
                }
            } else if (item.elementType === 'TEXT') {
                if (item.text) {
                    return false
                } else {
                    message.error('文字组件请填写文案')
                    return true
                }
            } else if (item.elementType === 'QR_CODE') {
                if (item?.imageList?.every(i => i)) {
                    return false
                } else {
                    message.error('添加商家微信组件请上传素材')
                    return true
                }
            }
        })) {
            return
        }
        if (globalElementsSpecList?.some(item => {
            if (item.elementType === 'FLOAT_BUTTON') {
                if (item?.qrCodeFloatList?.every(i => i)) {
                    return false
                } else {
                    message.error('悬浮组件请上传素材')
                    return true
                }
            }
        })) {
            return
        }
        setSVisible(true)
    }

    return <Drawer
        title={<div className={style.drawerTitle}>
            <div>
                <strong>{initialValues?.isCopy ? `复制落地页 ${initialValues.name}` : initialValues?.id ? '修改' + initialValues.name + '落地页' : '新增落地页'}</strong>
            </div>
            <Button type='primary' className={style.next} onClick={() => { handleNext() }}>下一步 <SwapRightOutlined /></Button>
        </div>}
        closable={{ 'aria-label': 'Close Button' }}
        onClose={onClose}
        open={visible}
        width={'80%'}
        className={style.drawer}
        styles={{ body: { padding: '0 2px 0 10px' } }}
    >
        <DispatchMiniPageCreate.Provider
            value={{
                dragging, setDragging,
                draggingCon, setDraggingCon,
                pageSpecs, setPageSpecs,
                installActive,
                setTopUrl,
                setCompt,
                setGlobal,
                setTopShortVideoUrl,
                isNewAdd: !(initialValues?.id || initialValues?.isCopy)
            }}
        >
            <div className={style.boxCont}>
                <Row className={style.row}>
                    <Left />
                    <Center />
                    <Right />
                </Row>
            </div>
        </DispatchMiniPageCreate.Provider>
        {/* 提交设置 */}
        {sVisible && <Submit
            pageSpecs={pageSpecs}
            groupList={groupList}
            corpList={corpList}
            visible={visible}
            initialValues={initialValues}
            onChange={() => {
                onChange?.()
                setSVisible(false)
            }}
            onClose={() => {
                setSVisible(false)
            }}
        />}
    </Drawer>
}

export default React.memo(DrawerMini)