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

const vm = new AdmVue({
  components: {
    BaseCard: () => import(/* webpackChunkName: "BaseCard" */ '@elements/BaseCard/index.vue'),
    BaseManual: () => import(/* webpackChunkName: "BaseManual" */ '@elements/BaseManual/index.vue'),
    HighlightEditor: () => import(/* webpackChunkName: "HighlightEditor" */ '@components/HighlightEditor/index.vue'),
    AsideContent: () => import(/* webpackChunkName: "AsideContent" */ '@components/AsideContent/index.vue'),
    BaseTabs: () => import(/* webpackChunkName: "BaseTabs" */ '@components/BaseTabs/index.vue'),
    BaseModal: () => import(/* webpackChunkName: "BaseModal" */ '@components/BaseModal/index.vue'),
  },
  data() {
    return {
      tabsCode: [],
      tracking_code: [],
      showLastCode: false,
      showNewCodeScreen: false,
      updateComponent: 0,
      excluded: [],
      presets: ['Google Analytics', 'Google Tag Manager'],
      showModal: false,
    };
  },
  computed: {
    sendData() {
      const tracking_code = this.tracking_code.map(trackingCodeItem => {
        if (validate(trackingCodeItem.tracking_code_id)) {
          delete trackingCodeItem.tracking_code_id;
        }
        return trackingCodeItem;
      });

      return {
        tracking_code,
        excluded: [...this.excluded],
      };
    },
    indexActiveCode() {
      return this.tabsCode.findIndex(item => item.active);
    },
    activeCode() {  
      if (this.indexActiveCode) {
        return this.tracking_code[this.indexActiveCode];
      }
      
      if (typeof this.tracking_code[0] !== 'undefined') {
        return this.tracking_code[0];
      }

      return {};
    },
    infoCode() {
      switch (this.activeCode.title) {
        case 'Google Analytics':
          return `
           <span class="text-small"> Crie uma conta e uma propriedade no Google Analytics 4. Copie e cole o código gerado. Deixe esse código em todas as páginas e no cabeçalho<br>
            Para mais informações acesse os </span><a class="text-info text-small text-bold" href="https://developers.google.com/analytics/devguides/collection/ga4" target="_blank">Adicionar o Google Analytics G4</a>.
          `;

        case 'Google Tag Manager':
          return `
            <span class="text-small">Copie e cole apenas o primeiro código do Google Tag Manager. Ignore o código do Google Tag Manager (noscript). Deixe esse código em todas as páginas e no cabeçalho.<br>
            Para mais informações acesse </span><a class="text-info text-small text-bold" href="https://developers.google.com/tag-manager/quickstart" target="_blank">Guia de início rápido</a> do Google Tag Manager.
          `;

        default:
          return '<i class="text-small">Esta opção ainda não possuí manual, tente entrar em contato com a equipe de suporte.</i>';
      }
    },
    buttonPresets() {
      return this.presets.filter(presetsItem => {
        if (this.tracking_code.find(trackingCodeItem => trackingCodeItem.title === presetsItem)) {
          return;
        }
        return presetsItem;
      });
    },
    textScript() {
      return this.activeCode.tag == 0 ? "Script" : "Meta Tag";
    },
    getPositions(){
      if(this.activeCode.tag == 0){
        return this.positions
      }else{
        this.activeCode.position == 1
      }
    }
  },
  watch: {
    tracking_code: {
      handler(value) {
        if (!value.length) {
          this.tabsCode = [];
          return;
        }

        let active = this.activeCode
          ? value.findIndex(item => item.tracking_code_id === this.activeCode.tracking_code_id)
          : 0;

        if (this.showLastCode) {
          this.showLastCode = false;
          active = value.length - 1;
        }

        this.tabsCode = value.map((trackingCodeItem, trackingCodeIndex) => {
          return {
            text: trackingCodeItem.title,
            active: trackingCodeIndex === active,
          };
        });
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    onPrimaryAdd() {
      const hasEmptyScript = this.tracking_code.find(
        trackingCodeItem => trackingCodeItem.script === '' || trackingCodeItem.title === ''
      );

      if (hasEmptyScript) {
        this.alert = {
          type: 'error',
          message: 'Termine o código antes de criar um novo.',
        };
        this.showNewCodeScreen = false;
        return;
      }

      if (this.buttonPresets.length > 0) {
        this.showNewCodeScreen = true;
      } else {
        this.onAdd('Novo código');
      }
    },
    onAdd(preset) {
      const trackingCode = {
        tracking_code_id: uuidv4(),
        title: preset,
        all_layouts: 1,
        position: 1,
        script: '',
        tag: 0,
        status: 1,
      };

      if(this.presets.find(presetItem => presetItem === trackingCode.title) &&
        this.tracking_code.filter(trackingCodeItem => {
          return this.presets.find(presetItem => presetItem === trackingCodeItem.title);
        }).length > 0) {
        this.alert = {
          type: 'warning',
          message: 'Google Tag Manager e Analytics juntos, pode gerar duplicidade nos dados dos relatórios!',
        };
      }

      this.tracking_code.push(trackingCode);

      this.showLastCode = true;
      this.showNewCodeScreen = false;
    },
    onRemove() {
      if (!validate(this.activeCode.tracking_code_id)) {
        this.setExcludedIds(this.activeCode.tracking_code_id);
      }

      const activeIndexCode = this.tracking_code.findIndex(
        trackingCodeItem => trackingCodeItem.tracking_code_id === this.activeCode.tracking_code_id
      );

      if (activeIndexCode === this.tracking_code.length - 1) {
        this.showLastCode = true;
      }

      this.tracking_code.splice(activeIndexCode, 1);
    },
    setExcludedIds(tracking_code_id) {
      if (typeof tracking_code_id !== 'undefined') {
        this.excluded = [...this.excluded, tracking_code_id];
      }
    },
    formSuccess({ list }) {
      this.tracking_code = list;
    },
    onClickTab(tabs) {
      this.updateComponent += 1;
      this.tabsCode = tabs;
    },
    openModal(){
      this.showModal = true;
    },
    onClose(){
      this.showModal = false;
    },
  },

});

AdmVue.init(vm);
