import { useModel } from 'umi'
import { Modal, Button, Form, Select, message, Space, Image as AntImg, Upload, } from 'antd'
import { SelectValue } from 'antd/es/select'
import Cropprt from '@/components/Cropper'
import React, { useCallback, useEffect, useState } from "react"
const { Option } = Select
import style from './index.less'
import { request } from 'umi'
import { api } from '@/services/api'
import { DeleteOutlined, InboxOutlined } from '@ant-design/icons'
import { RcFile } from 'antd/lib/upload'
import getMD5 from '@/components/MD5'
import { dataURLtoFile, imgMessage, videoMessage } from '@/utils/compress'

const { Dragger } = Upload

type Props = {
    visible: boolean,
    num?: number, // 上传数量
    imgSize?: { width: number, height: number, size: number }
    // handleOk: () => void
    hideModal: (id?: number) => void,
    editData?: any,
    ajax: any,
    dataType: string,
    uploadType?: 'img' | 'video'
}
const channelCon = ['朋友圈信息流', '公众平台流量', '广点通', '小程序', '头条', '抖音']
function AddCon(props: Props) {
    let { visible, hideModal, editData, ajax, dataType: typeData, uploadType, imgSize, num } = props
    const [imgs, setImgs] = useState<string[]>([])
    const [video, setVideo] = useState<RcFile>()
    const [imgLength, setImgLength] = useState<{ width: number, height: number }>({ width: imgSize?.width || 800, height: imgSize?.height || 800 })
    const [queryForm, setQueryForm] = useState<any>({ content: '', labelIds: [], type: 1, channel: '朋友圈信息流', id: undefined, dataType: 'personal' })
    const [loading, setLoading] = useState<boolean>(false)
    const [fileList, setFileList] = useState<any[]>([])
    const { addMedias, getLabels, editMedias } = useModel('useLaunch.useMaterial')
    const [graph, setGraph] = useState<any>(1)
    useEffect(() => {
        if (editData && typeof editData === 'object' && Object.keys(editData).length > 0) {
            let { content, labelIds, type, channel, id, dataType } = editData
            setImgs(content?.split(','))
            setQueryForm({ content, labelIds: labelIds || [], type, id, channel, dataType })
        }
    }, [editData])
    useEffect(() => {
        getLabels.run({ pageNum: 1, pageSize: 200 })
    }, [])
    /** 选择了图片触发 */
    const setImgsHandle = useCallback(async (img: any) => {
        if (img) {
            if (imgs.length > 0) {
                let file = await dataURLtoFile(img, Math.round(new Date() as any / 1000))
                let md5 = await getMD5(file)
                for (let item of imgs) {
                    let file = await dataURLtoFile(item, Math.round(new Date() as any / 1000))
                    let md5s = await getMD5(file)
                    if (md5 === md5s) {
                        message.error('重复选择，请选择不同图片!')
                        return
                    }
                }
                if (graph === 2) {
                    let onesCk = await imgMessage([imgs[0]])
                    let imgCK = await imgMessage([img])
                    if ((onesCk[0]?.width !== imgCK[0]?.width) || (onesCk[0]?.height !== imgCK[0]?.height)) {
                        message.error({
                            content: '上传组图时,需要图片尺寸相同',
                            duration: 5
                        })
                        return
                    }
                }
            }
            imgs.push(img)
            if (imgs.length > 20) {
                message.error('每次最多上传20张')
                return
            }
            setImgs([...imgs])
            imgMessage([...imgs]).then((res: any) => {
                if (res && res?.length > 0) {
                    setImgLength({ width: res[0]?.width || 800, height: res[0]?.height })
                }
            })
        }

    }, [imgs, imgLength, graph])
    /** 设置上传类型 */
    useEffect(() => {
        if (uploadType) {
            if (uploadType === 'img') {
                setQueryForm({ ...queryForm, type: 1 })
            } else {
                setQueryForm({ ...queryForm, type: 2 })
            }
        }
    }, [uploadType])
    /** 上传创意 确定  */
    const handleOk = useCallback(async () => {
        let { labelIds, content, type, dataType, channel, id } = queryForm

        if (labelIds.length === 0) { message.error('请选择标签'); return }
        if (!type) { message.error('请选择类型'); return }
        if (!channel) { message.error('请选择投放渠道'); return }
        if (!dataType) { message.error('请选择数据类型'); return }
        if (editData && typeof editData === 'object' && Object.keys(editData).length > 0) {// 修改
            editMedias.run({ content, type, dataType, labelIds: labelIds, id, channel }).then(res => {
                setLoading(false)
                setQueryForm({ title: '', labelIds: [], type: 1 })
                hideModal()
                ajax?.refresh()
            })
        } else {  // 新增
            if (type === 1) { // 图片
                if (imgs.length === 0) { message.error('请选择图片'); return }
                let singleImg = true
                if (imgs.length > 1) {
                    singleImg = false
                }
                let md5s: any = []
                let newImgs: File[] = []
                for (let item of imgs) {
                    let file = await dataURLtoFile(item, Math.round(new Date() as any / 1000))
                    let md5 = await getMD5(file)
                    newImgs.push(file)
                    md5s.push(md5)
                }
                setLoading(true)
                let ajaxs = newImgs.map((item) => {
                    return request(`${api}/ads/oss/ossUpload?type=image/jpeg&fileType=image`).then(res => {
                        let formData = new FormData();
                        Object.keys(res.data).forEach((key: string) => {
                            if (key !== 'url') {
                                formData.append(key, res.data[key])
                            }
                        })
                        formData.append('file', item)
                        return request(res?.data?.ossUrl, { method: 'post', body: formData })
                    })
                })
                let imgInfo = await imgMessage(imgs)
                Promise.all(ajaxs).then(res => {
                    if (graph === 1) {//单图
                        let up = res?.map((item: any, index: number) => {
                            return addMedias.run({
                                content: item?.data?.url,
                                type,
                                dataType,
                                labelIds: labelIds,
                                singleImg: true,
                                channel,
                                width: imgInfo[0]?.width,
                                height: imgInfo[0]?.height,
                                mediaSize: newImgs[index]?.size?.toString(),
                                mediaFormat: 'JPEG',
                                signatures: md5s[index]?.split()
                            })
                        })
                        Promise.all(up).then((res: any) => {
                            setLoading(false)
                            message.success('上传成功')
                            setQueryForm({ title: '', labelIds: [], type: 1 })
                            hideModal(res)
                            ajax?.refresh()
                        })
                    } else {//组图
                        let contents = res?.map((item: any) => {
                            return item?.data?.url
                        })
                        if (contents && contents?.length > 0 && contents?.every(item => item)) {
                            addMedias.run({
                                content: contents.toString(),
                                type,
                                dataType,
                                labelIds: labelIds,
                                singleImg,
                                channel,
                                width: imgInfo[0]?.width,
                                height: imgInfo[0]?.height,
                                mediaSize: newImgs?.map(item => item?.size)?.toString(),
                                mediaFormat: newImgs?.map(item => 'JPEG')?.toString(),
                                signatures: md5s
                            }).then(res => {
                                setLoading(false)
                                message.success('上传成功')
                                setQueryForm({ title: '', labelIds: [], type: 1 })
                                hideModal(res)
                                ajax?.refresh()
                            })
                        }
                    }
                })
            } else { // 视频
                if (!video) { message.error('请选择视频'); return }
                let singleImg = true
                let md5: string = await getMD5(video)
                let videoInfo: any = null
                if (video.name.includes('mp4')) {
                    videoInfo = await videoMessage([video])
                }
                if (video.name.includes('ts')) {
                    videoInfo = [
                        {
                            width: 900,
                            height: 500,
                            videoLength: 30
                        }
                    ]
                }

                console.log('上传视频', video, md5, videoInfo, video?.type)
                setLoading(true)
                request(`${api}/ads/oss/ossUpload?type=${video?.type.includes('ts') ?'video/ts' :video?.type ? 'video/mp4' : 'video/ts'}&fileType=video`).then(res => {
                    let formData = new FormData();
                    Object.keys(res.data).forEach((key: string) => {
                        if (key !== 'url') {
                            formData.append(key, res.data[key])
                        }
                    })
                    formData.append('file', video)
                    request(res?.data?.ossUrl, { method: 'post', body: formData }).then(res => {
                        setLoading(false)
                        message.success('上传成功, 视频长宽等数据正在更新中...')
                        addMedias.run({
                            content: res.data.url,
                            type,
                            dataType,
                            labelIds: labelIds,
                            singleImg,
                            channel,
                            width: videoInfo[0]?.width,
                            height: videoInfo[0]?.height,
                            mediaSize: video?.size?.toString(),
                            mediaFormat: video?.type?.toString() || 'video/mp4',
                            signatures: [md5],
                            videoLength: videoInfo[0]?.videoLength?.toFixed(0),
                            aspectRatio: Math.ceil(videoInfo[0]?.width / videoInfo[0]?.height * 10) / 10
                        }).then(res => {
                            setQueryForm({ title: '', labelIds: [], type: 1 })
                            hideModal(res)
                            ajax?.refresh()
                        })
                    })
                }).catch(() => setLoading(false))
            }
        }

    }, [queryForm, imgs, loading, graph, video])



    const del = useCallback((src: string) => {
        let newImgs = imgs.filter((item: string) => item !== src)
        setImgs(newImgs)
    }, [imgs])

    return <Modal visible={visible} width={460} title={
        <Space>
            <span>上传图片/视频</span>
            <Select value={queryForm.type} disabled={queryForm?.id || uploadType} size='small' onChange={(value: SelectValue) => { setQueryForm({ ...queryForm, type: value }) }} placeholder="选择类型">
                <Option value={1}>图片</Option>
                <Option value={2}>视频</Option>
            </Select>
            {
                queryForm.type === 1 && <Select value={graph} size='small' onChange={(value: SelectValue) => { setGraph(value) }} placeholder="单图/组图">
                    <Option value={1}>单图</Option>
                    <Option value={2}>组图</Option>
                </Select>
            }
        </Space>
    }
        onOk={handleOk}
        onCancel={() => { hideModal() }}
        footer={
            <>
                <Space>
                    <Button onClick={() => { hideModal() }}>取消</Button>
                    <Button type="primary" onClick={handleOk} loading={addMedias?.loading || editMedias?.loading || loading}>{editData && typeof editData === 'object' && Object.keys(editData).length > 0 ? '修改' : '新增'}</Button>
                </Space>
            </>
        }
    >
        <Form labelCol={{ span: 4 }}>
            {
                queryForm?.type === 1 ? <Form.Item >
                    {
                        !queryForm?.id && <Cropprt disabled={!!(num && num === imgs.length)} imgSize={imgSize} isChangeCropperSize={imgs.length > 0} isLaunch={imgSize && Object.keys(imgSize).length > 0} {...imgLength} callback={(img) => { setImgsHandle(img) }} />
                    }
                    {
                        imgs.length > 0 && <div className={style.imgs}>
                            <Space wrap>
                                {imgs?.map((item: string, index: number) => (
                                    <div className={style.imgCon} key={index}>
                                        <AntImg width={60} src={item} preview={false} />
                                        {!queryForm?.id && <div className={style.handle}>
                                            <Space><div className={style.bt} onClick={() => { del(item) }}><DeleteOutlined style={{ color: 'red' }} /></div></Space>
                                        </div>}
                                    </div>
                                ))}
                            </Space>
                        </div>
                    }

                </Form.Item> :
                    <Form.Item>
                        {
                            !queryForm?.id ? <Dragger
                                accept="video/*,.ts"
                                action=""
                                maxCount={1}
                                multiple={false}
                                customRequest={() => { }}
                                fileList={fileList}
                                onRemove={() => { setVideo(undefined); setFileList([]) }}
                                beforeUpload={(file: RcFile, FileList: RcFile[]): any => {
                                    console.log('file', file)
                                    const isLt2M = file.size / 1024 / 1024 < 500;
                                    if (!isLt2M) {
                                        message.error('请上传视频小于 500MB!');
                                        return
                                    }
                                    setFileList(FileList)
                                    setVideo(file)
                                }}
                            >
                                <p className="ant-upload-drag-icon">
                                    <InboxOutlined />
                                </p>
                                <p className="ant-upload-text">单击或拖动文件到此区域以上载</p>
                                <p className="ant-upload-hint">
                                    支持MP4....
                                </p>
                            </Dragger> :
                                <video style={{ width: '100%' }} height={160} src={queryForm?.content} loop={true} autoPlay={false} controls></video>
                        }


                    </Form.Item>
            }
            <Form.Item label="标签">
                <Select value={queryForm.labelIds} onChange={(value: SelectValue) => { setQueryForm({ ...queryForm, labelIds: value }) }} placeholder="选择标签" mode="multiple">
                    {getLabels?.data?.records.map((item: any) => (<Option value={item?.id} key={item?.label + item?.id}>{item?.label}</Option>))}
                </Select>
            </Form.Item>
            <Form.Item label="渠道">
                <Select value={queryForm.channel} disabled={queryForm?.id} onChange={(value: SelectValue) => { setQueryForm({ ...queryForm, channel: value }) }} placeholder="选择投放渠道">
                    {channelCon?.map((item: string, index: number) => <Option value={item} key={index}>{item}</Option>)}
                </Select>
            </Form.Item>
            <Form.Item label="数据类型">
                <Select value={queryForm.dataType} disabled={queryForm?.id && typeData === 'all'} onChange={(value: SelectValue) => { setQueryForm({ ...queryForm, dataType: value }) }} placeholder="选择数据类型">
                    <Option value='personal' disabled={queryForm?.id && typeData === 'group'}>个人</Option>
                    <Option value='group'>组内共享</Option>
                    <Option value='all'>公司全员共享</Option>
                </Select>
            </Form.Item>
        </Form>
    </Modal>
}

export default React.memo(AddCon)