<template>
    <div id='tags-view-container' class='tags-view-container'>
        <scroll-pane ref='scrollPane' :watch-data='visitedTags' class='tags-view-wrapper'>
            <router-link v-for='tag in visitedTags' ref='tag' :key='tag.routeName'
                         :class="isActive(tag) ? 'active' : ''"
                         :to='tag.routePath' tag='span' class='tags-view-item'
                         @click.middle.native="!isAffix(tag) ? closeSelectedTag(tag) : ''"
                         @contextmenu.prevent.native='openMenu(tag, $event)'>
                <i v-if='tag.routeName == routeName' class='el-icon-s-home'></i>
                {{ tag.title }}
                <span v-if='tag.routeName == routeName' />
                <span v-else class='el-icon-close' @click.prevent.stop='closeSelectedTag(tag)' />
            </router-link>
        </scroll-pane>
        <ul v-if='selectedTag.routeName==routeName' v-show='visible' :style="{ left: left + 'px', top: top + 'px' }"
            class='contextmenu'>
            <li @click='refreshSelectedTag(selectedTag)'><i class='el-icon-refresh-right'></i> 刷新页面</li>
            <li @click='closeOthersTags(selectedTag)'><i class='el-icon-circle-close'></i> 关闭其他</li>
            <li @click='closeAllTags'><i class='el-icon-circle-close'></i> 关闭所有</li>
        </ul>
        <ul v-else v-show='visible' :style="{ left: left + 'px', top: top + 'px' }" class='contextmenu'>
            <li @click='refreshSelectedTag(selectedTag)'><i class='el-icon-refresh-right'></i> 刷新页面</li>
            <li @click='closeSelectedTag(selectedTag)'><i class='el-icon-close'></i> 关闭当前</li>
            <li @click='closeOthersTags(selectedTag)'><i class='el-icon-circle-close'></i> 关闭其他</li>
            <li @click='closeAllTags'><i class='el-icon-circle-close'></i> 关闭所有</li>
        </ul>
    </div>
</template>
<script>
import ScrollPane from './ScrollPane'
import Sortable from 'sortablejs'
import { mapGetters } from 'vuex'

