import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, InputNumber, message, Tag, Upload } from 'antd'
import Modal from 'antd/lib/modal/Modal'
import React, { useCallback, useReducer, useState } from 'react'
import { request, useModel } from 'umi';
import { api } from '@/services/api'
import './updata.less'
import getMD5 from '../MD5';
type State = {
    visible?: boolean,//批量弹窗
    fileList?: any[],//已上传的文件列表
    previewVisible?: boolean,//查看图片弹窗
    previewImage?: string,//查看图片地址
    previewTitle?: string//查看图片标题
}
type Action = {
    type: 'visible' | 'fileList' | 'delList' | 'previewVisible' | 'init',
    params?: any
}
const initData: State = {
    visible: false,
    fileList: [],
    previewVisible: false,
    previewImage: '',
    previewTitle: ''
}
function reducer(state: State, action: Action) {
    let { type, params } = action
    switch (type) {
        case 'visible':
            return { ...state, visible: params.visible }
        case 'previewVisible':
            return { ...state, ...params }
        case 'delList':
            let delArr = state?.fileList?.filter((file: { uid: string }) => file.uid !== params?.uid)
            return { ...state, fileList: delArr }
        case 'fileList':
            let arr = state?.fileList ? [...state?.fileList, ...params.fileList as any[]] : params.fileList
            return { ...state, fileList: arr }
        case 'init':
            return { ...initData }
        default:
            return { ...state }
    }
}
/**文件限制字典 */
const fileTypes: any = {
    '1': 'image/gif,image/jpeg,image/png,image/jpg',
    '3': 'video/*',
    '2': 'audio/*',
}
// type: 0 | 1,
function Updata(props: { mediaType: '3' | '2' | '1', callBcak: (str: boolean) => void, type: 0 | 1, isAll: boolean }) {
    const [state, dispatch] = useReducer(reducer, initData)
    const { mediaType, callBcak, type, isAll } = props
    const { deloss } = useModel('useOperating.useMaterialContent')
    const { visible, fileList, previewVisible, previewImage, previewTitle } = state
    const { state: bdState, add, list } = useModel(isAll ? 'useOperating.useBdMedia' : 'useOperating.useBdMediaPup')
    const { parentId, belongUser, fileType } = bdState
    const [sort, setSort] = useState<number>(0)
    //创建
    const submit = useCallback(() => {
        let arr: any[] = []
        fileList.forEach((file: { type: number, mediaType: number, url: string, name: string, sort: number, fileMd5: string, fileSize: number }) => {
            let { url, name, sort, fileMd5, fileSize } = file
            let obj = { title: name, fileType, folder: false, parentId, belongUser, url, sort, fileMd5, fileSize }
            arr.push(obj)
        })
        if (arr.length > 0) {
            arr.forEach((item) => {
                add.run(item).then((res) => {
                    list.refresh()
                })
            })
        }
        dispatch({ type: 'init' })
        callBcak(false)
    }, [fileList, list])
    //取消
    const cancel = useCallback(() => {
        if (fileList.length > 0) {
            message.warning('你有已上传的文件没有删除或保存，如果放弃请先删除图片，释放服务器空间')
            return
        }
        dispatch({ type: 'init' })
        callBcak(false)
    }, [fileList])
    //批量删除
    const allDel = useCallback(() => {
        fileList.forEach((file: { key: string, uid: string }) => {
            let { key, uid } = file
            dispatch({ type: 'delList', params: { uid } })
            deloss.run(key).then((res: any) => {//删除OSS文件
                console.log(res)
            })
        })
    }, [fileList])
    return <>
        {/* <span onClick={() => { dispatch({ type: 'visible', params: { visible: true } }) }}>批量创建素材</span> */}
        {/* <Button onClick={() => { dispatch({ type: 'visible', params: { visible: true } }) }} type='primary'>批量创建素材</Button> */}
        <Modal
            visible={true}
            title={<span>批量新增素材<small style={{ color: '#999' }}>（请先手动将文件名重命名为要创建的素材标题）</small></span>}
            onOk={submit}
            onCancel={cancel}
            width={800}
        >
            <Button type='primary' size='small' style={{ float: 'right', marginBottom: 5 }} onClick={allDel}>全部删除</Button>
            <Divider />
            <Tag color='warning'>数值越大越靠前</Tag>
            <div>
                <InputNumber
                    style={{ width: 300, marginTop: 10, marginBottom: 10 }}
                    value={sort}
                    placeholder='请输入序号, 数值越大越靠前'
                    onChange={(e: number) => {
                        setSort(e)
                    }}
                />
            </div>
            <Upload
                accept={fileTypes[mediaType]}
                action="" //上传的地址1
                listType="picture-card" //上传列表的内建样式，支持三种基本样式 text, picture 和 picture-card
                fileList={fileList} //已经上传的文件列表
                onPreview={(file) => {
                    dispatch({
                        type: 'previewVisible',
                        params: {
                            previewVisible: true,
                            previewImage: file.url,
                            previewTitle: file.name
                        }
                    })
                }} //点击文件链接或预览图标时的回调
                onChange={() => { }} //上传文件改变时的状态
                multiple={true} //是否支持多选文件，ie10+ 支持。开启后按住 ctrl 可选择多个文件
                customRequest={(options: any) => {
                    let formData = new FormData();
                    if (mediaType === '2') {
                        if (options.file.size > 2097152) {
                            message.error('请上传小于2M的音频')
                            return
                        }
                    }
                    if (mediaType === '1' || mediaType === '3') {
                        if (options.file.size > 10485760) {
                            message.error('请上传小于10M的素材')
                            return
                        }
                    }
                    request(`${api}/system/oss/ossUpload?type=${options.file.type}`).then((res) => { //请求后端获取ossKey
                        if (res.data) {
                            Object.keys(res.data).forEach((key: string) => {
                                if (key !== 'url') {
                                    formData.append(key, res.data[key])
                                }
                            })
                            formData.append('file', options.file)
                            //请求OSS上传
                            request(res?.data?.ossUrl, { method: 'post', body: formData }).then(async (res2: { code: number, data: { url: string } }) => {
                                console.log(res2)
                                if (res2.code === 200) {
                                    let fileMd5 = await getMD5(options.file)
                                    dispatch({
                                        type: 'fileList', params: {
                                            fileList: [
                                                {
                                                    url: res2.data.url,
                                                    name: options.file.name,
                                                    uid: options.file.uid,
                                                    // type,
                                                    mediaType,
                                                    key: res.data.key,
                                                    sort,
                                                    fileMd5,
                                                    fileSize: options.file.size
                                                }
                                            ]
                                        }
                                    })
                                } else {
                                    message.error(`${options.file.name}上传失败！`)
                                }
                            })
                        }
                    })
                }}
                // transformFile={} //在上传之前转换文件。支持返回一个 Promise 对象  
                onRemove={(file: any) => {
                    let uid = file.uid
                    dispatch({ type: 'delList', params: { uid } })
                    deloss.run(file.key).then((res: any) => {//删除OSS文件
                        console.log(res)
                    })
                }} //点击移除文件时的回调，返回值为 false 时不移除。支持返回一个 Promise 对象，Promise 对象 resolve(false) 或 reject 时不移除   
            >
                <div>
                    <PlusOutlined />
                    <div style={{ marginTop: 8 }}>Upload</div>
                </div>
            </Upload>
            <Modal
                visible={previewVisible}
                title={previewTitle}
                footer={null}
                onCancel={() => {
                    dispatch({
                        type: 'previewVisible', params: {
                            previewVisible: false,
                            previewImage: '',
                            previewTitle: ''
                        }
                    })
                }}
            >
                {
                    mediaType === '1' ? <img alt="example" style={{ width: '100%' }} src={previewImage} /> :
                        mediaType === '3' ? <video src={previewImage} controls width='100%' /> : <audio src={previewImage} controls />
                }

            </Modal>
        </Modal>
    </>
}

export default Updata