import { useCallback, useEffect, useReducer } from 'react'
import { useAjax } from '@/Hook/useAjax'
import {
    addMediaList, delMediaList, editMediaList, getMediaList, MediaList, GetMediaList, getTagList,
    getClass, delClass, editClass, addClass, createGraphic, CreateGraphic, getGraphicList, editGraphic, EditGraphic, GetGraphicList,
    getWeChatITData, GetWeChatITData, GetWeChatData, getWeChatData, getWxMediaInfo, syncMedias, syncPermanentGraphicMedias, delMediawx,
    createGraphicMaterial, editGraphicWxMaterial, getFileUrl, getGraphicDetail, exportMediaByUrl, updateMediaCache, syncResult, bantchAdd, delOss
} from '@/services/operating/material'
import {  notification } from 'antd'
import { useModel } from 'umi'
type State = {
    mediaType: string,//弹窗开关
    isPublic: 0 | 1,//个人本地和公共本地
    allData: any[],
    syncIds: any[],//同步的素材ID，用于判断是否是当前素材在同步展示login
}
type Action = {
    type: 'setType' | 'isPublic' | 'addData' | 'initData' | 'syncIds',
    params?: any
}
export function reducer(state: State, action: Action) {
    let { allData } = state
    let { type, params } = action
    switch (type) {
        case 'setType':
            return { ...state, mediaType: params.mediaType }
        case 'isPublic':
            return { ...state, isPublic: params.isPublic }
        case 'addData':
            return { ...state, allData: [...allData, ...params.data] }
        case 'syncIds':
            let arr: any[] = []
            if (params.del) {
                arr = state.syncIds.filter((id: any) => id !== params.del)
            } else {
                arr = [...state.syncIds, params.add]
            }
            return { ...state, syncIds: arr }
        case 'initData':
            return { ...state, allData: params?.data ? params.data : [], }
        default:
            return state;
    }
}

