import { useAjax } from '@/Hook/useAjax';
import { kefuMsgStrategyAdd, kefuMsgStrategyDel, kefuMsgStrategyDetail, kefuMsgStrategyEdit, kefuMsgStrategyGet, kefuMsgStrategyOn, kefuMsgStrategyRestart, kefuMsgStrategyDays, kefuMsgStrategyHistoryNews, kefuMsgStrategyDels } from '@/services/operating/news';
import moment from 'moment';
import { useCallback, useEffect, useReducer } from 'react'
type State = {
    visible: boolean,//弹窗开启与否
    wxVisible: boolean,//微信公众号选择弹窗
    moreVisible: boolean,//批量弹窗
    msgVisible: boolean,//图片，视频，音频类型弹窗
    textVisible: boolean,//文字类型弹窗
    graphicVisible: boolean,//图文类型弹窗
    msgContents: any[],//当前出入的数据
    delId: number[],//上次删除的ID集合
    fans: 0 | 1,//群发粉丝
    taskName: string,//任务名称
    msgType: 'mpnews' | 'text' | 'voice' | 'mpvideo' | 'image',//消息类型
    mobile?: string,
    actionWX: any,//当前微信
    mpIds: any[],//批量选中的微信
    triggerType: number,//发送方式
    weekDay: number,//星期几
    time: string,//时分
    sendTime: string,//指定时间
    enabled: 0 | 1,//0暂停1启用
    msgStrategy: 0 | 1, // 0全部推送 1 随机回复一条
    mpFansListDto: {
        sex: 'all' | 0 | 1 | 2,// 'all'全部，0未知，1男，2女
        tagIds: any[],
        tagType: 0 | 1 | 2, // 0：并集,1：交集,2：取反

    },

}
export type Action = {
    type: 'show' | 'wxShow' | 'moreShow' |
    'msgType' | 'msgVisible' |
    'textVisible' | 'graphicVisible' |
    'setDate' | 'setTime'  | 'setWeekDay' | 'setFans' | 'setSex' |
    'setMpFansListDto' | 'initData' | 'setActionWX' | 'setActionWXs' | 'setName' | 'triggerType' | 'setEnabled' | 'setMsgStrategy' |
    'addList' | 'delList' | 'edit' | 'up' | 'down'
    ,
    params?: any
}
function reducer(state: State, action: Action) {
    let { type, params } = action
    let { msgContents } = state
    let newArr: any[] = []
    switch (type) {
        case 'addList':
            newArr = [...msgContents]
            let indexId: number
            let newIds: any[] = []
            if (state?.delId?.length > 0) {//假如delId存在代表删除过数据，取删除的数据的Id做为新素材的ID避免重复ID
                indexId = state.delId[0]
                newIds = state.delId.filter((id) => id !== state.delId[0])
            } else {//假如不存在那就是第一次新建只要设ID为数组的长度+1就行
                indexId = msgContents.length + 1
            }
            if (params.list.index && !params.list.indexId) {//index存在indexId不存在表示是插入
                newArr.forEach((item: any, index: number) => {
                    if (item.indexId === params.list.index) {
                        newArr.splice(index + 1, 0, { ...params.list, indexId })
                    }
                })
            } else {//最后插入
                newArr.push({ ...params.list, indexId })
            }
            return { ...state, msgContents: newArr, delId: newIds }
        case 'edit':
            newArr = [...msgContents]
            newArr.forEach((item: any, index: number) => {
                if (item.indexId === params.list.index) {
                    newArr.splice(index, 1, { ...item, ...params.list })
                }
            })
            return { ...state, msgContents: newArr }
        case 'delList':
            let delId = [...state.delId, params.indexId]//存放本次删除的ID以备新增时使用
            return { ...state, msgContents: msgContents.filter((item: any) => item.indexId !== params.indexId), delId }
        case 'up':
            newArr = [...msgContents]
            msgContents.forEach((item: any, index: number) => {
                if (item.indexId === params.indexId) {
                    newArr[index - 1] = item
                    newArr[index] = msgContents[index - 1]
                }
            })
            return { ...state, msgContents: newArr }
        case 'down':
            newArr = [...msgContents]
            msgContents.forEach((item: any, index: number) => {
                if (item.indexId === params.indexId) {
                    newArr[index + 1] = item
                    newArr[index] = msgContents[index + 1]
                }
            })
            return { ...state, msgContents: newArr }
        case 'setActionWX':
            return { ...state, actionWX: params.actionWX }
        case 'setActionWXs':
            return { ...state, mpIds: params.mpIds }
        case 'show':
            return { ...state, visible: !state.visible }
        case 'wxShow':
            return { ...state, wxVisible: !state.wxVisible }
        case 'moreShow':
            return { ...state, moreVisible: !state.moreVisible }
        case 'msgType':
            return { ...state, msgType: params.msgType }
        case 'msgVisible':
            return { ...state, msgVisible: !state.msgVisible }
        case 'textVisible':
            return { ...state, textVisible: !state.textVisible }
        case 'graphicVisible':
            return { ...state, graphicVisible: !state.graphicVisible }
        case 'setDate':
            return { ...state, sendTime: params.sendTime }
        case 'setWeekDay':
            return { ...state, weekDay: params.weekDay }
        case 'triggerType':
            return { ...state, triggerType: params.triggerType }
        case 'setTime':
            return { ...state, time: params.time }
        case 'setEnabled':
            return { ...state, enabled: params.enabled }
        case 'setMsgStrategy':
            return { ...state, msgStrategy: params.msgStrategy }
        case 'setFans':
            return { ...state, fans: params.fans }
        case 'setSex':
            return { ...state, sex: params.sex }
        case 'setName':
            return { ...state, taskName: params.taskName }
        case 'setMpFansListDto':
            return { ...state, mpFansListDto: { ...state.mpFansListDto, ...params } }
        case 'initData':
            if (!params) {
                return {
                    visible: false,
                    wxVisible: false,
                    moreVisible: false,
                    msgType: 'mpnews',
                    msgVisible: false,
                    graphicVisible: false,
                    textVisible: false,
                    time: moment(new Date()).format('HH:mm'),
                    fans: 1,
                    taskName: '',
                    sex: 'all',
                    actionWX: null,
                    msgContents: [],
                    delId: [],
                    mpIds: [],
                    triggerType: 0,
                    enabled: 1,
                    msgStrategy: 0,
                    weekDay: 2,
                    sendTime: null,
                    resDelayHours: 0,//时
                    resDelayMinutes: 0,//分
                    resDelaySecond: 0,//秒
                    mpFansListDto: {
                        sex: 'all',
                        tagIds: [],
                        tagType: 0
                    }
                }
            }
            return { ...state, ...params }
        default:
            return state;
    }
}
export default function useAservice() {
    const [state, dispatch] = useReducer(reducer, {
        visible: false,
        wxVisible: false,
        moreVisible: false,
        msgType: 'mpnews',
        msgVisible: false,
        msgContents: [],
        delId: [],
        graphicVisible: false,
        textVisible: false,
        time: moment(new Date()).format('HH:mm'),
        fans: 1,
        taskName: '',
        sex: 'all',
        actionWX: null,
        mpIds: [],
        triggerType: 1,
        enabled: 1,
        msgStrategy: 0,
        weekDay: 1,
        sendTime: null,
        resDelayHours: 0,//时
        resDelayMinutes: 0,//分
        resDelaySecond: 0,//秒
        mpFansListDto: {
            sex: 'all',
            tagIds: [],
            tagType: 0
        }
    })
    const addKefuMsgStrategy = useAjax((params?: any) => kefuMsgStrategyAdd(params))
    const editKefuMsgStrategy = useAjax((params: any) => kefuMsgStrategyEdit(params), { msgNmae: '编辑' })
    const delKefuMsgStrategy = useAjax((params: any) => kefuMsgStrategyDel(params), { msgNmae: '删除' })
    const delskefu = useAjax((params) => kefuMsgStrategyDels(params), { msgNmae: '批量删除' })
    const restartKefuMsgStrategy = useAjax((params: { strategyId: number, belongUserId: number }) => kefuMsgStrategyRestart(params), { msgNmae: '启动' })
    const onKefuMsgStrategy = useAjax((params: any) => kefuMsgStrategyOn(params), { msgNmae: '操作' })
    const getKefuMsgStrategy = useAjax((params: any) => kefuMsgStrategyGet(params))
    const detailKefuMsgStrategy = useAjax((params: any) => kefuMsgStrategyDetail(params))
    const daysKefuMsgStrategy = useAjax((params: { strategyId: number, pageNum: number, pageSize: number, belongUserId: number, mpId?: string }) => kefuMsgStrategyDays(params))
    const historyKefuMsgStrategy = useAjax((params: { pageNum: number, pageSize: number }) => kefuMsgStrategyHistoryNews(params))

    /** 初始化数据*/
    const initData = useCallback((data: any) => {
        dispatch({ type: 'initData', params: { data } })
    }, [])
    /** 添加list*/
    const addList = useCallback((list: any) => {
        dispatch({ type: 'addList', params: { list } })
    }, [])
    const editList = useCallback((list: any) => {
        dispatch({ type: 'edit', params: { list } })
    }, [])
    /**删除list */
    const delList = useCallback((indexId: any) => {
        dispatch({ type: 'delList', params: { indexId } })
    }, [])
    /** 向上移动*/
    const up = useCallback((indexId: any) => {
        dispatch({ type: 'up', params: { indexId } })
    }, [])
    /** 向下移动*/
    const down = useCallback((indexId: any) => {
        dispatch({ type: 'down', params: { indexId } })
    }, [])
    useEffect(() => {
        localStorage.setItem('collapsed', state.visible ? '1' : '0')
    }, [state.visible])
    console.log('useAservice=>sate.msgContents====>', state?.msgContents)
    return {
        state,
        addKefuMsgStrategy,
        editKefuMsgStrategy,
        delKefuMsgStrategy,
        getKefuMsgStrategy,
        onKefuMsgStrategy,
        detailKefuMsgStrategy,
        restartKefuMsgStrategy,
        daysKefuMsgStrategy,
        historyKefuMsgStrategy,
        delskefu,
        initData,
        dispatch,
        addList,
        delList,
        editList,
        up,
        down,
    }
}
