<script>
import events from './events'
import { CACHE_INCLUDED_ROUTES } from '@/store/mutation-types'
import Vue from 'vue'
import { EventBus } from '@/eventBus'
export default {
  name: 'MultiTab',
  props: {
    showFavor: {
      type: Boolean,
      default: false
    },
    favorLists: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      fullPathList: [],
      pages: [],
      activeKey: '',
      newTabIndex: 0,
      favor: false,
    }
  },
  created () {
    // bind event
    events.$on('open', val => {
      if (!val) {
        throw new Error(`multi-tab: open tab ${val} err`)
      }
      this.activeKey = val
    }).$on('close', val => {
      if (!val) {
        this.closeThat(this.activeKey)
        return
      }
      this.closeThat(val)
    }).$on('rename', ({ key, name }) => {
      // console.log('rename', key, name)
      try {
        const item = this.pages.find(item => item.path === key)
        item.meta.customTitle = name
        this.$forceUpdate()
      } catch (e) {
      }
    }).$on('renameByFullPath', ({ fullPath, name }) => {
      // console.log('renameByFullPath', fullPath, name)
      try {
        const item = this.pages.find(item => item.fullPath === fullPath)
        item.title = name
        this.$forceUpdate()
      } catch (e) {
        console.log('renameByFullPath', e)
      }
    })

    this.pages.push({ id: this.$route.meta.id, title: this.$route.meta.title, fullPath: this.$route.fullPath })
    this.fullPathList.push(this.$route.fullPath)
    this.selectedLastPath()
  },
  methods: {
    onEdit (targetKey, action) {
      this[action](targetKey)
    },
    remove (targetKey) {
      if (targetKey.indexOf('report/view') >= 0) {
        EventBus.$emit('deleteIframe', targetKey.split('?')[0] ? targetKey.split('?')[0] : '')
        this.pages = this.pages.filter(page => page.fullPath !== targetKey)
        this.fullPathList = this.fullPathList.filter(path => path !== targetKey)
        // 判断当前标签是否关闭，若关闭则跳转到最后一个还存在的标签页
        if (!this.fullPathList.includes(this.activeKey)) {
          this.selectedLastPath()
        }
        var routers = Vue.ls.get(CACHE_INCLUDED_ROUTES)
        if (routers.includes(targetKey)) {
          routers.splice(routers.findIndex(item => item === targetKey), 1)
        }
        Vue.ls.set(CACHE_INCLUDED_ROUTES, routers)
        this.$router.push({ path: targetKey })
        this.$router.push({ path: this.activeKey })
      } else {
        this.pages = this.pages.filter(page => page.fullPath !== targetKey)
        this.fullPathList = this.fullPathList.filter(path => path !== targetKey)
        // 判断当前标签是否关闭，若关闭则跳转到最后一个还存在的标签页
        if (!this.fullPathList.includes(this.activeKey)) {
          this.selectedLastPath()
        }
        var routers = Vue.ls.get(CACHE_INCLUDED_ROUTES)
        if (routers.includes(targetKey)) {
          routers.splice(routers.findIndex(item => item === targetKey), 1)
        }
        Vue.ls.set(CACHE_INCLUDED_ROUTES, routers)
        this.$router.push({ path: targetKey })
        this.$router.push({ path: this.activeKey })
      }
    },
    selectedLastPath () {
      this.activeKey = this.fullPathList[this.fullPathList.length - 1]
    },

    // content menu
    closeThat (e) {
      // 判断是否为最后一个标签页，如果是最后一个，则无法被关闭
      const path = this.$route.fullPath
      if (this.fullPathList.length > 1) {
        this.remove(e)
      } else {
        this.$message.info('这是最后一个标签了, 无法被关闭')
      }
    },
    closeLeft (e) {
      const currentIndex = this.fullPathList.indexOf(e)
      if (currentIndex > 0) {
        this.fullPathList.forEach((item, index) => {
          if (index < currentIndex) {
            this.remove(item)
          }
        })
      } else {
        this.$message.info('左侧没有标签')
      }
    },
    closeRight (e) {
      const currentIndex = this.fullPathList.indexOf(e)
      if (currentIndex < (this.fullPathList.length - 1)) {
        this.fullPathList.forEach((item, index) => {
          if (index > currentIndex) {
            this.remove(item)
          }
        })
      } else {
        this.$message.info('右侧没有标签')
      }
    },
    closeAll (e) {
      const currentIndex = this.fullPathList.indexOf(e)
      this.fullPathList.forEach((item, index) => {
        if (index !== currentIndex) {
          this.remove(item)
        }
      })
      this.$router.push({ path: e })
    },

    handleMenuClick (key, route) {
      this[key](route)
    },
    renderTabPaneMenu (e) {
      const favor = this.favorLists.filter(x => x.tailInfos.tUmResource.webUrl === e).length !== 0
      return (
        <a-menu {...{ on: { click: ({ key, item, domEvent }) => { this.handleMenuClick(key, e) } } }}>
          <a-menu-item key="closeThat">关闭当前标签</a-menu-item>
          <a-menu-item key="closeRight">关闭右侧</a-menu-item>
          <a-menu-item key="closeLeft">关闭左侧</a-menu-item>
          <a-menu-item key="closeAll">关闭全部</a-menu-item>
        </a-menu>
      )
    },
    // render
    renderTabPane (title, keyPath) {
      const menu = this.renderTabPaneMenu(keyPath)

      return (
        <a-dropdown overlay={menu} trigger={['contextmenu']}>
          <span style={{ userSelect: 'none' }}>{ title }</span>
        </a-dropdown>
      )
    }
  },
  watch: {
    '$route': function (newVal) {
      this.activeKey = newVal.fullPath
       if (this.fullPathList.indexOf(newVal.fullPath) < 0) {
        this.fullPathList.push(newVal.fullPath)
        this.pages.push({ id: newVal.meta.id, title: newVal.meta.title, fullPath: newVal.fullPath })
      }
      // 泊位安排，报表传入的参数不同，更新页面
      if (this.activeKey.indexOf('/report/view/') >= 0) {
        const routeArr = this.activeKey.split('_')
        if (routeArr.length === 2) {
          for (const index in this.fullPathList) {
            const element = this.fullPathList[index]
            if (element && element !== this.activeKey && element.indexOf(routeArr[0]) >= 0 && element.indexOf(routeArr[1]) < 0) {
              EventBus.$emit('deleteIframe', element)
              this.pages = this.pages.filter(page => page.fullPath !== element)
              this.fullPathList = this.fullPathList.filter(path => path !== element)
            }
          }
        }
      } else {
      const duplicateRoutes = [
        '/book/ModifyBook',
        '/book/CntInBook',
        '/book/CntOutBook',
        '/book/BokSundry',
        '/book/ChanegeVessel',
        '/book/EmptyContainerTransit',
        '/containervessel/DesignateVoyageClose',
        '/container/ActInventoryBl',
        '/container/EPYEPCompare',
        '/vessel/Vplan'
      ]
      for (const dupRoute of duplicateRoutes) {
        if (this.activeKey.indexOf(dupRoute) >= 0) {
          for (var item in this.fullPathList) {
            if (this.fullPathList[item].indexOf(dupRoute) >= 0 && this.fullPathList[item] !== this.activeKey) {
              this.fullPathList.splice(item, 1)
            }
          }
          for (var items in this.pages) {
            if (this.pages[items].fullPath.indexOf(dupRoute) >= 0 && this.pages[items].fullPath !== this.activeKey) {
              this.pages.splice(items, 1)
            }
          }
        }
      }
      }
    },
    activeKey: function (newPathKey) {
      this.$router.push({ path: newPathKey })
    }
  },
  render () {
    // eslint-disable-next-line no-unused-vars
    const { onEdit, $data: { pages } } = this
    // 获取收藏列表
    if (this.showFavor) {
      for (const favor of this.favorLists) {
        const favorPage = {
          id: favor.resourceId.toString(),
          title: favor.tailInfos.tUmResource.name,
          fullPath: favor.tailInfos.tUmResource.webUrl
        }
        if (this.pages.filter(x => x.id === favorPage.id && x.title === favorPage.title && x.fullPath === favorPage.fullPath).length === 0) {
          this.fullPathList.push(favor.tailInfos.tUmResource.webUrl)
          this.pages.push(favorPage)
        }
      }
      this.$emit('setShowFavor', false)
    }
    const cacheRouterArray = this.pages.map(e => e.fullPath)
    Vue.ls.set(CACHE_INCLUDED_ROUTES, cacheRouterArray)
    const panes = this.pages.map(page => {
      return (
        <a-tab-pane
          tab={this.renderTabPane(page.title, page.fullPath)}
          key={page.fullPath} closable={this.pages.length > 1}>
        </a-tab-pane>)
    })

    return (
      <div class="ant-pro-multi-tab">
        <div class="ant-pro-multi-tab-wrapper">
          <a-tabs
            hideAdd
            type={'editable-card'}
            v-model={this.activeKey}
            tabBarStyle={{ background: '#FFF', margin: 0, paddingLeft: '16px', paddingTop: '1px', width: 'calc(100% - 100px)' }}
            {...{ on: { edit: onEdit } }}>
            {panes}
          </a-tabs>
        </div>
      </div>
    )
  }
}
</script>
<style>

</style>
<style scoped>
.ant-pro-multi-tab {
    margin: -23px -24px 8px -24px;
    background: #fff;
}

</style>
