<script>
import events from './events'

export default {
  name: 'MultiTab',
  data () {
    return {
      fullPathList: [],
      tabsList: [],
      pages: [],
      activeKey: '',
      newTabIndex: 0
    }
  },
  inject: ['reloadView'],
  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) {
      }
    })

    this.pages.push(this.$route)
    this.tabsList.push(this.$route.name)
    this.selectedLastPath()
  },
  methods: {
    onEdit (targetKey, action) {
      this[action](targetKey)
    },
    onChange (targetKey) {
      const index = this.tabsList.indexOf(targetKey)
      if (index >= 0) {
        const row = this.pages[index]
        if (row && row.fullPath && row.fullPath.indexOf('/list') == -1) { // 非列表页
          this.$store.state.app.isNewSubTab = true
        } else {
          this.$store.state.app.isNewSubTab = false
        }
      }
    },
    remove (targetKey) {
      this.pages = this.pages.filter(page => page.name !== targetKey)
      this.tabsList = this.tabsList.filter(name => name !== targetKey)
      // 判断当前标签是否关闭，若关闭则跳转到最后一个还存在的标签页
      if (!this.tabsList.includes(this.activeKey)) {
        this.selectedLastPath()
      }
    },
    selectedLastPath () {
      this.activeKey = this.tabsList[this.tabsList.length - 1]
    },
    // content menu
    refashThat (e) {
      this.reloadView()
    },
    closeThat (e) {
      // 判断是否为最后一个标签页，如果是最后一个，则无法被关闭
      if (this.tabsList.length > 1) {
        this.remove(e)
      } else {
        this.$message.info('这是最后一个标签了, 无法被关闭')
      }
    },
    closeLeft (e) {
      const currentIndex = this.tabsList.indexOf(e)
      if (currentIndex > 0) {
        this.tabsList.forEach((item, index) => {
          if (index < currentIndex) {
            this.remove(item)
          }
        })
      } else {
        this.$message.info('左侧没有标签')
      }
    },
    closeRight (e) {
      const currentIndex = this.tabsList.indexOf(e)
      if (currentIndex < (this.tabsList.length - 1)) {
        this.tabsList.forEach((item, index) => {
          if (index > currentIndex) {
            this.remove(item)
          }
        })
      } else {
        this.$message.info('右侧没有标签')
      }
    },
    closeAll (e) {
      const currentIndex = this.tabsList.indexOf(e)
      this.tabsList.forEach((item, index) => {
        if (index !== currentIndex) {
          this.remove(item)
        }
      })
    },
    closeMenuClick (key, route) {
      this[key](route)
    },
    renderTabPaneMenu (e) {
      // return (
      //   <a-menu {...{ on: { click: ({ key, item, domEvent }) => { this.closeMenuClick(key, e) } } }}>
      //     {this.activeKey == e ? (<a-menu-item key="refashThat">刷新页面</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>
      // )
      return (
        <a-menu {...{ on: { click: ({ key, item, domEvent }) => { this.closeMenuClick(key, e) } } }}>
          <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, oldVal) {
      // 父页面（列表）进入子页面（编辑、详情）再返回至父页面时关闭子页面页签   子页面点击“返回列表”
      if (oldVal && oldVal.name && newVal.query.closeLastOldTab) {
        if (oldVal.name.indexOf('List') == -1) { // 要关闭的页面不能是列表页
          this.remove(oldVal.name) // 关闭子页面
        }
      }
      this.activeKey = newVal.name
      const index = this.tabsList.indexOf(newVal.name)
      // 解决页面地址相同参数不同时打开多个页签问题（例 详情页id或sn不同时）
      if (index < 0) { // 不存在
        this.tabsList.push(newVal.name)
        this.pages.push(newVal)
        this.$store.state.app.isNewTab = true
      } else { // 已存在
        this.pages.splice(index, 1, newVal)
        this.$store.state.app.isNewTab = false
      }
    },
    activeKey: function (newPathKey) {
      const row = this.pages.find(item => item.name == newPathKey)
      if (row.fullPath.indexOf('/list') == -1) {
        this.$router.push({ path: row.fullPath })
      } else {
        // this.$router.push({ path: row.fullPath, query: { closeLastOldTab: true } })  //  需求：切换页签需关掉子页面
        this.$router.push({ path: row.path }) //  需求：切换页签不需关掉子页面
      }
    }
  },
  render () {
    const { onEdit, onChange, refashThat, $data: { pages } } = this
    const panes = pages.map(page => {
      return (
        <a-tab-pane
          style={{ height: 0 }}
          key={page.name} closable={pages.length > 1}
        >
          <span slot="tab">
            {this.renderTabPane(page.meta.customTitle || page.meta.title, page.name)}
            {this.activeKey == 'page.name' ? (<a-icon
              {...{ on: { click: refashThat } }}
              style={{ marginLeft: '8px', fontSize: '12px' }}
              type="reload" />) : ''}
          </span>
        </a-tab-pane>)
    })

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