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 } from '@/utils/compress'

const { Dragger } = Upload

type Props = {
    visible: boolean,
    num?: number, // 上传数量
    imgSize?: { width: number, height: 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, dataLable } = useModel('useLaunch.useMaterial')

    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
                    }
                }
                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 > 12) {
                message.error('每次最多上传12张')
                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])
    /** 设置上传类型 */
    useEffect(() => {
        if (uploadType) {
            if (uploadType === 'img') {
                setQueryForm({ ...queryForm, type: 1 })
            } else {
                setQueryForm({ ...queryForm, type: 2 })
            }
        }
    }, [uploadType])
    /** 上传创意 确定  */
    const handleOk = useCallback(async () => {
        let { labelIds, id } = queryForm
        setLoading(true)
        if (labelIds.length === 0) { message.error('请选择标签'); return }
        dataLable.run({ labelIds: labelIds?.toString(), id, name: 'tagMedia' }).then(res => {
            setLoading(false)
            setQueryForm({ title: '', labelIds: [], type: 1 })
            hideModal()
            ajax?.refresh()
        })

    }, [queryForm, imgs, loading])



    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} onChange={(value: SelectValue) => { setQueryForm({ ...queryForm, type: 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 || dataLable?.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/*"
                                action=""
                                maxCount={1}
                                multiple={false}
                                customRequest={()=>{}}
                                fileList={fileList}
                                beforeUpload={(file: RcFile, FileList: RcFile[]): any => {
                                    const isLt2M = file.size / 1024 / 1024 < 500;
                                    if (!isLt2M) {
                                        message.error('请上传视频小于 500MB!');
                                        return isLt2M;
                                    }
                                    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="tags">
                    {getLabels?.data?.records.map((item: any) => (<Option value={item?.id} key={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)