export default {
    components: { ScrollPane },
    data() {
        return {
            visible: false,
            top: 0,
            left: 0,
            selectedTag: {},
            affixTags: [],
            menulists: [],
            path: '',
            routeName: '',
            title: ''
        }
    },
    computed: {
        visitedTags() {
            // console.log("+++++++++++++++++===================++++++++++++++++++++",this.$store.state.tagsView.visitedTags)
            let arr = this.$store.state.tagsView.visitedTags
            arr.filter((item, index) => arr.indexOf(item) === index)
            //console.log("########----------",this.$store.state.user.userInfo.loginName)
            //   if(this.$store.state.user.userInfo==null){
            //     return arr;
            //   }else{
            //   if(this.$store.state.user.userInfo.roleCode[0]=='root'){
            //   //  arr[0]={
            //   //  routeName:"qualityzhilestimate",
            //   //  routePath: "/harmonic-boot/area/powerAssessment",
            //   //  title: "电能质量综合评估"
            //   //  };

            //   // arr[0]={
            //   //   routeName:"test",
            //   //   routePath: "/jbei/QualityOverview",
            //   //   title: "电能质量概览"
            //   // };
            //         arr[0]={
            //           routeName:"dashboard",
            //           routePath: "/dashboard/index",
            //           title: "首页概览"
            //         };
            //    }
            //   if(this.$store.state.user.userInfo.loginName=='njcnpqs'){

            //     arr[0]={
            //     routeName:"uesrmanagement",
            //     routePath: "/user-boot/user/list",
            //     title: "用户管理"
            //    };

            //   }else if(this.$store.state.user.userInfo.loginName=='njcnser'){

            //     arr[0]={
            //     routeName:"premage",
            //     routePath: "/BusinessAdministrator/TerminalManagement/FrontManagement",
            //     title: "前置管理"
            //   };

            //   }else if(this.$store.state.user.userInfo.loginName=='njcnsh'){

            //     arr[0]={
            //     routeName:"sys-user-boot-check",
            //     routePath: "/user/checkUserListview",
            //     title: "审核列表"
            //   };

            //   }else if(this.$store.state.user.userInfo.loginName=='njcnsj'){

            //     arr[0]={
            //     routeName:"Management",
            //     routePath: "/BusinessAdministrator/Audit/Operations/Management",
            //     title: "审计列表管理"
            //   };

            //   }else{

            //     arr[0]={
            //     routeName:"qualityzhilestimate",
            //     routePath: "/harmonic-boot/area/powerAssessment",
            //     title: "电能质量综合评估"
            //   };

            //      arr[0]={
            //     routeName:"test",
            //     routePath: "/jbei/QualityOverview",
            //     title: "电能质量概览"
            //   };


            // console.log("########----------",this.$store.state.user)
            // arr[0]={
            //   routeName:"dashboard",
            //   routePath: "/dashboard/index",
            //   title: "首页概览"
            // };
            this.menulists = JSON.parse(window.sessionStorage.getItem('menus'))
            this.getmuen(this.menulists[0])
            arr[0] = {
                routeName: this.routeName,
                routePath: this.path,
                title: this.title
            }
            //   }
            // }
            // console.log('++++++++++++', arr)
            return arr
        }
    },
    watch: {
        $route() {
            this.addTags()
            //this.moveToCurrentTag();
        },
        visible(value) {
            if (value) {
                document.body.addEventListener('click', this.closeMenu)
            } else {
                document.body.removeEventListener('click', this.closeMenu)
            }
        }
    },

    mounted() {
        this.addTags()
        this.setSort()
        //this.filtertag()
    },
    methods: {
        getmuen(data) {
            if (data.children.length == 0) {
                this.path = data.routePath
                this.routeName = data.routeName
                this.title = data.title
            } else {
                this.getmuen(data.children[0])
            }


        },
        filtertag() {
            let arr = this.$store.state.tagsView.visitedTags
            arr.filter((item, index) => arr.indexOf(item) === index)
            return arr
        },
        isActive(tag) {
            return tag.routePath === this.$route.fullPath
        },
        isAffix(tag) {
            const { affixTags } = this.$store.state.tagsView
            return affixTags.some((t) => t.routeName === tag.routeName)
        },
        addTags() {
            // alert(0)
            const { name } = this.$route
            if (name) {
                this.$store.dispatch('tagsView/addView', this.$route)
            }
            return false
        },
        //移除当前 标签
        moveToCurrentTag() {
            // alert(1)
            const tags = this.$refs.tag
            tags.splice(0, 1)
            // this.$router.push("/Statistical-analysis/indicatorClassification");
            this.$nextTick(() => {
                for (const tag of tags) {
                    if (tag.to === this.$route.fullPath) {
                        //if (tag.to !== "/Statistical-analysis/indicatorClassification") {
                        this.$refs.scrollPane.moveToTarget(tag)
                        break
                        //}
                    }
                }
            })
        },
        //刷新当前
        refreshSelectedTag(tag) {
            // alert(2)
            const fullPath = tag.routePath
            this.$store.commit('tagsView/DEL_CACHED_VIEW', tag.routeName)
            this.$nextTick(() => {
                this.$router.replace({
                    path: '/redirect' + fullPath
                })
            })
        },
        open() {

        },
        //关闭选择
        closeSelectedTag(tag) {
            //  console.log("+++++++++++++++++++++",tag)
            if (tag.title == '算法编辑器') {
                this.$confirm('此操作将关闭删除该标签,是否已保存! 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$store.dispatch('tagsView/delTag', tag).then(({ visitedTags }) => {
                        if (this.isActive(tag)) {
                            this.toLastView(visitedTags, tag)
                            // this.$message({
                            //   type: 'success',
                            //   message: '确认保存成功!'
                            // });
                            //this.$router.push("/Statistical-analysis/indicatorClassification");
                            // this.$nextTick(() => {
                            //   this.$router.replace({
                            //     path: "/Statistical-analysis/indicatorClassification",
                            //   });
                            //   this.$router.push("/Statistical-analysis/indicatorClassification");
                            // });
                        }
                    })

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消关闭'
                    })
                })
            } else {
                this.$store.dispatch('tagsView/delTag', tag).then(({ visitedTags }) => {
                    if (this.isActive(tag)) {
                        this.toLastView(visitedTags, tag)
                    }
                })
            }
        },
        //关闭其他
        closeOthersTags(tag) {
            // alert(4)
            this.$router.push(tag.routePath)
            const fullPath = tag.routePath
            this.$store.dispatch('tagsView/delOthersTags', tag)
            this.$nextTick(() => {
                this.$router.replace({
                    path: '/redirect' + fullPath
                })
            })
            this.moveToCurrentTag()
        },
        //关闭所有
        closeAllTags() {
            // alert(5)
            this.$store.dispatch('tagsView/delAllTags')
            //this.$router.push("/dashboard/index");
            //this.$router.push("/jbei/QualityOverview");
            this.$nextTick(() => {

                //  this.$router.replace({
                //    path: "/dashboard/index",
                //  });
                //this.$router.push("/dashboard/index");
                // this.$router.replace({
                //     path: "/jbei/QualityOverview",
                //   });
                //   this.$router.push("/jbei/QualityOverview");
            })
            // 关完还剩下的
            const { visitedTags } = this.$store.state.tagsView
            const lastTag = visitedTags[visitedTags.length - 1]
            if (lastTag) {
                if (this.$route.fullPath !== lastTag.routePath) {
                    this.$router.push(lastTag.routePath)
                }
            } else {
                this.getmuen(this.menulists[0])
                this.$router.replace({ path: '/redirect' + this.path })
                //if (this.$route.name === "dashboard") {
                // this.$router.replace({ path: "/redirect" + this.$route.path });
                //} else {
                //  this.$router.push("/");
                //}
            }
        },
        toLastView(visitedTags, view) {
            // alert(6)
            const latestTag = visitedTags.slice(-1)[0]
            if (latestTag) {
                this.$router.push(latestTag.routePath)
            } else {
                if (view.name === 'dashboard') {
                    //  this.$router.replace({ path: "/redirect" + view.routePath });
                } else {
                    this.$router.push('/')
                }
            }
        },
        openMenu(tag, e) {
            const menuMinWidth = 105
            const windowWidth = document.documentElement.clientWidth
            const maxLeft = windowWidth - menuMinWidth // left boundary
            const left = e.clientX + 15 // 15: margin right

            if (left > maxLeft) {
                this.left = maxLeft
            } else {
                this.left = left
            }

            this.top = e.clientY
            this.visible = true
            this.selectedTag = tag
        },
        closeMenu() {
            this.visible = false
        },
        setSort() {
            const el = this.$refs.scrollPane.$el.querySelector('.el-scrollbar__view')
            this.sortable = Sortable.create(el, {
                ghostClass: 'tags-view-ghost', // Class name for the drop placeholder,
                setData: function(dataTransfer) {
                    // to avoid Firefox bug
                    // Detail see : https://github.com/RubaXa/Sortable/issues/1012
                    dataTransfer.setData('Text', '')
                }
            })
            //console.log("kjkjkjkjkjkjkjkjkjkjk",this.$router)
            // this.$router.push('/Statistical-analysis/indicatorClassification')
        }
    }
}
</script>

