import AdmVue from '@assets/js/adm-vue';
import initVue from '@assets/js/initVue';

import { v4 as uuidv4 } from 'uuid';
import { validate as uuidValidate } from 'uuid';

const vm = new AdmVue({
  components: {
    BaseCard: () => import(/* webpackChunkName: "BaseCard" */ '@elements/BaseCard/index.vue'),
    BaseInputFile: () => import(/* webpackChunkName: "BaseInputFile" */ '@elements/BaseInputFile/index.vue'),
    BaseTabs: () => import(/* webpackChunkName: "BaseTabs" */ '@components/BaseTabs/index.vue'),
    SearchProduct: () => import(/* webpackChunkName: "SearchProduct" */ '@components/SearchProduct/index.vue'),
    draggable: () => import(/* webpackChunkName: "draggable" */ 'vuedraggable'),
    bannersMosaic: () => import(/* webpackChunkName: "bannersMosaic" */ './bannersMosaic.vue'),
  },
  data() {
    return {
      configurations: {},
      banners: [],
      displayAside: 'BannerList',
      displayMain: 'empty',
      bannerContent: {},
      bannerContentTab: [
        {text:'Imagens', active:true},
        {text:'Layouts', active:false}
      ],
      bannerContentImage: {},
      bannerContentLayout: {},
      layoutName: '',
      drag: true,
      excluded: [],
      banner_home_page: {},
      bannerHomePageTab: [
        {text:'Imagens', active:true},
        {text:'Produtos', active:false},
        {text:'Dinâmicos', active:false}
      ],
      openSearchProduct: false,
      imageError: {},
    };
  },
  watch: {
    bannerContentLayout(value) {
      const layoutSelected = this.layouts.find(layout => layout.layout_id == value.layout_id);
      if (layoutSelected) {
        this.layoutName = layoutSelected.name;
      }
    },
  },
  computed: {
    sendData() {
      return {
        banners: this.banners,
        modules: this.configurations,
        excluded: this.excluded,
        bannerHomePage: this.banner_home_page,
      };
    },
  },
  mounted() {
    this.isLoading = false;
  },
  methods: {
    getFirstNumericIndex(string) {
      // banner[123][title] retorna 123
      return string.replace(/^[^\[]+\[(\d+)\].*/, '$1');
    },
    getLastSentenceLowerCase(string) {
      // BannerHomePageUpdateImage retorna image
      return string.replace(/.*([A-Z][a-z]+)$/, (_, $1) => $1.toLowerCase());
    },
    getElementWithError(string) {
      // banner_image[0][banner_image_description][1][title] retorna banner_image_description[1][title]
      return string.replace(/^[^\[]+\[\d+\]\[([^\[]+)\](.*)/,'$1$2');
    },
    getArrayName(string) {
      // banners[0][name] retorna banners
      return string.replace(/^([^\[]+).*/,'$1');
    },
    formError({ errors }) {
      const { bannerHomePage, bannerHomePageConfig, ...errorsModules } = errors;
      let hasErrorDisplayed = false;

      if(bannerHomePageConfig){
        this.bannerContentImage = this.banner_home_page;
        this.displayAside = 'bannerHomePageConfig';

        setTimeout(() => {
          this.$refs.validationBannerHomePageConfig.setErrors(bannerHomePageConfig);
        },1000);
      }

      for (const key in bannerHomePage) {
        const keys = Object.keys(bannerHomePage[key]);

        if (!keys[0]) {
          continue;
        }

        const errorOriginKey = this.getFirstNumericIndex(keys[0]);

        if (key !== null) {
          const bannerType = this.getLastSentenceLowerCase(key);

          this.bannerContentImage = this.banner_home_page[`banner_${bannerType}`][errorOriginKey];
          this.displayAside = key;

          const errorsSameObject = {};
          const err = bannerHomePage[key];
          for (const keyErr in err) {
            if (keyErr.indexOf(`[${errorOriginKey}]`) != -1) {
              const newKeyErr = this.getElementWithError(keyErr);
              errorsSameObject[newKeyErr] = err[keyErr];
              if (newKeyErr == 'image') {
                this.imageError['image'] = err[keyErr];
              }
            }
          }

          const keyObject = 'validation' + key.charAt(0).toUpperCase() + key.slice(1);

          setTimeout(() => {
            this.$refs[keyObject].setErrors(errorsSameObject);
          }, 1000);

          hasErrorDisplayed = true;

          break;
        } else {
          unset(key);
        }
      }

      if (!hasErrorDisplayed) {
        for (const key in errorsModules) {
          const keys = Object.keys(errorsModules[key]);

          if (!keys[0]) {
            continue;
          }

          const bannerType = keys[0];
          const errorOriginKey = this.getFirstNumericIndex(Object.keys(errorsModules[key][bannerType])[0]);
          const modulesKey = this.getArrayName(Object.keys(errorsModules[key][bannerType])[0]);

          if (key !== null) {

            if (key == 'modules') {
              this.bannerContentLayout = this.configurations[modulesKey][errorOriginKey];
              this.banners.forEach(bannerContent => {
                if (bannerContent.banner_id === this.bannerContentLayout.banner_id) {
                  this.bannerContent = bannerContent;
                }
              });
            } else {
              this.bannerContent = this.banners[errorOriginKey];
            }

            this.displayAside = bannerType;

            const errorsSameObject = {};
            const err = errorsModules[key][bannerType];

            for (const keyErr in err) {
              if (keyErr.indexOf(`[${errorOriginKey}]`) != -1) {
                const newKeyErr = this.getElementWithError(keyErr);
                if (keyErr.indexOf('banner_image') != -1) {
                  const index = this.getFirstNumericIndex(newKeyErr);
                  const bannerImageDescription = Object.keys(err)[0];

                  if (bannerImageDescription.indexOf('banner_image_description') != -1) {
                    errorsSameObject[newKeyErr] = err[keyErr];
                  } else {
                    this.imageError['image'] = err[keyErr];
                  }

                  this.bannerContentImage = this.bannerContent['banner_image'][index];
                } else {
                  errorsSameObject[newKeyErr] = err[keyErr];
                }
              }
            }

            const keyObject = 'validation' + bannerType.charAt(0).toUpperCase() + bannerType.slice(1);

            setTimeout(() => {
              this.$refs[keyObject].setErrors(errorsSameObject);
            }, 1000);

            break;
          } else {
            unset(key);
          }
        }
      }


    },
    setData(data) {
      Object.assign(this, data);
    },
    addNewBanner() {
      this.bannerContent = {
        banner_id: uuidv4(),
        name: 'Novo banner',
        status: '1',
        banner_image: [],
        index: this.banners.length,
      };
      this.displayAside = 'bannerConfig';
    },
    addBanner() {
      this.banners.push(this.bannerContent);
    },
    isUuid(id) {
      return uuidValidate(id);
    },
    onBannerUpdate(index) {
      this.displayAside = 'bannerUpdate';
      this.bannerContent = this.banners[index];
      this.bannerContent.index = index;
    },
    onBannerUpdateImage(page) {
      this.displayAside = page;
      this.bannerContentImage = {
        banner_image_description: {
          1: { title: '' }
        },
        image: '',
        new: true,
        link: '',
      }
    },
    onBannerUpdateProduct() {
      this.displayAside = 'BannerHomePageUpdateProduct';
      this.bannerContentImage = {
        banner_product_description: {
          1: { title: '' }
        },
        new: true,
      }
    },
    onBannerUpdateDinamic() {
      this.displayAside = 'BannerHomePageUpdateDinamico';
      this.bannerContentImage = {
        new: true,
      }
    },
    onRemoveBanner(index) {
      const { configurations } = this;
      const bannerId = this.banners[index].banner_id;

      const { banners, carousels, mosaics } = configurations;

      const inUse = [...banners, ...carousels, ...mosaics].find(item => item.banner_id == bannerId);

      if (inUse) {
        const confirmed = window.confirm('Este banner contêm layouts em uso, deseja realmente excluir?');
        if (confirmed === false){
          return;
        }
      }

      for (const key in configurations) {
        configurations[key] = configurations[key].filter((item) => item.banner_id != bannerId);
      }

      this.configurations = configurations;
      this.excluded = [...this.excluded, bannerId]
      this.banners = this.onRemove(this.banners, index);
    },
    onRemove(list, index) {
      return list.filter((_, itemIndex) => itemIndex !== index);
    },
    onBannerAddItem(list, banner) {
      const { bannerContentImage } = this;
      bannerContentImage.new = Boolean(false);
      list.push(bannerContentImage);
      if (banner) {
        this.updateBannerOrder(banner);
      }
    },
    setBannerImage() {
      const { index, ...banner_content_image } = this.bannerContentImage;
      this.banners[this.bannerContent.index].banner_image[index] = banner_content_image;
    },
    setBannerLayout() {
      const { index, ...banner_content_layout } = this.bannerContentLayout;
      this.configurations[this.bannerContentLayout.style][index] = banner_content_layout;
    },
    onToggleSearchProduct() {
      this.openSearchProduct = !this.openSearchProduct;
    },
    onProductsSelected(productsSelected) {
      const { bannerContentImage } = this;
      bannerContentImage.banner_product_description[1].title = productsSelected.name;
      bannerContentImage.product_id = productsSelected.product_id;
      bannerContentImage.image = productsSelected.thumb;
      this.bannerContentImage = bannerContentImage;
    },
    onChangeTab(tabs) {
      this.bannerContentTab = tabs;
    },
    onChangeHomePageTab(tabs) {
      this.bannerHomePageTab = tabs;
    },
    onCloseFileManager({value, thumbnail}) {
      this.bannerContentImage.image = value;
      this.bannerContentImage.thumb = thumbnail;
    },
    onCloseFileManagerBannerHomePageImage({value, thumbnail}) {
      this.bannerContentImage.image = value;
      this.bannerContentImage.thumb = thumbnail;
    },
    onCloseFileManagerBannerHomePageImageResponsive({value, thumbnail}) {
      this.bannerContentImage.image_responsive = value;
      this.bannerContentImage.thumb_responsive = thumbnail;
    },
    onBannerUpdateLayout(item, oldIndex, oldStyle) {
      if (item) {
        this.bannerContentLayout = this.cloneObject(item);
        this.bannerContentLayout.oldIndex = oldIndex;
        this.bannerContentLayout.oldStyle = oldStyle;

        if (!this.bannerContentLayout.hasOwnProperty('category_id')){
          this.bannerContentLayout.category_id = "-1";
        }
        if (!this.bannerContentLayout.hasOwnProperty('show_in_subsequent_categories')){
          this.bannerContentLayout.show_in_subsequent_categories = Type_DsimDnao.Tp_Nao;
        }

      } else {
        this.bannerContentLayout = {
          banner_id: this.bannerContent.banner_id,
          new: true,
          first_module: true,
          category_id: "-1", //valor default aqui pq alguem nao sabia oq tava fazendo qnd crio essa tela
          show_in_subsequent_categories: Type_DsimDnao.Tp_Nao, //valor default aqui pq alguem nao sabia oq tava fazendo qnd crio essa tela
        }
      }
      this.displayAside = 'BannerUpdateLayout';
    },
    onClickBack(validate, type, successFunction) {
      validate()
        .then((valid) => {
          if (valid) {
            this.alert = {};
            if (typeof successFunction !== 'undefined') {
              successFunction();
            }
            this.bannerContentImage = {};
            this.bannerContentLayout = {};
            this.displayAside = type;
          } else {
            this.alert = { type: 'error', message: 'Verifique os campos novamente'};
          }
        });
    },
    updateBannerOrder(banner) {
      this.banner_home_page[banner] = this.banner_home_page[banner].map(
        (item, index) => {
          if (banner == 'banner_dinamico') {
            item.banner_dinamico_ordem = index;
          } else {
            item.banner_order = index;
          }
          return item;
        }
      )
    },
    updateBannerGroupOrder(banner) {
      // debugger;
      this.banner_home_page[banner] = this.banner_home_page[banner].map(
        (item, index) => {
          if (banner == 'banner_group') {
            item.order = index;
          }
          return item;
        }
      )
    },
    onClickCancel(type) {
      this.bannerContentImage = {};
      this.bannerContentLayout = {};
      this.displayAside = type;
    },
    cloneObject(item) {
      return JSON.parse(JSON.stringify(item));
    },
    onClickBackHome() {
      this.bannerContent = {};
      this.bannerContentImage = {};
      this.displayAside = 'BannerList';
    },
    onClickBackLayout(style) {
      const { bannerContentLayout, configurations } = this;
      const { oldIndex, oldStyle } = bannerContentLayout;
      const index = configurations[style].findIndex((item) => item.index === bannerContentLayout.oldIndex);

      delete bannerContentLayout.oldIndex;
      delete bannerContentLayout.oldStyle;

      bannerContentLayout.new = false;

      if (typeof oldStyle != 'undefined' && bannerContentLayout.style != oldStyle) {
        bannerContentLayout.first_module = true;
      }

      if (typeof oldStyle != 'undefined' && bannerContentLayout.style != oldStyle) {
        configurations[oldStyle].splice(oldIndex, 1);
      }

      if (index !== -1 ) {
        configurations[style][index] = bannerContentLayout;
      } else {
        configurations[style] = [...configurations[style], bannerContentLayout];
      }

      this.configurations = configurations;
      this.bannerContentLayout = {};
    },
    onRemoveBannerLayout(key, index) {
      this.configurations[key] = this.onRemove(this.configurations[key], index);
      this.bannerContentLayout = {};
      this.displayAside = 'bannerUpdate';
    },
    onSelectMosaic(mosaicType) {
      const { bannerContentLayout } = this;

      if (bannerContentLayout.mosaic_style) {
        bannerContentLayout.mosaic_style = mosaicType;
      } else {
        this.bannerContentLayout = {...bannerContentLayout, mosaic_style:mosaicType}
      }
    },
    selectReturn(selectedValue){
      this.bannerContentLayout.category_id = selectedValue;
    },
    formSuccess(data) {
      this.onClickBackHome();
    },
  }
});

initVue(vm);