import { Modal, Tabs, Image, Row, Col, Card, Tag, Pagination, Button, message } from 'antd'
import React, { useCallback, useEffect, useRef, useState } from 'react'
import { request, useModel } from 'umi';
import style from './index.less'
// import UploadModal from '@/pages/operatePage/material/cloud/components/Modal'
const { TabPane } = Tabs;
/**编辑器左侧选择图片弹窗 */
type Props = {
    visible: boolean,
    onCancel: () => void,
    onOk: (param: { type: 'pushData', params: { menuId: string, thumbUrl: string } }) => void,
    title: string,
    data: any,
    menuId: string,
    isWx?: boolean
}
/**编辑器右侧选择图片弹窗*/
let MaterialModal = React.memo((props: Props) => {
    const [action, setAction] = 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 { actionWX } = useModel('useOperating.useWxGroupList', model => ({ actionWX: model.state.actionWX }))
    const { getWeData, classGet, tagData, addData, getData, fileUrl } = useModel('useOperating.useMaterialContent', model => ({
        getWeData: model.getWeData,
        tagData: model.tagData,
        classGet: model.classGet,
        addData: model.addData,
        getData: model.getData,
        fileUrl: model.fileUrl
    }))
    let { state } = useModel('useOperating.useMaterialModal')

    //选中图片
    let handleClick = useCallback((url) => {
        setAction(url)
    }, [])
    //个人共用切换
    useEffect(() => {
        setPage(1)
        if (key === '1') {
            props.data.run({
                mediaType: 1,
                pageNum: 1,
                pageSize: 8,
                type: 0
            })
        }
        if (key === '3') {
            props.data.run({
                mediaType: 1,
                pageNum: 1,
                pageSize: 8,
                isAdmin: true,
                type: 1
            })
        }
    }, [key])
    //翻页
    let pageSizeChange = useCallback((page: number, pageSize?: number) => {
        setPage(page)
        if (key === '1') {
            props.data.run({
                mediaType: 1,
                pageNum: page,
                pageSize: 10,
                type: 0
            })
        } else {
            props.data.run({
                mediaType: 1,
                pageNum: page,
                pageSize: 10,
                isAdmin: true,
                type: 1
            })
        }
    }, [props, key])
    //确定插入
    let handleOk = useCallback(() => {
        props.onOk({ type: 'pushData', params: { menuId: props.menuId, thumbUrl: action } })
        props.onCancel()
    }, [action])
    useEffect(() => {
        if (actionWX?.appid) {
            getWeData.run({
                appId: actionWX?.appid,
                count: 10,
                offset: 0,
                type: 1
            })
        }
    }, [actionWX])
    //新增编辑非图文素材弹窗确定发送
    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: 1, groupId: res.groupId }).then(() => {
                                            refM?.current.onCancel()
                                            getData.refresh()
                                        })
                                    }
                                }
                            } else {
                                message.error('上传失败！')
                            }
                        })
                    })
                }
            }
        })
    }, [getData.data, state])
    return <>
        <Modal
            width={750}
            title={props.title}
            visible={props.visible}
            okText='插入'
            cancelText='取消'
            onCancel={() => props.onCancel()}
            onOk={handleOk}
            destroyOnClose
        >
            <Tabs type="card" onChange={(key: string) => { setKey(key) }}
                tabBarExtraContent={key === '1' ? <Button type='primary' onClick={() => {
                    refM?.current?.onOpen('新建')
                }}>新建图片</Button> : ''}
            >
                <TabPane tab="个人本地素材" key="1" style={{ padding: 10 }}>
                    <Row justify='start' gutter={[15, 15]}>
                        {
                            props?.data?.data?.records?.map((item: any) => {
                                return <Col key={item.id} className={`${style.img} ${action === item.url ? style.action : undefined}`}>
                                    <Card bodyStyle={{ padding: 0, height: 150 }} bordered={false} hoverable>
                                        <Image src={item.url} width={150} height={150} placeholder preview={false} onClick={() => handleClick(item.url)} />
                                    </Card>
                                </Col>
                            })
                        }
                    </Row>
                    <Pagination onChange={pageSizeChange} size={'small'} current={page} total={props.data?.data?.total} style={{ float: 'right' }} showTotal={(total: any) => <Tag color="cyan">总共{total}数据</Tag>} />
                </TabPane>
                <TabPane tab="共用本地素材" key="3" style={{ padding: 10 }}>
                    <Row justify='start' gutter={[15, 15]}>
                        {
                            props?.data?.data?.records?.map((item: any) => {
                                return <Col key={item.id} className={`${style.img} ${action === item.url ? style.action : undefined}`}>
                                    <Card bodyStyle={{ padding: 0, height: 150 }} bordered={false} hoverable>
                                        <Image src={item.url} width={150} height={150} placeholder preview={false} onClick={() => handleClick(item.url)} />
                                    </Card>
                                </Col>
                            })
                        }
                    </Row>
                    <Pagination onChange={pageSizeChange} size={'small'} current={page} total={props.data?.data?.total} style={{ float: 'right' }} showTotal={(total: any) => <Tag color="cyan">总共{total}数据</Tag>} />
                </TabPane>
            </Tabs>
            {/* <UploadModal labelName='图片' ref={refM} submit={modalOk} title='图片' classs={classGet?.data} tags={tagData?.data} /> */}
        </Modal>
    </>
})

export default MaterialModal