import Vue from 'vue';
import { Local } from "@/utils/storage";

Vue.mixin({
  methods: {
    $page(url) {
      const host = window.location.host;
      const protocol = window.location.protocol;
      const SYSTEM_SET = "system_set_config__";
      const SystemConfig = Local.get(SYSTEM_SET)
      let contextPath = SystemConfig.publicPath;
      if (!contextPath) {
        contextPath = '';
      }
      return `${ protocol }//${ host }` + contextPath + "#" + (url ? url : "");
    }
  }
});

const rootNav = {
  provide() {
    return {
      $routerView: this
    }
  },
  data() {
    return {
      drawerConfig: {
        type: '',
        width: '70%',
        direction: 'rtl',
        title: '',
        viewVisible: false
      },
    }
  },
  mounted() {
    this.$bus.$on('$close', () => {
      this.drawerConfig.viewVisible = false;
    });

    this.$bus.$on('$closeAndRefresh', async (url) => {
      this.drawerConfig.viewVisible = false;
      await this.$router.push({ path: url })
    });
  },
  methods: {
    async $open(url, params = { query: {} }) {
      const query = []
      console.log('-----------', this.$routerView);
      Object.keys(params.query).forEach(field => query.push(field + "=" + params.query[field]));
      url = (this.$page(url) + (query.length > 0 ? ("?" + query.join("&")) : ""));
      delete params.query;
      console.log('new url: ', url);
      this.drawerConfig = Object.assign({ ...this.drawerConfig },
        { ...params },
        { viewVisible: true },
        { url: url });
    },
    handleClose() {
      this.drawerConfig.viewVisible = false;
    }
  },
}

const childNav = {
  inject: {
    $routerView: {
      default: undefined
    }
  },
  methods: {
    async $toPage(url, params, options) {
      if (this.$routerView) {
        await this.$routerView.$open(url, { ...params }, options);
      } else {
        await this.$open(url, { ...params }, options);
      }
    },
    $closeAndRefresh(url) {
      if (window.parent.$bus) {
        window.parent.$bus.$emit('$closeAndRefresh')
      } else {
        this.$bus.$emit('closePage')
      }
    },
    $close() {
      if (window.parent.$bus) {
        window.parent.$bus.$emit('$close')
      } else {
        this.$bus.$emit('$close')
      }
    }
  }
}

export { rootNav, childNav }
