import { Button, Card, Col, Empty, Image, Input, message, Modal, Pagination, Row, Select, Space, Tabs, Tag } from "antd"
import React, { useMemo, useRef } from "react"
import { useCallback, useEffect, useState } from "react"
import { request, useModel } from "umi"
import UploadModal from '@/pages/operatePage/material/cloud/components/Modal'
const { TabPane } = Tabs;
import style from './index.less'
/**编辑器内容选择图片弹窗*/
let config1 = {
    1: '图片',
    2: '音频',
    3: '视频',
    4: '文字',
    5: '图文'
}
type Props = {
    mediaType: number,
    visible: boolean,
    onOk: (url: string, type?: number) => void,
    onCancel: () => void,
    title: string,
    actionKey?: string,
    isShowWx?: boolean,
    isAllData?: boolean
}
const ModalPage = (props: Props) => {
    const [action, setAction] = useState<string>('')
    const [actionData, setActionData] = useState<any>(null)
    const { mediaType, visible, onOk, onCancel, title, actionKey, isShowWx = true, isAllData = false } = props
    const [qqLink, setQqLink] = useState<string>('')
    const [key, setKey] = useState<string>('1')//菜单值
    const [page, setPage] = useState<number>(1)//页码
    let refM: { current: { onOpen: () => void, onCancel: () => void } } | any = useRef()//获取Modal实例方法
    const { access } = useModel('@@initialState', model => ({ access: model.initialState?.currentUser?.access }))
    const { getData, getWeData, addData, tagData, classGet, fileUrl } = useModel('useOperating.useMaterialContent', model => ({
        getData: model.getData,
        getWeData: model.getWeData,
        addData: model.addData,
        tagData: model.tagData,
        classGet: model.classGet,
        fileUrl: model.fileUrl,
    }))
    let { state } = useModel('useOperating.useMaterialModal')
    const { actionWX } = useModel('useOperating.useWxGroupList', model => ({ actionWX: model.state.actionWX }))
    const [className, setClassName] = useState<number>()
    const [tagName, setTagName] = useState<number[]>([])
    //搜索
    let handleSelect = useCallback((name: number | number[], isTag: boolean) => {
        if (isTag) {
            setTagName(name as number[])
            getData.run({ type: key === '3' ? 1 : 0, mediaType, groupId: className || '', tagIds: name, pageNum: 1, pageSize: 10 })
            setPage(1)
        } else {
            setClassName(name as number)
            getData.run({ type: key === '3' ? 1 : 0, mediaType, groupId: name || '', tagIds: tagName || '', pageNum: 1, pageSize: 10 })
            setPage(1)
        }
    }, [tagName, className, key, mediaType,])
    //
    let tagArr = useMemo(() => {
        if (tagData?.data) {
            let arr = tagData?.data?.map((item: { id: string, tagName: string }) => ({ value: item.id, text: item.tagName }))
            return arr
        }
        return []
    }, [tagData?.data])
    let classArr = useMemo(() => {
        if (classGet?.data) {
            let arrClass = classGet?.data?.map((item: { id: string, groupName: string }) => ({ value: item.id, text: item.groupName }))
            return arrClass
        }
        return []
    }, [classGet?.data])
    //
    useEffect(() => {
        getData.run({
            mediaType: mediaType,
            pageNum: 1,
            pageSize: 10,
            type: 0
        })
    }, [mediaType, actionWX])
    //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 handleClick = useCallback((url, data?: any) => {
        console.log(url)
        setAction(url)
        setActionData(data)
    }, [])
    //个人共用切换
    useEffect(() => {
        setPage(1)
        if (key === '1') {
            getData.run({
                mediaType: mediaType,
                pageNum: page,
                pageSize: 10,
                type: 0
            })
            tagData.run({ type: 0 })
            classGet.run({ type: 0 })
        }
        if (key === '3') {
            getData.run({
                mediaType: mediaType,
                pageNum: page,
                pageSize: 10,
                type: 1
            })
            tagData.run({ type: 1 })
            classGet.run({ type: 1 })
        }
        if (key === '4') {
            getWeData.run({
                appId: actionWX?.appid,
                size: 10,
                page: 0,
                type: mediaType
            })
        }
    }, [key, mediaType, actionWX])
    //翻页
    let pageSizeChange = useCallback((page: number, pageSize?: number) => {
        setPage(page)
        if (key === '1') {
            getData.run({
                mediaType: mediaType,
                pageNum: page,
                pageSize: 10,
                type: 0,
                tagIds: tagName || '',
                groupId: className || '',
            })
        } else {
            getData.run({
                mediaType: mediaType,
                pageNum: page,
                pageSize: 10,
                type: 1,
                tagIds: tagName || '',
                groupId: className || '',
            })
        }
    }, [mediaType, key, tagName, className])
    let wxpageSizeChange = useCallback((page: number, pageSize?: number) => {
        setPage(page)
        if (actionWX?.appid) {
            getWeData.run({
                appId: actionWX?.appid,
                size: pageSize,
                page: page,
                type: mediaType
            })
        }
    }, [mediaType, actionWX])
    //Ok
    let ok = () => {
        if (!actionKey) {
            if (isAllData) {
                if (actionData) {
                    onOk(actionData, mediaType)
                }

            } else {
                if (action) {
                    onOk(action, mediaType)
                }
            }
        }
        if (actionKey === '1') {
            if (qqLink) {
                onOk(qqLink)
            } else {
                message.error('地址不正确')
            }
        }
    }
    //新增编辑非图文素材弹窗确定发送
    let modalOk = useCallback((fnc: () => Promise<any>, data: any) => {
        fnc().then((res: any) => {
            if (res) {
                if (res?.file) {
                    /**修改文件名以用户设置的文件title命名*/
                    let newFile = new File([state?.file], res.title + '.' + state?.file?.name.split('.')[1], { type: state?.file?.type })
                    let formData = new FormData();
                    /**向阿里云请求上传地址*/
                    fileUrl.run({ type: newFile.type }).then(res1 => {
                        Object.keys(res1).forEach((key: string) => {
                            if (key !== 'url') {
                                formData.append(key, res1[key])
                            }
                        })
                        formData.append('file', newFile)
                        /**向阿里云返回的上传地址上传文件*/
                        request(res1?.url, { method: 'post', body: formData }).then((res2: { code: number, data: { url: string } }) => {
                            if (res2.code === 200) {
                                message.success('上传成功')
                                if (res) {
                                    /**取到返回的文件地址向后端发送具体数据*/
                                    if (res2?.data?.url) {
                                        addData.run({ title: res.title, url: res2?.data?.url, mediaTagIds: res.mediaTagId, mediaType, groupId: res.groupId, type: key === '3' ? 1 : 0 }).then(() => {
                                            refM?.current.onCancel()
                                            getData.refresh()
                                        })
                                    }
                                }
                            } else {
                                message.error('上传失败！')
                            }
                        })
                    })
                }
            }
        })
    }, [getData.data, state, key])
    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={900}
        visible={visible}
        onOk={ok}
        onCancel={onCancel}
    >
        <>
            {
                !actionKey && <>
                    <Tabs
                        type="card"
                        onChange={(key: string) => { setKey(key) }}
                        tabBarExtraContent={
                            <Space>
                                {
                                    key !== '4' && <Select
                                        style={{ width: 120 }}
                                        allowClear
                                        placeholder='标签搜索'
                                        onChange={(value: any) => handleSelect(value, true)}
                                        mode='multiple'
                                        filterOption={(input, option) =>
                                            option?.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    >
                                        {
                                            tagArr?.map((item: { value: string, text: string }) => {
                                                return <Select.Option value={item.value} key={item.value}>{item.text}</Select.Option>
                                            })
                                        }
                                    </Select>
                                }
                                {
                                    key !== '4' && <Select
                                        showSearch
                                        style={{ width: 120 }}
                                        allowClear
                                        placeholder='类型搜索'
                                        onChange={(value: any) => handleSelect(value, false)}
                                        filterOption={(input, option) =>
                                            option?.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                    >
                                        {
                                            classArr?.map((item: { value: string, text: string }) => {
                                                return <Select.Option value={item.value} key={item.value}>{item.text}</Select.Option>
                                            })
                                        }
                                    </Select>
                                }
                                {
                                    key === '1' ?
                                        <Button type='primary' onClick={() => refM?.current?.onOpen('新建')}>新建{title}</Button> :
                                        key === '3' && access === 'admin' ? <Button type='primary' onClick={() => refM?.current?.onOpen('新建')}>新建{title}</Button> :
                                            key === '2' ? <Button type='primary' onClick={() => refM?.current?.onOpen('新建')}>新建{title}</Button> : ''
                                }
                            </Space>
                        }
                    >
                        <TabPane tab="个人本地素材" key="1" style={{ padding: 10 }}>
                            {
                                getData?.data?.records?.length > 0 ? <Row justify='start' gutter={[15, 15]}>
                                    {
                                        getData?.data?.records?.map((item: any) => {
                                            return <Col key={item.id} className={`${style.img} ${action === item.url ? style.action : undefined}`}>
                                                <Tags url={item.url} data={item} />
                                            </Col>
                                        })
                                    }
                                </Row> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                            }
                            <Pagination onChange={pageSizeChange} size={'small'} current={page} total={getData?.data?.total} style={{ float: 'right' }} showTotal={(total) => <Tag color="cyan">总共{total}数据</Tag>} />
                        </TabPane>
                        <TabPane tab="公共本地素材" key="3" style={{ padding: 10 }} >
                            {
                                getData?.data?.records?.length > 0 ? <Row justify='start' gutter={[15, 15]}>
                                    {
                                        getData?.data?.records?.map((item: any) => {
                                            return <Col key={item.id} className={`${style.img} ${action === item.url ? style.action : undefined}`}>
                                                <Tags url={item.url} data={item} />
                                            </Col>
                                        })
                                    }
                                </Row> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                            }
                            <Pagination onChange={pageSizeChange} size={'small'} current={page} total={getData?.data?.total} style={{ float: 'right' }} showTotal={(total) => <Tag color="cyan">总共{total}数据</Tag>} />
                        </TabPane>
                        {
                            isShowWx && false && <TabPane tab="微信素材" key="4" style={{ padding: 10 }}>
                                {
                                    getWeData?.data?.records?.length > 0 ? <Row justify='start' gutter={[15, 15]}>
                                        {
                                            getWeData?.data?.records?.map((item: any) => {
                                                item = item?.content
                                                return <Col key={item?.mediaId} className={`${style.img} ${action === item?.url ? style.action : undefined}`}>
                                                    <Tags url={item?.url} data={item} />
                                                </Col>
                                            })
                                        }
                                    </Row> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                                }

                                <Pagination onChange={wxpageSizeChange} size={'small'} current={page} total={getWeData?.data?.total} style={{ float: 'right' }} showTotal={(total) => <Tag color="cyan">总共{total}数据</Tag>} />
                            </TabPane>
                        }
                    </Tabs>
                    <UploadModal labelName={config1[mediaType]} ref={refM} submit={modalOk} title={title} classs={classGet?.data} tags={tagData?.data} />
                </>
            }
            {
                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="500"
                                    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="500"
                                    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 ModalPage