<template>
  <span>
    <component v-if="old" :is="type" v-bind="linkProps(url)"  @click="handle">
      <slot />
    </component>
    <component v-else :is="type" v-bind="linkProps(url)">
      <slot />
    </component>
  </span>
</template>

<script>
import { isExternal } from '@/utils/validate'
import { mapActions } from 'vuex';

export default {
  props: {
    to: {
      type: String,
      required: true
    }
  },
  computed: {
    isExternal() {
      return isExternal(this.to)
    },
    type() {
      if(this.old === false) return 'router-link';
      if (this.isExternal) {
        return 'a'
      }
      return 'a'
    }
  },
  data(){
    return {
      old: true,
      url: '',
    }
  },
  created() {
    this.old = !(this.$setting.routerMode === 'hash');
    if(this.$router.options.mode === 'hash' && this.$router.options.base) {
      this.url = `${this.$router.options.base}#${this.to}`;
    }else{
      this.url =  this.to;
    }

  },
  methods: {
    ...mapActions({
      delAllViews: 'tagsView/delAllViews',
    }),

    handle(){
      let to = this.to;
      if(this.$router.options.mode === 'hash' && this.$router.options.base) {
        to = `${this.$router.options.base}#${to}`;
      }
      this.url = to;
      this.delAllViews();
      this.$router.push(to)
      //window.location.href = to
    },
    linkProps(to) {
      if (this.isExternal) {
        return {
          href: to,
          target: '_blank',
          rel: 'noopener'
        }
      }
      if(this.$router.options.mode === 'hash' && this.$router.options.base) {
        to = `${this.$router.options.base}#${to}`;
      }
      return {
        to: to
      }
    }
  }
}
</script>
