import React, { useCallback, useEffect, useState } from "react"
import { Card, Col, Empty, Modal, Pagination, Row, Tabs, Tag, Image, Input, message, Button, Space } from "antd"
import { useModel } from 'umi'
import FlieBox from '@/components/FileBox'
const { TabPane } = Tabs
import style from './index.less'
type Props = {
    mediaType: number,
    visible: boolean,
    onOk: (url: string, type?: number) => void,
    onCancel: () => void,
    title: string,
    actionKey?: string,
    isShowWx?: boolean,
    isAllData?: boolean,
    noFile?: boolean//是否禁止选择文件夹
}
let config2 = {
    1: 'image',
    2: 'voice',
    3: 'video',
    5: 'news',
    6: 'knews'
}
const SmModalBox = (props: Props) => {
    const { mediaType, visible, onOk, onCancel, title, actionKey, isShowWx = true, isAllData = false, noFile = false } = props
    const { getWeData, update } = useModel('useOperating.useMaterialContent', model => ({
        getWeData: model.getWeData,
        update: model.update,
    }))
    const { actionWX } = useModel('useOperating.useWxGroupList', model => ({ actionWX: model.state.actionWX }))
    const { state, set, getList, init, typeEnum } = useModel('useOperating.useBdMediaPup')
    const { fileType, belongUser, parentId, selectItem } = state
    const [actionData, setActionData] = useState<any>(null)
    const [action, setAction] = useState<string>('')
    const [page, setPage] = useState<number>(1)//页码
    const [qqLink, setQqLink] = useState<string>('')
    //
    let ok = useCallback(() => {
        if (!actionKey) {
            if (isAllData) {
                if (belongUser == 0 || belongUser == 1) {

                    if (selectItem && Object.keys(selectItem).length > 0) {
                        onOk(selectItem, mediaType)
                    } else {
                        message.error('选择本地图片')
                    }
                } else if (belongUser == 3) {
                    if (actionData) {
                        onOk(actionData, mediaType)
                    } else {
                        message.error('选择微信图片')
                    }
                }
            } else {
                if (action) {
                    onOk(action, mediaType)
                }
            }
        } else if (actionKey === '1') {
            if (qqLink) {
                onOk(qqLink)
            } else {
                message.error('地址不正确')
            }
        }
    }, [actionKey, actionData, selectItem, belongUser])
    useEffect(() => {
        if (belongUser == 0 || belongUser == 1) {
            getList()
        } else if (belongUser == 3) {
            setPage(1)
            getWeData.run({
                mpId: actionWX?.id,
                pageSize: 20,
                pageNum: 1,
                mediaType: config2[mediaType]
            })
        }
    }, [fileType, belongUser, parentId, actionWX?.id])
    useEffect(() => {
        init({ fileType: config2[mediaType] })
    }, [mediaType])
    // 分页
    let wxpageSizeChange = useCallback((page: number, pageSize?: number) => {
        setPage(page)
        if (actionWX?.id) {
            getWeData.run({
                mpId: actionWX?.id,
                pageSize: pageSize,
                pageNum: page,
                mediaType: config2[mediaType]
            })
        }
    }, [mediaType, actionWX])
    //选中图片
    let handleClick = useCallback((url, data?: any) => {
        setAction(url)
        setActionData(data)
    }, [])
    //qq视频
    const qqLinkChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
        let v = e.target.value
        let arr = v.split('/')
        let vid = arr[arr.length - 1].replace('.html', '')
        if (v.search(/http[s]?:\/\/v.qq.com[\S]*.html/ig) !== -1) {
            setQqLink(`https://v.qq.com/iframe/player.html?vid=${vid}&auto=0`)
        }
    }, [])
    // 更新公众号下素材
    let sync = useCallback(() => {
        update.run({ mpId: actionWX?.id, mediaType: config2[mediaType] }).then((res) => {
            if (res) {
                setPage(0)
                if (actionWX?.id) {
                    getWeData.run({
                        mpId: actionWX?.id,
                        pageSize: 20,
                        pageNum: 1,
                        mediaType: config2[mediaType]
                    })
                }
            }
        })
    }, [update, actionWX?.id, mediaType])

    let Tags = (props: { url: string, data?: { title?: string, name?: string } }) => {
        switch (mediaType) {
            case 1:
                return <Card bodyStyle={{ padding: 0, height: 150, display: 'flex', flexFlow: 'column' }} bordered={false} hoverable>
                    <Image src={props.url} width={150} height={150} placeholder preview={false} onClick={() => handleClick(props.url, props?.data)} />
                </Card >
            case 3:
                return <div>
                    <Card bodyStyle={{ padding: 10, height: 165, display: 'flex', flexFlow: 'column', border: '1px solid #efefef' }} bordered={false} hoverable onClick={() => handleClick(props.url, props?.data)}>
                        <video src={props.url} height='130px' controls />
                        <span>名称： {props?.data?.title || props?.data?.name}</span>
                    </Card>
                </div>
            default:
                return <div>
                    <Card bodyStyle={{ padding: 10, height: 80, display: 'flex', flexFlow: 'column', border: '1px solid #efefef' }} bordered={false} hoverable onClick={() => handleClick(props.url, props?.data)}>
                        <audio src={props.url} controls />
                        <span>名称： {props?.data?.title || props?.data?.name}</span>
                    </Card>
                </div>
        }
    }

    return <Modal
        title={title}
        width={1200}
        visible={visible}
        onOk={ok}
        onCancel={onCancel}
        maskClosable={false}
    >
        {
            !actionKey && <>
                <Tabs
                    type="card"
                    onChange={(activeKey: any) => { set({ belongUser: activeKey }) }}
                    activeKey={belongUser}
                    tabBarExtraContent={
                        <Space>
                            {
                                belongUser === '3' ? <Button type='primary' onClick={sync} loading={update?.loading}>更新公众号下素材</Button> : ''
                            }
                        </Space>
                    }
                >
                    <TabPane tab={'个人本地'} key={1} />
                    <TabPane tab={'公共本地'} key={0} />
                    {
                        isShowWx && <TabPane tab={"微信素材"} key={3}>
                            {
                                getWeData?.data?.records?.length > 0 ? <Row justify='start' gutter={[15, 15]}>
                                    {
                                        getWeData?.data?.records?.map((item: any) => {
                                            return <Col key={item?.mediaId} className={`${style.img} ${actionData?.id === item?.id ? style.action : undefined}`}>
                                                <Tags url={item?.url} data={item} />
                                            </Col>
                                        })
                                    }
                                </Row> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                            }

                            <Pagination onChange={wxpageSizeChange} size={'small'} defaultPageSize={20} current={page} total={getWeData?.data?.total} style={{ float: 'right' }} showTotal={(total) => <Tag color="cyan">总共{total}数据</Tag>} />
                        </TabPane>
                    }
                </Tabs>
            </>
        }

        {
            (belongUser == 1 || belongUser == 0) && !actionKey && <FlieBox isAll={false}  noFile={noFile} />
        }

        {
            actionKey === '1' &&
            <Tabs type="card">
                <TabPane tab="腾讯视频" key="2" style={{ padding: 10 }}>
                    <Row>
                        <Col className={style.qq_link}>
                            <label>视频地址：</label>
                            <Input placeholder='请输入腾讯视频地址' onChange={qqLinkChange} allowClear />
                        </Col>
                        <Col className={style.qq_iframe}>
                            <label>预览：</label>
                            <iframe
                                data-vidtype="2"
                                height="310"
                                width="1000"
                                data-ratio="1.7666666666666666"
                                data-w="848"
                                src={qqLink}
                            />
                        </Col>
                    </Row>
                </TabPane>
            </Tabs>

        }
        {
            actionKey === '2' && <Tabs type="card">
                <TabPane tab="音频" key="2" style={{ padding: 10 }}>
                    <Row>
                        <Col className={style.qq_link}>
                            <label>视频地址：</label>
                            <Input placeholder='请输入腾讯视频地址' />
                        </Col>
                        <Col className={style.qq_iframe}>
                            <label>预览：</label>
                            <iframe
                                data-vidtype="2"
                                height="310"
                                width="1000"
                                data-ratio="1.7666666666666666"
                                data-w="848"
                                src="https://v.qq.com/iframe/player.html?vid=e3161ny316e&auto=0"
                            />
                        </Col>
                    </Row>
                </TabPane>
            </Tabs>
        }
    </Modal>
}
export default React.memo(SmModalBox)