<script>
import events from './events'
import PlgTabPane from '@/components/MultiTab/PlgTabPane.vue'
import { mapState } from 'vuex'
import Icon from '../PlgIcon'

export default {
  name: 'MultiTab',
  props: {
    i18nRender: { type: Function },
    siderWidth:{
        type: [String, Number],
        default: 210,
      },
    contentWidth:{
        type: String,
        default: "Fluid",
      },
    themeColor:{
      type: String,
      default: ""
    }
  },
  data() {
    return {
      fullPathList: [],
      pages: [],
      activeKey: '',
      newTabIndex: 0,
    }
  },
  computed: {
    ...mapState({
      layout: (state) => state.app.layout,
    }),
  },
  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 }) => {
        try {
          const item = this.pages.find((item) => item.path === key)
          item.meta.customTitle = name
          this.$forceUpdate()
        } catch (e) {}
      })

    this.pages.push(this.$route)
    this.fullPathList.push(this.$route.fullPath)
    this.selectedLastPath()
  },
  methods: {
    onEdit(targetKey, action) {
      this[action](targetKey)
    },
    remove(targetKey) {
      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()
      }
    },
    selectedLastPath() {
      this.activeKey = this.fullPathList[this.fullPathList.length - 1]
    },

    // content menu
    closeThat(e) {
      // 判断是否为最后一个标签页，如果是最后一个，则无法被关闭
      if (this.fullPathList.length > 1) {
        this.remove(e)
      } else {
        this.$message.info('这是最后一个标签了, 无法被关闭')
      }
    },
    closeOther(e){
      this.closeRight(e)
      this.closeLeft(e)
    },
    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)
        }
      })
    },
    closeMenuClick(key, route) {
      this[key](route)
    },
    renderTabPaneMenu(e) {
      return (
        <a-menu
          {...{
            on: {
              click: ({ key, item, domEvent }) => {
                this.closeMenuClick(key, e)
              },
            },
          }}
        >
          <a-menu-item key="closeThat">关闭</a-menu-item>
           <a-menu-item key="closeOther">关闭其它</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,icon) {
      const menu = this.renderTabPaneMenu(keyPath)
      let ico =  icon ? <Icon type={icon} pstyle={{marginRight:'5px'}} /> : undefined
      if(icon){
        if(this.themeColor && this.themeColor !== ''){
          ico =  <Icon type={icon} pstyle={{marginRight:'5px',color:this.themeColor}} />
        }
      }


      return (
        <a-dropdown overlay={menu} trigger={['contextmenu']}>
          <span style={{ userSelect: 'none' }}>
           {ico}
           {this.i18nRender(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(newVal)
      }
    },
    activeKey: function (newPathKey) {
      this.$router.push({ path: newPathKey })
      this.$emit('activeKey',newPathKey)
    },
    pages(value){
      this.$emit('pages',value)

    }
  },
  render() {
    const {
      onEdit,
      $data: { pages },
      layout,
    } = this

    const panes = pages.map((page) => {
      return (
        <PlgTabPane
          tab={this.renderTabPane(page.meta.customTitle || page.meta.title, page.fullPath,page.meta.icon)}
          key={page.fullPath}
          closable={pages.length > 1}
        >
        </PlgTabPane>
      )
    })
    //  {page.meta.iframe && <IframeView  path={page.meta.iframePath} />}

    const { sideCollapsed } = this.$store.getters

    let styles = {
      width: layout == 'topmenu' ? `${this.contentWidth=='Fluid'?'100%':'1200px'}` : `calc(100% - ${sideCollapsed ? 80 : this.siderWidth}px)`,
    }

    if (layout == 'topmenu') {
      styles = {
        ...styles,
      }
    }

    return (
      <div class="ant-pro-multi-tab" style={styles}>
        <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' }}
            {...{ on: { edit: onEdit } }}
          >
            {panes}
          </a-tabs>
        </div>
      </div>
    )
  },
}
</script>

<style lang="less" scoped>
.ant-pro-multi-tab {
  position: fixed;
  z-index: 9;
  margin: -0px -24px 0px 0px !important;
  border-top: 1px solid #e8e8e8;
}
</style>
