import { getApp, getNum } from '@/app'
// import { Loading, Dialog } from '@/global_components/'
import { nextTick } from 'vue'
import common from '@/utils/common'

export default {
    namespaced: true,
    state() {
        return {
            tagsList: null,
            iconsList: null,
            tagClickType: {
                type:'',
                data:{}
            },
            timer: null,
            hotData: null,
            isEdit: false,
            tags: null,
            changeTagsList: [], //保存需要更改的tags
            positionInfo: null,
            icons: null,
            iconId: '',
            isFixed: false,
            inputLink: '',
            delIconList: [],
            enterVisible: false,
            editPosition: false,
            toggleIndex: null,
            isClick: false,
            leaveId: null,
            metaDelList: [],
            historyIcon: null, //记录上一个选择的icon
        }
    },
    getters: {
        iconId: state => state.iconId,
        hotData: state => state.hotData,
        inputLink: state => {
            let url = ''
            if (state.hotData) {
                if (state.hotData.media.link && state.hotData.media.link.length > 0) {
                    url = state.hotData.media.link[0].src
                } else {
                    url = state.inputLink
                }
            }

            return url
        },
        isEdit: state => state.isEdit,
        isFixed: state => state.isFixed,
        tagClickType: state => state.tagClickType,
        tags: (state, getters, rootState, rootGetters) => {
            let tags = state.tagsList
            if (!state.tags && tags) {
                state.tags = []

                for (let i = 0; i < tags.length; i++) {
                    let obj = {}
                    for (let key in tags[i]) {
                        if (key == 'media') {
                            obj[key] = JSON.parse(JSON.stringify(tags[i][key]))
                        } else {
                            obj[key] = tags[i][key]
                        }
                    }

                    state.tags.push(obj)
                }
            }
            getApp().TagManager.updatePosition(state.tags)
            return state.tags || []
        },
        icons: (state, getters, rootState, rootGetters) => {
            let icons = state.iconsList
            if (!state.icons && icons) {
                state.icons = []
                for (let i = 0; i < icons.length; i++) {
                    let sid = icons[i].split('.')[0]
                    state.icons.push({ sid: sid, name: icons[i] })
                }
            }

            return state.icons
        },
        enterVisible: state => state.enterVisible,
        editPosition: state => state.editPosition,
        toggleIndex: state => state.toggleIndex,
        leaveId: state => state.leaveId,
        isClick: state => state.isClick,
        positionInfo: state => state.positionInfo,
    },
    mutations: {
        add(state, payload) {
            state.isEdit = true
            state.isFixed = true
            state.hotData = {
                type: 'image',
                icon: '',
                title: '',
                content: '',
                sid: '',
                isHidden: false,
                position: null,
                media: {
                    image: [],
                    video: [],
                    audio: [],
                    link: [],
                },
            }
            this.commit('enterEdit')
        },
        load(state, data) {
            if (data) {
                state.tagsList = data.tags
                state.iconsList = data.icons
            } else {
                state.tagsList = []
                state.iconsList = []
            }
        },
        setToggleIndex(state, payload) {
            //标记进入查看模式的索引
            state.toggleIndex = payload
        },
        addTag(state, tag) {
            this.commit('tag/add')
            tag.isAdd = true
            if (!state.tags) {
                state.tags = []
                state.tagsList = []
                state.tagsList.push(tag)
            }
            state.tags.push(tag)
            state.hotData = tag
            state.iconId = state.historyIcon ? state.historyIcon.split('.')[0] : '' //标记上次使用的icon
            state.hotData.icon = state.historyIcon ? state.historyIcon : ''
            state.hotData['type'] = 'image'
            state.hotData['title'] = ''
            state.hotData['content'] = ''
            state.hotData['media'] = { image: [], video: [], audio: [], link: [] }
        },
        setTagsList(state, payload) {
            let arr = []
            state.tagsList[payload.index] = payload.tag
            state.tagsList = arr.concat(state.tagsList)
            state.tags = null
        },
        edit(state, payload, rootState) {
            state.isEdit = true
            state.isFixed = true

            this.commit('enterEdit')
        },

        show(state, payload, rootState) {
            clearTimeout(state.timer)
            state.timer = null
            state.hotData = state.tags[payload]
            //选中当前icon
            if (state.hotData.icon != '') {
                state.iconId = state.hotData.icon.split('.')[0]
            } else {
                state.iconId = ''
            }
        },
        setLeaveId(state, payload) {
            state.leaveId = payload
        },
        save(state, payload) {
            this.commit('tag/updateData', payload)
            this.commit('tag/closeTag')
            this.commit('info/cancel')
        },
        updateData(state, payload) {
            if (state.icons && state.tagsList) {
                if (state.icons.length != state.iconsList.length) {
                    state.iconsList = JSON.parse(JSON.stringify(state.icons))
                    for (let i = 0; i < state.iconsList.length; i++) {
                        state.iconsList[i] = state.iconsList[i].name
                    }
                }
                //更新原始数据
                if (state.tagsList.length < state.tags.length) {
                    //更新新增热点
                    state.tagsList.unshift(state.tags[state.tags.length - 1])
                } else if (state.tagsList.length > state.tags.length) {
                    //更新删除热点
                } else {
                    //更新修改热点
                    for (let i = 0; i < state.tagsList.length; i++) {
                        if (payload.sid == state.tagsList[i].sid) {
                            for (let key in payload) {
                                if (key == 'media') {
                                    state.tagsList[i][key] = JSON.parse(JSON.stringify(payload[key]))
                                } else {
                                    state.tagsList[i][key] = payload[key]
                                }
                            }
                        }
                    }
                }
            }
            //删除相同的icon，需要修改原数据
            if (state.changeTagsList.length > 0) {
                for (let i = 0; i < state.tagsList.length; i++) {
                    for (let j = 0; j < state.changeTagsList.length; j++) {
                        if (state.tagsList[i].sid == state.changeTagsList[j].sid) {
                            state.tagsList[i].icon = ''
                        }
                    }
                }
                state.changeTagsList = []
            }
        },
        cancel(state, payload) {
            if (state.hotData) {
                //编辑热点取消
                this.commit('tag/setLink', '')
            } else {
                if (state.enterVisible) {
                    //热点可视取消
                    this.commit('setMode', 'panorama')
                    this.commit('setSceneUI', true)
                    state.enterVisible = false
                    state.editPosition = false
                    getApp().TagManager.hideAll()
                    getApp().TagManager.edit.cancelTagVisiSetting()
                }
            }
            if (state.positionInfo) {
                let { index, tag } = state.positionInfo
                // state.tagsList[index] = tag
                this.commit('tag/setTagsList', state.positionInfo)
                getApp().TagManager.updatePosition(state.tags)
            }
            state.metaDelList = []
            this.commit('tag/closeTag')
            this.commit('info/cancel')
        },
        async closeTag(state, payload) {
            //用于回滚热点
            state.tags = null
            state.icons = null
            state.delIconList = []
            state.isFixed = false
            state.iconId = ''
            state.isEdit = false
            if (state.positionInfo) {
                state.positionInfo = null
            }
            state.timer = setTimeout(() => {
                state.hotData = null
                clearTimeout(state.timer)
                state.timer = null
            }, 300)
        },

        setFixed(state, payload) {
            state.isFixed = payload
        },
        setTagClickType(state, payload) {
            state.tagClickType = payload.value || payload
        },
        setTitle(state, payload) {
            state.hotData.title = payload
        },
        setLink(state, payload) {
            state.inputLink = payload
        },
        setContent(state, payload) {
            state.hotData.content = payload.value ? payload.value : payload
        },
        setMetaType(state, type) {
            if (!state.hotData.media[type]) {
                state.hotData.media[type] = []
            }
            state.hotData.type = type
        },
        changeIcon(state, payload) {
            state.hotData.icon = payload.name
            state.iconId = payload.sid
        },
        pushIcon(state, payload) {
            state.icons.unshift(payload)
        },
        deleteIcon(state, icon) {
            for (let i = 0; i < state.icons.length; i++) {
                if (icon.name == state.icons[i].name) {
                    state.icons.splice(i, 1)
                }
            }

            if (!icon.fileName) {
                state.delIconList.push(icon.name)
                for (let i = 0; i < state.tags.length; i++) {
                    if (icon.name == state.tags[i].icon) {
                        let obj = {}
                        obj.sid = state.tags[i].sid
                        obj.icon = state.tags[i].icon
                        state.changeTagsList.push(obj)
                        state.tags[i].icon = ''
                    }
                }
            }
        },
        resetTagList(state, tagList) {
            for (let i = 0; i < tagList.length; i++) {
                if (tagList[i].sid == state.tagsList[i].sid) {
                    state.tagsList[i]['isHidden'] = JSON.parse(tagList[i].hotData).isHidden
                }
            }
        },
        setImageList(state, payload) {
            state.hotData.media.image = []
            state.hotData.media.image = payload
        },

        setVideo(state, payload) {
            state.hotData.media.video.push({ src: URL.createObjectURL(payload), file: payload })
        },
        setAudio(state, payload) {
            let data = {
                name: payload.name,
                file: payload,
                src: URL.createObjectURL(payload),
            }
            state.hotData.media.audio.push(data)
        },
        setWeb(state, payload) {
            state.hotData.media.link.push({ src: payload })
        },
        delMetas(state, payload) {
            switch (payload.type) {
                case 'image':
                    if (!state.hotData.media.image[payload.index].file) {
                        state.metaDelList.push(state.hotData.media.image[payload.index].src)
                    }
                    state.hotData.media.image.splice(payload.index, 1)
                    break
                case 'video':
                    if (!state.hotData.media.video[payload.index].file) {
                        state.metaDelList.push(state.hotData.media.video[payload.index].src)
                    }
                    state.hotData.media.video.splice(payload.index, 1)
                    break
                case 'audio':
                    if (!state.hotData.media.audio[payload.index].file) {
                        state.metaDelList.push(state.hotData.media.audio[payload.index].src)
                    }
                    state.hotData.media.audio.splice(payload.index, 1)
                    break
                case 'link':
                    state.hotData.media.link.splice(payload.index, 1)
                    break
            }
        },
        setClick(state, payload) {
            state.isClick = payload
        },
        gotoTag(state, item, tag) {
            nextTick(() => {
                let t = setTimeout(() => {
                    clearTimeout(t)
                    let tagBox = document.getElementById(`tagBox_${item.sid}`)
                    let arrowBox = document.getElementById(`arrow_${item.sid}`)
                    let tagBox_w = tagBox.getBoundingClientRect().width
                    let tagBox_h = tagBox.getBoundingClientRect().height
                    let arrowBox_w = arrowBox.getBoundingClientRect().width
                    let arrowBox_h = arrowBox.getBoundingClientRect().height

                    let params = {
                        sid: item.sid,

                        tagBox: {
                            width: tagBox_w,
                            height: tagBox_h,
                        },
                        arrowBox: {
                            width: arrowBox_w,
                            height: arrowBox_h,
                        },
                    }
                    if (tag) {
                        params.tag = tag
                    }
                    let position = getApp().config.mobile ? 'top' : 'left'
                    getApp().TagManager.focus(params, 'board', position)
                }, 0)
            })
        },
        setVisible(state, payload) {
            state.enterVisible = payload
            if (state.enterVisible) {
                getApp().TagManager.showAll()
            }

            this.commit('enterEdit')
            this.commit('setSceneUI', false)
        },
        setPosition(state, payload) {
            state.editPosition = payload.status

            if (payload.index >= 0) {
                state.positionInfo = {
                    index: payload.index,
                    tag: state.tagsList[payload.index],
                }
            }
        },
    },
    actions: {
        async getTagList({ commit, state }, payload) {
            let res = await getApp().remote_editor.tag_list({ num: getNum() })
            if (res.success) {
                state.tags = res.data.tags
            }
        },
        async tagDelete({ commit, state }, payload) {
            Loading.show()
            let params = {
                num: getNum(),
                sidList: [payload.item.sid],
            }

            return new Promise(function (resolve, reject) {
                getApp()
                    .remote_editor.tag_delete(params)
                    .then(res => {
                        Loading.hide()
                        if (res.success) {
                            state.tags.splice(payload.index, 1)
                            state.tagsList.splice(payload.index, 1)
                            resolve({ type: 'toast', tips: 'success', msg: 'common.deleteSuccess' })
                        } else {
                            resolve({ type: 'toast', tips: 'error', msg: 'common.deleteFail' })
                        }
                    })
                    .catch(err => {
                        Loading.hide()
                        resolve({ type: 'toast', tips: 'error', msg: 'common.deleteFail' })
                        reject(err)
                    })
            })
        },
        svaeTag({ state, commit, dispatch }, params) {
            return getApp().remote_editor.tag_save(params)
        },
        async delFile({ commit, state }, payload) {
            let type = state.hotData.type
            let params = {
                num: getNum(),
                bizType: 'tag-' + type,
                fileNames: state.metaDelList,
            }
            let res = await this.dispatch('delFiles', params)
            if (res.success) {
                state.metaDelList = []
            }
        },
        async save({ state, commit, dispatch }, payload) {
            if (state.hotData) {
                if (state.hotData.title.trim() == '') {
                    return Promise.reject({ type: 'toast', tips: 'warn', msg: 'tag.toolbox.hotspotTitleTips' })
                }
                let hotData = Object.assign({}, state.hotData)
                //新增的热点删除isAdd标识

                //删除visiblePanos
                if (hotData.visiblePanos) {
                    delete hotData.visiblePanos
                }
                if (hotData.visible) {
                    delete hotData.visible
                }
                let type = state.hotData.type

                //处理icon
                let upLoadIocns = []
                if (state.icons && state.icons.length > 0) {
                    for (let i = 0; i < state.icons.length; i++) {
                        //判断是否为新上传的
                        if (state.icons[i].fileName) {
                            let sid = state.icons[i].sid
                            let file = state.icons[i].name
                            let fileName = state.icons[i].fileName
                            let res = await this.dispatch('scene/upload_files', { base64: file, bizType: 'tag-icon', num: getNum(), type: 0, fileName: fileName })
                            upLoadIocns.push(fileName)
                            if (res.success) {
                                state.icons[i].name = fileName
                                state.icons[i].sid = sid
                                delete state.icons[i].fileName
                                if (state.icons[i].sid == state.iconId) {
                                    state.hotData.icon = state.icons[i].name
                                    hotData.icon = state.icons[i].name
                                }
                            }
                        }
                    }
                }
                if (state.metaDelList.length > 0) {
                    dispatch('delFile')
                }
                if (hotData.isAdd) {
                    state.historyIcon = hotData.icon
                    delete hotData.isAdd
                } else {
                    state.historyIcon = null
                }
                //处理媒体文件
                if (hotData.media[type] && hotData.media[type].length > 0) {
                    for (let i = 0; i < hotData.media[type].length; i++) {
                        if (hotData.media[type][i].file) {
                            let file = hotData.media[type][i].file
                            let sid = common.getRandomSid()
                            let suffix = file.type.split('/')[1]
                            let fileName = sid + '.' + suffix

                            let res = await this.dispatch('scene/upload_files', { files: file, bizType: 'tag-' + type, num: getNum(), type: 0, fileName: fileName })
                            if (res.success) {
                                hotData.media[type][i].src = fileName
                                hotData.media[type][i].name = file.name
                                delete hotData.media[type][i].file
                            }
                        }
                    }
                }

                for (let key in hotData.media) {
                    if (key != state.hotData.type) {
                        delete hotData.media[key]
                    }
                }
                //去除空html
                if (hotData.content.replace(/<[^>]+>/g, '') == '') {
                    hotData.content = ''
                    state.hotData.content = ''
                }
                let tagList = []

                if (state.changeTagsList && state.changeTagsList.length > 0) {
                    for (let i = 0; i < state.changeTagsList.length; i++) {
                        for (let k = 0; k < state.tags.length; k++) {
                            if (state.changeTagsList[i].sid == state.tags[k].sid) {
                                let hotData = Object.assign({}, state.tags[k])
                                if (hotData.visiblePanos) {
                                    delete hotData.visiblePanos
                                }
                                let data = {
                                    sid: hotData.sid,
                                    hotData: JSON.stringify(hotData),
                                }
                                tagList.push(data)
                            }
                        }
                    }
                } else {
                    tagList.push({
                        sid: hotData.sid,
                        hotData: JSON.stringify(hotData),
                    })
                }

                //是否判断是否删除icon
                if (state.delIconList && state.delIconList.length > 0) {
                    let res = await getApp().remote_editor.icons_delete({ num: getNum(), fileNameList: state.delIconList })
                    if (res.success) {
                        // state.copyIcons = []
                    }
                }

                let params = {
                    num: getNum(),
                    hotDataList: tagList,
                    icons: upLoadIocns,
                }
                let data = await dispatch('svaeTag', params)
                if (data.success) {
                    commit('save', hotData)
                }
                return data
            } else {
                //保存热点可视
                let { data, func } = getApp().TagManager.edit.saveTagVisi()
                if (!data || data.length == 0) {
                    //无改动
                    commit('cancel')
                } else {
                    let tagList = []
                    if (data.length > 0) {
                        for (let i = 0; i < data.length; i++) {
                            for (let j = 0; j < state.tagsList.length; j++) {
                                if (data[i].sid == state.tagsList[j].sid) {
                                    let hotData = Object.assign({}, state.tagsList[j])
                                    if (data[i].value.length == 0) {
                                        hotData['isHidden'] = true
                                        data[i]['isHidden'] = true
                                    } else {
                                        hotData['isHidden'] = false
                                        data[i]['isHidden'] = false
                                    }
                                    if (hotData.visiblePanos) {
                                        delete hotData.visiblePanos
                                    }
                                    if (hotData.visible) {
                                        delete hotData.visible
                                    }
                                    let obj = {
                                        sid: hotData.sid,
                                        hotData: JSON.stringify(hotData),
                                    }
                                    tagList.push(obj)
                                }
                            }
                        }
                    }

                    console.log(data)
                    return getApp()
                        .remote_editor.saveTagsVisible({ num: getNum(), data: JSON.stringify(data) })
                        .then(async res => {
                            if (res.success) {
                                func && func()
                                commit('resetTagList', tagList)
                                commit('cancel')
                            }
                            return res
                        })
                        .catch(err => {
                            console.log(err)
                            return err
                        })
                }
            }
        },
    },
}