<style lang='scss' scoped>
.tags-view-container {
    width: 100%;
    height: 34px;
    background: rgb(255, 255, 255);
    border-bottom: 1px solid #d8dce5;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.12), 0 0 3px 0 rgba(0, 0, 0, 0.04);

    .tags-view-wrapper {
        .tags-view-item {
            position: relative;
            display: inline-block;
            height: 26px;
            padding: 0 8px;
            margin-top: 4px;
            margin-left: 5px;
            font-size: 12px;
            line-height: 26px;
            color: $themeColor;
            cursor: pointer;
            background: #fff;
            border: 1px solid #d9ecff;
            border-radius: 3px;

            &:first-of-type {
                margin-left: 15px;
            }

            &:last-of-type {
                margin-right: 15px;
            }

            &.active {
                color: #fff;
                background-color: $themeColor;
                border-color: $themeColor;

                &::before {
                    position: relative;
                    //display: inline-block;
                    width: 8px;
                    height: 8px;
                    margin-right: 2px;
                    //  background: #fff;
                    border-radius: 50%;
                    content: "";
                }
            }
        }
    }

    .contextmenu {
        position: fixed;
        z-index: 3000;
        padding: 5px 0;
        margin: 0;
        font-size: 12px;
        font-weight: 400;
        color: #333;
        list-style-type: none;
        background: #fff;
        border-radius: 4px;
        box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);

        li {
            padding: 7px 16px;
            margin: 0;
            cursor: pointer;

            &:hover {
                background: #eee;
            }
        }
    }
}
</style>

<style lang='scss' scoped>
//reset element css of el-icon-close
::v-deep .el-scrollbar__wrap {
    overflow: auto !important;
    height: 48px !important;
    margin-bottom: 0 !important;
}

::v-deep ::-webkit-scrollbar-thumb {
    background: $themeColor !important;
    height: 8px ! important
}

::-webkit-scrollbar {
    display: block;
    width: 8px !important;
    height: 14px;
}

::v-deep .el-scrollbar__thumb {
    position: relative;
    display: block;
    width: 0;
    height: 0;
    cursor: pointer !important;
    border-radius: inherit;
    background-color: $themeColor !important;
    -webkit-transition: .3s background-color;
    transition: .3s background-color;
}
</style>