import {
    inviteCount,
    inviteList,
    inviteRead,
    inviteRemove,
    noticeCount,
    noticeList,
    noticeRead,
    noticeRemove,
    noticeStatus1,
    noticeStatus2,
    noticeStatus3,
    settingRead1,
    settingRead2,
    settingRead3,
} from '@/api/news.js'
import {
    tuiJianMission
} from '@/api/mission.js';
import website from '@/config/website.js'
const size = 20
const handler = {
    '0': {
        count: noticeCount,
        getList: noticeList,
        read: noticeRead,
        remove: noticeRemove
    },
    '1': {
        count: noticeStatus1,
        getList: tuiJianMission,
        read: settingRead1
    },
    '2': {
        count: noticeStatus2,
        read: settingRead2
    },
    '3': {
        count: noticeStatus3,
        read: settingRead3
    }
}

function getCount(data) {
    let sum = 0
    for (let key in data) {
        if (data[key] >= 0) {
            sum += data[key]
        }
    }
    return sum
}

let refreshTimer = null;

function startRefreshToken(dispatch) {
    refreshTimer = setInterval(() => {
        dispatch("newsInit");
    }, website.newsRefreshTime);
}

function stopRefreshToken() {
    clearInterval(refreshTimer)
}

const news = {
    state: {
        count: 0,
        data: {
            "0": {
                id: "0",
                uid: "0",
                title: "消息通知",
                icon: "../../static/img/notice.svg",
                page: {
                    current: 0,
                    size,
                    total: size
                },
                data: [],
                prop: {
                    title: 'title',
                    desc: (value) => {
                        if (value.data[0])
                            return value.data[0][0]['desc']
                    },
                    time: 'createTime',
                    isRead: 'isRead',
                    listDesc: 'desc',
                },
                navigateTo(item) {
                    uni.$once('getNewsDetail', (cb) => {
                        cb(item)
                    })
                    uni.navigateTo({
                        url: "/pages/news/newsDetail?type=0"
                    })
                }
            },
            "1": {
                id: "1",
                uid: "1",
                title: "推送零工岗位",
                icon: "../../static/img/renwu.png",
                page: {
                    current: 0,
                    size,
                    total: size
                },
                data: [],
                prop: {
                    title: 'missionTitle',
                    desc: (value) => {
                        if (value.data[0])
                            return `您收到${value.data[0][0]['companyName']}岗位`
                    },
                    time: 'createTime',
                    isRead: 'status',
                    listDesc: 'companyName',
                },
                navigateTo(item, dispatch) {
                    dispatch('readNew2', {
                        key: '1',
                        id: item.noticeId
                    })
                    // uni.navigateTo({
                    //     url: `/pages/projectInfo/projectInfo?type=1&missionNo=${encodeURIComponent(item.missionNo)}&id=${encodeURIComponent(item.id)}`
                    // })
                },
            },
            "2": {
                id: "1",
                uid: "2",
                title: "推送全职岗位",
                icon: "../../static/img/gangwei.svg",
                page: {
                    current: 0,
                    size,
                    total: size
                },
                data: [],
                prop: {
                    title: 'missionTitle',
                    desc: (value) => {
                        if (value.data[0])
                            return `您收到${value.data[0][0]['companyName']}的岗位`
                    },
                    time: 'createTime',
                    isRead: 'status',
                    listDesc: 'companyName',
                },
                navigateTo(item, dispatch) {
                    dispatch('readNew2', {
                        key: '2',
                        id: item.noticeId
                    })
                    // uni.navigateTo({
                    //     url: `/pages/projectInfo/projectInfo?type=1&missionNo=${encodeURIComponent(item.missionNo)}&id=${encodeURIComponent(item.id)}`
                    // })
                }
            },
            "3": {
                id: "1",
                uid: "3",
                title: "推送政策指南",
                icon: "../../static/img/zhengce.svg",
                page: {
                    current: 0,
                    size,
                    total: size
                },
                data: [],
                prop: {
                    title: 'missionTitle',
                    desc: (value) => {
                        if (value.data[0])
                            return `您收到${value.data[0][0]['companyName']}的岗位`
                    },
                    time: 'createTime',
                    isRead: 'status',
                    listDesc: 'companyName',
                },
                navigateTo(item, dispatch) {
                    dispatch('readNew2', {
                        key: '3',
                        id: item.noticeId
                    })
                    // uni.navigateTo({
                    //     url: `/pages/projectInfo/projectInfo?type=1&missionNo=${encodeURIComponent(item.missionNo)}&id=${encodeURIComponent(item.id)}`
                    // })
                }
            }
        },
        unread: {
            "0": 0,
            "1": 0,
            "2": 0,
            "3": 0,
        },
        allUnread: 0,
        dic: {}
    },
    actions: {
        newsInit({
            dispatch
        }) {
            const ps = []
            ps.push(dispatch('getUnreadNum'))

            for (let key in handler) {
                ps.push(dispatch('newsReload', key))
            }
            return Promise.all(ps)
        },
        newsReload({
            dispatch,
            commit
        }, id) {
            commit('CLEAR_NEWS_DATA', id)
            return dispatch('newsGetNextPage', id)
        },
        getUnreadNum({
            commit
        }) {
            for (let key in handler) {
                handler[key].count().then((result) => {
                    console.log('result', result)
                    commit('SET_UNREADNUM', {
                        id: key,
                        count: result
                    })
                })
            }
        },
        newsGetNextPage({
            state,
            commit
        }, id) {
            const item = state.data[id]
            const page = item.page
            const current = page.current + 1
            return new Promise((resolve, reject) => {
                if (parseInt(page.total / page.size) + 1 < current) {
                    resolve()
                    return
                }
                if (!handler[id].getList) {
                    return
                }
                if (id === '1' || id === '2') {
                    handler[id].getList(['1'], id === '1' ? 0 : 1).then(res => {
                        const data = res.data.data;
                        commit('ADD_NEWS_DATA', {
                            id,
                            data: data.records,
                            current,
                            total: data.total
                        })
                        resolve(res)
                    }).catch(reject)
                } else {
                    handler[id].getList(current, page.size).then(res => {
                        const data = res.data.data;
                        commit('ADD_NEWS_DATA', {
                            id,
                            data: data.records,
                            current,
                            total: data.total
                        })
                        resolve(res)
                    }).catch(reject)
                }

            })
        },
        removeNew({
            commit
        }, {
            id,
            key,
            group,
            index
        }) {
            return new Promise((resolve, reject) => {
                commit('REMOVE_NEWS', {
                    id,
                    key,
                    group,
                    index
                })
                handler[key].remove(id).then(resolve, reject)
            })
        },
        readNew2({
            commit
        }, {
            key,
            id
        }) {
            return new Promise((resolve, reject) => {
                handler[key].read({
                    ids: id
                }).then(() => {
                    commit('changeUnread', {
                        key
                    })
                })
            })
        },
        readNew({
            commit
        }, {
            key,
            id
        }) {
            return new Promise((resolve, reject) => {
                commit('READ_NEWS', {
                    key,
                    id
                })
                handler[key].read(id).then(resolve, reject)
            })
        },
        endRefreshNewsTimer() {
            stopRefreshToken()
        },
        startRefreshNewsTimer({
            state,
            commit,
            dispatch
        }) {
            dispatch('newsInit').then(() => {
                startRefreshToken(dispatch);
            })
        },
        readUnread({
            commit
        }, {
            key,
        }) {
            return new Promise((resolve, reject) => {

            })
        }
    },
    mutations: {
        changeUnread: (state, {
            key
        }) => {
            if (state.unread[key]) {
                state.unread[key]--
                state.allUnread--
            }
        },
        SET_UNREADNUM: (state, {
            id,
            count
        }) => {
            state.unread[id] = count
            state.allUnread = getCount(state.unread)
        },
        CLEAR_NEWS_DATA: (state, id) => {
            state.data[id].page = {
                current: 0,
                size
            }
            state.data[id].data = []
        },
        ADD_NEWS_DATA: (state, {
            id,
            data,
            current,
            total
        }) => {
            if (!data) return
            data.forEach(item => {
                state.dic[item.id] = item
            })
            state.data[id].page.total = total
            state.data[id].page.current = current
            if (data.length > 0) {
                state.data[id].data.push(data)
            }
        },
        REMOVE_NEWS: (state, {
            id,
            key,
            group,
            index
        }) => {
            const readProp = state.data[key].prop['isRead']
            if (state.dic[id][readProp] === 0) {
                state.unread[key]--
                state.allUnread--
            }
            state.dic[id] = undefined
            const data = state.data[key].data
            data[group].splice(index, 1)
            if (data[group].length === 0) {
                data.splice(group, 1)
            }
        },
        READ_NEWS: (state, {
            key,
            id
        }) => {
            // http://localhost:1888/api/jobslink-api/desk/notice/noticeStatus
            const readProp = state.data[key].prop['isRead']
            console.log(state.dic, id, readProp)
            if (state.dic[id][readProp] === 0) {
                state.dic[id][readProp] = 1
                state.unread[key]--
                state.allUnread--
            }
        }
    },
    getters: {

    }
};
export default news;