import { Input, message, Radio, Select, Space, Switch, Tooltip } from 'antd';
import { RadioChangeEvent } from 'antd/lib/radio';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from '../style.less';
import { videoS, shengdan, man } from './defaultVideo';
import { exitFullScreen, requestFullScreen, isFull } from '@/utils/fullScreen'
import { useMouse } from 'ahooks';



/**
 * 
 * @param props 
 * @param data.visible 配置弹窗
 * @param open 设置data配置回调
 * @param show 设置登录界面显示隐藏
 */
function Bg(props: { data: { visible: boolean, left?: number, top?: number }, open: (props: { visible: boolean }) => void, show: (show?: boolean) => void, isShow: boolean, }) {
    let { data, open, show ,isShow} = props
    let ulRef: { current: HTMLUListElement | null } = useRef(null)
    let [type, setType] = useState<any>(localStorage?.getItem('type') || '2')
    let [src, setSrc] = useState<string>('')
    let [bfsrc, setBfSrc] = useState<string>('')
    let [name, setName] = useState<string>('')
    let [checked, setChecked] = useState<string>(localStorage.getItem('checked') || '2')//
    let [actionSp, setActionSp] = useState<string>(localStorage.getItem('actionSp') || '')//
    let [off, setOff] = useState<boolean>(true)
    let { clientX, clientY } = useMouse()
    let [sps, setSps] = useState<any>({})
    let [isImg, setIsImg] = useState<any>(localStorage.getItem('isImg') || 'false')
    let videoRef: { current: HTMLVideoElement | null } = useRef(null)
    /**获取自定义视频列表 */
    let mySrcs = useMemo(() => {
        let obj: any = {}
        let str = isImg === 'true' ? localStorage.getItem('img') || '' : localStorage.getItem('video') || ''
        str.split(';').forEach((item: string) => {
            if (item) {
                let arr = item.split('=')
                obj[arr[0]] = arr[1]
            }
        })
        return obj
    }, [localStorage, isImg])
    useEffect(() => {
        if (type === '2') {
            let userId = localStorage.getItem('userId')
            setSps((userId == '1' || userId == '123') ? man : videoS)
        }
    }, [type])
    useEffect(()=>{
        let obj = type === '1' ? mySrcs : sps
        if (JSON.stringify(obj) !== '{}') {
            let sj = ''
            if (JSON.stringify(obj) !== '{}') {
                let eq = Math.floor(Math.random() * (Object.keys(obj).length - 1 + 1) + 1)
                Object.keys(obj).forEach((key: string, index: number) => {
                    if (eq === index + 1) {
                        sj = key
                    }
                })
            }
            let src: string = ''
            if (type === '2') { //假如是默认模式
                if (checked === '0') {//指定
                    src = actionSp ? obj[actionSp] : obj[Object.keys(obj)[0]]
                }
                if (checked === '2') {//随机
                    let eq = Math.floor(Math.random() * (Object.keys(obj).length - 1 + 1) + 1)
                    Object.keys(obj).forEach((key: string, index: number) => {
                        if (eq === index + 1) {
                            sj = key
                            src = obj[key]
                            localStorage.setItem('sjSp', sj)
                        }
                    })
                    // Object.values(obj).forEach((value: unknown, index: number) => {
                    //     if (eq === index + 1) {
                    //         src = value as string
                           
                    //     }
                    // })
                }
            } else {//自定义
                if (checked === '2') {//随机
                    src = obj[sj]
                } else {//指定
                    src = obj[actionSp]
                }
            }
            setBfSrc(src)
        }
    },[sps, mySrcs, type,actionSp,checked])
    // 获取线上视频地址
    const bgArr = useMemo(() => {
        console.log(bfsrc)
        if (bfsrc) {
            return <ul className={styles.bg} ref={ulRef}>
                <li>
                    {
                        isImg === 'false' ? <video
                            width='100%'
                            autoPlay={true}
                            loop={true}
                            muted={off}
                            ref={videoRef}
                            id='video'
                            style={{
                                position: 'absolute',
                                left: '0px',
                                right: '0px',
                                bottom: '0px',
                                top: '0px',
                                width: '100vw',
                                height: '100vh',
                                objectFit: 'fill'
                            }}
                            src={bfsrc}
                        /> : <img src={bfsrc} style={{
                            position: 'absolute',
                            left: '0px',
                            right: '0px',
                            bottom: '0px',
                            top: '0px',
                            width: '100vw',
                            height: '100vh',
                            objectFit: 'fill'
                        }} />
                    }
                    <span style={{ position: 'absolute', zIndex: 1, display: 'block', width: '100vw', height: '100vh', top: 0, left: 0 }} />
                </li>
            </ul>
        }
        return null
    }, [checked, off,bfsrc])
    //切换
    useEffect(() => {
        if (type === '2') {
            setActionSp(localStorage.getItem('actionSp') || '')
        } else {
            if (isImg === 'true') {
                setActionSp(localStorage.getItem('actionImg') || '')
            } else {
                setActionSp(localStorage.getItem('actionMysp') || '')
            }
        }
    }, [type, isImg])
    let handleOk = useCallback(() => {
        localStorage.setItem('type', type)
        open({ visible: false })
    }, [type])
    /**close */
    let handleClose = useCallback(() => {
        open({ visible: false })
    }, [])
    /**add */
    let handleAdd = useCallback(() => {
        if (isImg === 'true') {
            let img = src.match(/(png)|(jpg)|(gif)|(jpeg)/ig)
            if (img) {
                let str = localStorage.getItem('img') || ''
                localStorage.setItem('img', str + name + '=' + src + ';')
                localStorage.setItem('actionImg', name)
                message.success('添加成功！')
                location.reload()
            } else {
                message.error('这不是图片')
            }
            setSrc('')
            setName('')
        } else {
            let video = document.createElement('video');
            video.src = src;
            video.onload = function () {
                console.log('支持')
            }
            video.onerror = function () {
                message.error('不支持该链接');
            }
            video.src = src;
            video.oncanplaythrough = function () {
                let str = localStorage.getItem('video') || ''
                localStorage.setItem('video', str + name + '=' + src + ';')
                localStorage.setItem('actionMysp', name)
                message.success('添加成功！')
                location.reload()
                setSrc('')
                setName('')
            };
        }
    }, [src, name, isImg])
    /**del */
    let handleDel = useCallback(() => {
        if (!name) {
            message.error('删除需要输入视频名称，连接不需要输入！')
            return
        }
        let obj: any = {}
        let str = isImg === 'true' ? localStorage.getItem('img') || '' : localStorage.getItem('video') || ''
        let newStr = ''
        str.split(';').forEach((item: string) => {
            if (item) {
                let arr = item.split('=')
                if (arr[0] !== name) {
                    obj[arr[0]] = arr[1]
                    newStr += item + ';'
                }
            }
        })
        if (isImg === 'true') {
            localStorage.setItem('img', newStr)
        } else {
            localStorage.setItem('video', newStr)
        }
        message.success('删除成功！')
        location.reload()
    }, [name, isImg])
    //全屏判断
    useEffect(() => {
        function esc() {
            if (!isFull()) {
                show(true)
            }
        }
        window.addEventListener('resize', esc)
        return () => {
            window.removeEventListener('resize', esc)
        }
    }, [show])
    //判断鼠标是否禁止
    useEffect(() => {
        let oldX = clientX
        let oldY = clientY
        let time: NodeJS.Timeout | null = null
        if (clientX && clientY) {
            time = setTimeout(() => {
                if (oldX === clientX && oldY === clientY) {
                    console.log('30秒没动了')
                    show(false)
                }
            }, 30000)
        }
        if (!isNaN(clientX) && !isFull()) {
            show(true)
        }
        return () => {
            clearTimeout(time as NodeJS.Timeout)
            time = null
        }
    }, [clientX, clientY])

    // useEffect(()=>{
    //     document.querySelectorAll('#root span')[0].addEventListener('click',ck)
    //     // document.addEventListener('click',ck)
    //     function ck(e: { target: any; }){
    //         let str = e?.target?.innerText 
    //         if(str !== '有声' && str !== '静音'){
    //             setOff(false)
    //         }
    //     }
    //     return ()=>{
    //         document.querySelectorAll('#root span')[0].removeEventListener('click',ck)
    //     }
    // },[])
    // 点开配置开启声音
    useEffect(()=>{
        if(data?.visible){
            setOff(!data?.visible)
        }
    },[data?.visible])
    return <>
        {
            data?.visible && <ul className={styles.config}>
                <li>
                    <Radio.Group onChange={(e: RadioChangeEvent) => {
                        setType(e.target.value)
                        localStorage.setItem('type', e.target.value)
                        if (e.target.value === '2') {
                            localStorage.setItem('isImg', 'false')
                            setIsImg('false')
                        }
                    }} value={type}>
                        <Radio value={'2'}>默认</Radio>
                        <Radio value={'1'}>自定义</Radio>
                        {/* {localStorage.getItem('userId') && (localStorage.getItem('userId') === '1' || localStorage.getItem('userId') === '57' || localStorage.getItem('userId') === '68') && <Radio value={'1'}>自定义</Radio>} */}
                    </Radio.Group>
                </li>
                {
                    type === '1' && <li>
                        <Radio.Group onChange={(e: RadioChangeEvent) => {
                            setIsImg(e.target.value)
                            localStorage.setItem('isImg', e.target.value)
                        }} value={isImg}>
                            <Radio value={'false'}>视频</Radio>
                            <Radio value={'true'}>图片</Radio>
                        </Radio.Group>
                    </li>
                }
                {
                    type === '1' && <li>
                        <Input
                            placeholder='名称'
                            onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
                                let value = event.target.value
                                setName(value)
                            }}
                            value={name}
                            size='small'
                        />
                        <Input
                            placeholder='请输入地址'
                            onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
                                let value = event.target.value
                                setSrc(value)
                            }}
                            value={src}
                            size='small'
                        />
                        <Tooltip title='添加请输入名称和连接'>
                            <a onClick={handleAdd}>+</a>
                        </Tooltip>
                        <Tooltip title='删除请输入视频名称'>
                            <a onClick={handleDel}>-</a>
                        </Tooltip>

                    </li>
                }
                {
                    <li className={styles.config_switch}>
                        <Space>
                            <Select
                                style={{ width: 100 }}
                                onChange={(value: any) => {
                                    setChecked(value)
                                    localStorage.setItem('checked', value)
                                }}
                                value={checked}
                                dropdownClassName={styles.bg_switch_option}
                            >
                                <Select.Option value={'2'}>随机模式</Select.Option>
                                <Select.Option value={'0'}>指定背景</Select.Option>
                            </Select>
                            {checked === '0' && <Select
                                style={{ width: 180 }}
                                onChange={(value: any) => {
                                    setActionSp(value)
                                    localStorage.setItem(type === '2' ? 'actionSp' : isImg === 'true' ? 'actionImg' : 'actionMysp', value)
                                }}
                                value={actionSp}
                                dropdownClassName={styles.bg_switch_option}
                            >
                                {
                                    Object.keys(type === '1' ? mySrcs : sps).map((key: string, index: number) => {
                                        return <Select.Option value={key} key={index}>{key}</Select.Option>
                                    })
                                }
                            </Select>}
                        </Space>

                    </li>
                }
                <li>
                    <Space>
                        <Switch
                            className='switch-kg'
                            checkedChildren='静音'
                            unCheckedChildren='有声'
                            checked={off}
                            onChange={(e: boolean) => {
                                setOff(e)
                                // localStorage.setItem('off', e ? '1' : '0')
                            }} />
                            
                        <div className={styles.config_btn}>
                            按钮颜色：
                            <input type='color' style={{ width: 80, border: 0 }} onChange={(value) => {
                                localStorage.setItem('color', value.target.value)
                            }} value={localStorage.getItem('color') || ''} />
                        </div>
                    </Space>
                </li>
                <li>
                    <Tooltip title='保存'>
                        <a onClick={handleOk}>✓</a>
                    </Tooltip>
                    <Tooltip title='取消'>
                        <a onClick={handleClose}>×</a>
                    </Tooltip>
                </li>
            </ul>
        }
        <span
            className={styles.config_qtww}
            onClick={() => {
                if (isFull()) {
                    show(true)
                    exitFullScreen()
                } else {
                    show(false)
                    requestFullScreen()
                }
            }}
        >
            <img alt='晴天娃娃' src={require(`../../../../../public/qtww.gif`)} />
            {isShow && <small className={styles.config_msg}>点击页面下方趣程可开启背景音乐并自由配置背景哦！点我全屏当壁纸！</small>}
        </span>

        {bgArr}
    </>
}

export default Bg