import AdmVue from '@assets/js/adm-vue.js';
import axiosApi from '@assets/js/axios-api';
import { v4 as uuidv4, validate } from 'uuid';

const vm = new AdmVue({
  components: {
    TheCustomLinks: () => import(/* webpackChunkName: "TheCustomLinks" */ '@components/TheCustomLinks/index.vue'),
    FileManager: () => import(/* webpackChunkName: "FileManager" */ '@components/FileManager/index.vue'),
  },
  provide() {
    return {
      onAddLink: this.onAddLink,
      onRemoveLink: this.onRemoveLink,
      onChangeField: this.onChangeField,
      onChangeDraggable: this.onChangeDraggable,
    };
  },
  data() {
    return {
      configurations: {},
      open: false,
      customLinksId: null,
    };
  },
  computed: {
    nav() {
      return this.organizeLinks('Nav');
    },
    header() {
      return this.organizeLinks('Header');
    },
  },
  beforeMount() {
    this.tabs = this.tabs;
  },
  methods: {
    organizeLinks(type) {
      const { customLinks } = this.configurations;
      const links = customLinks.filter(
        customLinksItem => customLinksItem.position == this.TypeCustomLinks[type] && !customLinksItem.parent
      );
      for (let i = 0; i < links.length; i++) {
        const linksItem = links[i];
        linksItem.items = customLinks.filter(customLinksItem => linksItem.custom_links_id === customLinksItem.parent);
      }
      links.sort((a, b) => {
        if (a.order > b.order) return 1;
        if (a.order < b.order) return -1;
        return 0;
      });
      for (let i = 0; i < links.length; i++) {
        const linksItem = links[i];
        if (linksItem.items.length) {
          linksItem.items.sort((a, b) => {
            if (a.order > b.order) return 1;
            if (a.order < b.order) return -1;
            return 0;
          });
        }
      }
      return links;
    },
    findLinkById(customLinksId) {
      return this.configurations.customLinks.find(customLinksItem => customLinksItem.custom_links_id === customLinksId);
    },
    onAddLink({ position, parent, order }) {
      const { customLinks } = this.configurations;

      let isEmpty;
      if (parent) {
        isEmpty = customLinks.some(
          customLinksItem =>
            customLinksItem.parent === parent && (customLinksItem.text === '' || customLinksItem.link === '')
        );
      } else {
        isEmpty = customLinks.some(customLinksItem => customLinksItem.text === '' || customLinksItem.link === '');
      }

      if (isEmpty) {
        return;
      }

      customLinks.push({
        custom_links_id: uuidv4(),
        icon: '',
        iconPreview: '',
        text: '',
        link: '',
        status: '1',
        order,
        position,
        parent,
      });
    },
    async onRemoveLink(customLinksId) {
      let deleteIds = [];

      if (!validate(customLinksId)) {
        deleteIds.push(customLinksId);
      }

      const sublinks = this.configurations.customLinks.filter(
        customLinksItem => customLinksItem.parent === customLinksId
      );

      for (let i = 0; i < sublinks.length; i++) {
        const { custom_links_id } = sublinks[i];
        if (!validate(custom_links_id)) {
          deleteIds.push(custom_links_id);
        }
        const sublinkIndex = this.configurations.customLinks.findIndex(
          customLinksItem => customLinksItem.custom_links_id === custom_links_id
        );
        this.configurations.customLinks.splice(sublinkIndex, 1);
      }

      const linkIndex = this.configurations.customLinks.findIndex(
        customLinksItem => customLinksItem.custom_links_id === customLinksId
      );
      this.configurations.customLinks.splice(linkIndex, 1);

      if (deleteIds.length === 0) {
        return;
      }

      try {
        await axiosApi.get(this.delete, {
          params: {
            id: deleteIds.join(),
          },
        });
      } catch (error) {
        console.log(error);
        this.alert = {
          type: 'warning',
          message: 'Aconteceu algo de inesperado, por favor tente novamente!',
        };
      }
    },
    onChangeField({ customLinksId, field, value }) {
      if (field === 'icon' && typeof value === 'undefined') {
        this.open = true;
        this.customLinksId = customLinksId;
        return;
      }

      const link = this.findLinkById(customLinksId);

      if (field === 'icon') {
        link['iconPreview'] = '';
      }
      link[field] = value;
    },
    onChangeDraggable(organizedLinks) {
      organizedLinks.map((organizedLinksItem, organizedLinksIndex) => {
        const customLinksIndex = this.configurations.customLinks.findIndex(
          customLinksItem => customLinksItem.custom_links_id === organizedLinksItem.custom_links_id
        );
        this.configurations.customLinks[customLinksIndex].order = organizedLinksIndex;
      });
    },
    onSelectedFile({ filename, thumbnail }) {
      const link = this.findLinkById(this.customLinksId);
      link['icon'] = filename;
      link['iconPreview'] = thumbnail;
    },
    onSelectedIcon(icon) {
      const link = this.findLinkById(this.customLinksId);
      link['icon'] = icon;
      link['iconPreview'] = icon;
    },
    formSuccess({ customLinks }) {
      this.configurations.customLinks = customLinks;
    },
  },
});

AdmVue.init(vm);