export default function useMaterialContent() {
    const { dispatchNews } = useModel('useOperating.useNews', (model: { dispatch: any }) => ({ dispatchNews: model.dispatch }))
    const getData = useAjax((params: GetMediaList) => getMediaList(params), { cacheKey: 'getModaldata' })
    const delData = useAjax((params: { id: string }) => delMediaList(params), { msgNmae: '删除' })
    const delWxData = useAjax((id: number) => delMediawx(id), { msgNmae: '删除' })
    const addData = useAjax((params: MediaList) => addMediaList(params), { msgNmae: '添加' })
    const editData = useAjax((params: MediaList) => editMediaList(params), { msgNmae: '编辑' })
    const tagData = useAjax((params: { type: string }) => getTagList(params), { cacheKey: 'tagData' })
    const classGet = useAjax((params: any) => getClass(params))
    const classDel = useAjax((params: { id: string }) => delClass(params), { msgNmae: '删除' })
    const classAdd = useAjax((params: { groupName: string }) => addClass(params), { msgNmae: '添加' })
    const classEdit = useAjax((params: { groupName: string, id: string }) => editClass(params), { msgNmae: '编辑' })
    const addGraphic = useAjax((params: CreateGraphic) => createGraphic(params), { msgNmae: '添加' })
    const addGraphicMaterial = useAjax((params: CreateGraphic) => createGraphicMaterial(params), { msgNmae: '添加' })
    const getGraphic = useAjax((params: GetGraphicList) => getGraphicList(params), { cacheKey: 'getGraphicList' })
    const graphicEdit = useAjax((params: EditGraphic) => editGraphic(params), { msgNmae: '编辑' })
    const graphicMaterialEdit = useAjax((params: EditGraphic) => editGraphicWxMaterial(params), { msgNmae: '编辑' })
    const getWeData = useAjax((params: GetWeChatData) => getWeChatData(params), { cacheKey: 'getWeChatData' })
    const getWeItData = useAjax((params: GetWeChatITData) => getWeChatITData(params), { cacheKey: 'getWeChatITData' })
    const getWXInfo = useAjax((params: {id: number, isCon?: boolean}) => getWxMediaInfo(params))
    const getBdGraphicDetail = useAjax((params: { id: string }) => getGraphicDetail(params), { cacheKey: 'getGraphicDetail' })
    const sync = useAjax((params: { appId: string[], mediaId: string }) => syncMedias(params), { msgNmae: '同步' })
    const syncWx = useAjax((params: { appId: string[], mediaId: string }) => syncPermanentGraphicMedias(params), { msgNmae: '操作' })
    const update = useAjax((params: { mpId: number, mediaType: string }) => updateMediaCache(params), { msgNmae: '更新' })
    const importNews = useAjax((params: { url: string }) => exportMediaByUrl(params))
    const syncQuery = useAjax((params: any) => syncResult(params))
    const bantchAdds = useAjax((params: any) => bantchAdd(params))
    const deloss = useAjax((params: any) => delOss(params))

    //请求上传地址
    const fileUrl = useAjax((params: { type: string }) => getFileUrl(params), {
        manual: true,
    })
    const [state, dispatch] = useReducer(reducer, { mediaType: 5, isPublic: 0, allData: [], syncIds: [] })
    let config: any = {
        '图文素材': '5',
        '视频': '3',
        '音频': '2',
        '图片': '1'
    }
    const actionKey = useCallback((key: string) => {
        dispatch({ type: 'setType', params: { mediaType: config[key] } })
    }, [])

    //首次获取类型列表
    useEffect(() => {
        if (sessionStorage.getItem('Admin-Token')) {
            // classGet.run()
        }
    }, [])
    //群发轮询查询媒体id
    let pollNews = useCallback((data, props) => {
        let time: any = null
        let tokens: string[] = []
        data?.forEach((wx: string) => {
            Object.values(wx).forEach((token: string) => {
                tokens.push(token)
            })
        })
        time = setInterval(() => syncQuery.run(tokens).then((res: any) => {
            if (res) {
                let isOk = res.every((wx: { appId: string, name: string, state: 0 | 1 | 2, mediaId: string }) => {//是否全部同步完成
                    if (wx.state !== 0) { //是否状态不等同步中
                        if (wx.state === 1) {//同步完成
                            notification.success({
                                message: wx.name + '同步素材成功,可以正常群发！',
                            });
                            dispatchNews({ type: 'mediaId', params: { mediaId: wx.mediaId } })
                        }
                        if (wx.state === 2) {//同步失败
                            notification.error({
                                message: wx.name + '同步素材失败，无法正常群发，请重操作！',
                            });
                        }
                    }
                    return wx.state !== 0
                })
                if (isOk) {
                    clearInterval(time)
                    time = null
                }
            }
        }), 3000)
    }, [])
    //轮询查询结果
    let poll = useCallback((data, mediaId) => {
        let time: any = null
        let tokens: string[] = []
        let newArr = [...data]
        newArr.forEach((wx: string) => {
            Object.values(wx).forEach((token: string) => {
                tokens.push(token)
            })
        })
        time = setInterval(() => syncQuery.run(tokens).then((res: any[]) => {
            if (res) {
                let isOk = res.every((wx: { appId: string, name: string, state: 0 | 1 | 2, mediaId: string }) => {//是否全部同步完成
                    if (wx.state !== 0) { //是否状态不等同步中
                        if (wx.state === 1) {//同步完成
                            notification.success({
                                message: wx.name + '同步素材成功！',
                            });
                        }
                        if (wx.state === 2) {//同步失败
                            notification.error({
                                message: wx.name + '同步素材失败！',
                            });
                        }
                        newArr.forEach((arr: any) => {//同步成功或失败剔除下次查询
                            Object.keys(arr).forEach((id: string) => {
                                if (id === wx.appId) {
                                    tokens = tokens.filter((token: string) => token !== arr[id])
                                }
                            })
                        })
                    }
                    return wx.state !== 0
                })
                if (isOk) {
                    notification.success({
                        message: '全部公众号同步完成！',
                    });
                    dispatch({ type: 'syncIds', params: { del: mediaId || '' } })
                    clearInterval(time)
                    time = null
                }
            }
        }), 3000)
    }, [])
    return {
        state,
        actionKey,
        dispatch,
        getData,
        delData,
        addData,
        editData,
        tagData,
        classGet,
        classDel,
        classAdd,
        classEdit,
        addGraphic,
        getGraphic,
        graphicEdit,
        getWeData,
        getWeItData,
        getWXInfo,
        sync,
        syncWx,
        delWxData,
        addGraphicMaterial,
        graphicMaterialEdit,
        fileUrl,
        getBdGraphicDetail,
        importNews,
        update,
        poll,
        pollNews,
        syncQuery,
        bantchAdds,
        deloss,
    }
}
