import store from '../../GlobalContextStore/GlobalContexts';
import BaseSelect from '@elements/BaseSelect/index.vue';
import BaseButton from '@elements/BaseButton/index.vue';
import BaseCard from '@elements/BaseCard/index.vue';
import SecundaryBannerComponents from './index.vue';
import { v4 as uuidv4, validate } from 'uuid';
import formMixin from '@mixins/formMixin';

export default {
  name: 'SecundaryBannerComponents',
  components: {
    BaseButton,
    BaseSelect,
    SecundaryBannerComponents,
    BaseCard,
    BaseVueToggles: () => import(/* webpackChunkName: "BaseVueToggles" */ '@elements/BaseVueToggles/index.vue'),
    BaseInput: () => import(/* webpackChunkName: "BaseInput" */ '@elements/BaseInput/index.vue'),
    BaseModal: () => import(/* webpackChunkName: "BaseModal" */ '@components/BaseModal/index.vue'),
  },
  mixins: [formMixin],
  data() {
    return {
      excludedUUID: '',
      showModal: false,
      isEdit: [],
      isExcluded: false,
      openSuccessBox: false,
      arrayAllBannersData: [],
      layoutArrayOfCarousels: [],
      clearArrayOfCarousels: [],
      layoutArrayOfBanner: [],
      layoutArrayOfMosaic: [],
      newBannerRootData: [],
      bannerObject: [],
      bannerVerified: 0,
      bannerLayoutKey: 0,
      newBannerName: this.getLanguage('text_new_banner'),
      setUndefined: '',
      activeClass: 0,
      handleEditBannerName: '',
      bannerName: '',
      messageErrorInLine: this.getLanguage('text_error_name'),
      scrollTop: 0,
      setBannerListLayout: store.state.banners,
    };
  },

  methods: {
    onClose(){
      this.showModal = false;
    },
    onOpen(banner_UUID){
      this.showModal = true;
      this.excludedUUID = banner_UUID;
    },
    isEmpty(strValue) {
      if (!strValue.length) {
        return false;
      }
      return true;
    },
    removeObjectWithId(arr, id) {
      const objWithIdIndex = arr.findIndex(obj => obj.id === id);

      if (objWithIdIndex > -1) {
        arr.splice(objWithIdIndex, 1);
      }

      return arr;
    },

    getNewBannerName(banner_name) {
      DATA.banners.map((findBannerById, __) => {
        if (store.state.bannerId === findBannerById.banner_id) {
          findBannerById.name = banner_name;
          this.bannerName = findBannerById.name;
        }
      });
    },

    removeBannerWithIndex(banner_UUID) {
      DATA.banners = DATA.banners.filter((banner)=> banner.banner_id !== banner_UUID );
      store.state.jsonBannersMounted.banner = DATA.banners;
      store.state.jsonBannersMounted.excluded.push(banner_UUID);

      let condBanners = DATA.banners.filter((banner)=> banner.banner_id === store.state.bannerId);
      if(!condBanners.length){
        store.state.setCarrosselLayoutName = [];
        store.state.setBannerLayoutName    = [];
        store.state.setMosaicLayoutName    = [];
        store.state.bannerId = 0;
      }

      this.isExcluded = true;
      this.addCookies(false);
    },

    selecrDefaultBannerSelected() {

      if (!store.state.bannerId) {
        if(store.state.jsonBannersMounted.banner[0] !== undefined){
          this.bannerSelectedById(store.state.jsonBannersMounted.banner[0].banner_id);
        }
      }

      this.bannerVerified = String(store.state.bannerId);
      this.activeClass = String(store.state.bannerId);
    },
    focusInput(index){
     this.$refs[index][0].inputFocus();
    },
    bannerSelectedById(banner_id) {

      if(this.isExcluded){
        this.isExcluded = false;
        return 0;
      }

      if (!banner_id) {

        this.insertNewBannerWithSubModules();
        this.openSuccessBox = true;
      }

      if (banner_id) {

        store.state.bannerId = banner_id;
        this.bannerVerified = String(banner_id);
        this.activeClass = String(banner_id);

        store.state.setCarrosselLayoutName = [];
        store.state.setBannerLayoutName    = [];
        store.state.setMosaicLayoutName    = [];
        const subModules = ['banners', 'carousels', 'mosaics'];

        DATA.banner_extensions.banners_secundaries.map(bannersCategories => {
          if (bannersCategories.banner_id === store.state.bannerId) {

            store.state.nameSecundarySub = bannersCategories.name? bannersCategories.name : '';
            store.state.StatusSecindaryBanner =  bannersCategories.status;

            Object.keys(bannersCategories).map(categoriesCallBack => {
              if (subModules.includes(categoriesCallBack)) {
                bannersCategories[String(categoriesCallBack)].map(bannersSubModulesCallBack => {
                  if (
                    store.state.bannerId == banner_id &&
                    bannersSubModulesCallBack.banner_id == store.state.bannerId
                  ) {
                    DATA.layouts.map(searchLayoutById => {
                      if (bannersSubModulesCallBack.layout_id === searchLayoutById.layout_id) {
                        switch (categoriesCallBack) {
                          case 'banners':
                            store.state.setBannerLayoutName.push({ searchLayoutById, bannersSubModulesCallBack });
                            break;
                          case 'carousels':
                            store.state.setCarrosselLayoutName.push({ searchLayoutById, bannersSubModulesCallBack });
                            break;
                          case 'mosaics':
                            store.state.setMosaicLayoutName.push({ searchLayoutById, bannersSubModulesCallBack });
                            break;
                          default:
                            break;
                        }
                        store.commit('setScreenName', 'HomePage');
                      }
                    });
                  }
                });
              }
            });
          }
        });

        store.state.imageThumb = DATA.banners.filter((bannersimg) => bannersimg.banner_id === banner_id);

        let bannerSelected = Object.keys(store.state.imageThumb[0]).some(name => name === 'banner_image');
        if(!bannerSelected || store.state.imageThumb[0].banner_image.length === 0){
          store.state.imageThumb[0].banner_image = this.bannerNew();
        }

        store.state.imageThumb = store.state.imageThumb[0].banner_image? store.state.imageThumb[0].banner_image: store.state.imageThumb;

      }
    },
    addCookies(boll){
      if(boll !== true){
        document.cookie = "secondary="+JSON.stringify(DATA.banner_extensions.banners_secundaries)+" ";
        document.cookie = "secondaryImages="+JSON.stringify(DATA.banners)+" ";
      }
    },
    insertNewBannerWithSubModules() {
      const dataIdRelationship = uuidv4();
      store.state.bannerId = dataIdRelationship;

      if (validate(dataIdRelationship)) {
        DATA.banner_extensions.banners_secundaries.push({
          banner_id: dataIdRelationship,
          UUID: dataIdRelationship,
          banners: [],
          carousels: [],
          mosaics: [],
          name: '',
          status: '1',
        });

        this.newBannerWithBufferCacheClean = [
          {
            banner_id: dataIdRelationship,
            UUID: dataIdRelationship,
            isEdit: false,
            banner_image: [],
            name: '',
            status: '1',
          },
        ];

        this.newBannerWithBufferCacheClean.map(newBannerForInsertIntoDashBoardCallback => {
          DATA.banners.push(newBannerForInsertIntoDashBoardCallback);
        });

        store.commit('insertNewBannerData', this.newBannerWithBufferCacheClean);

        this.bannerVerified = String(dataIdRelationship);
        this.activeClass = String(dataIdRelationship);
      }
    },
    getLanguage(label){
      return store.state.language[label];
    },
    keyPress(e,banner){
      if(['Enter','NumpadEnter'].indexOf(e.code) > -1){
        banner.isEdit = !banner.isEdit;
      }
    },
    editBannerSecundari(index, id){
      if(!this.isEdit[index]){
        this.isEdit.map((info, index) => this.isEdit[index] = false);
        this.isEdit[index] = true;
        this.bannerSelectedById(id);
      }else{
        this.isEdit[index] = false;
        this.bannerSelectedById(id);
      }
    },
    bannerNew(){
      let bannerValue = [];
      for(let count = 0; count < 6 ; count++){
        bannerValue.push({
          banner_image_description: {
            1:{title: 'Novo banner'}
          },
          image: 'data/preview-product.png',
          link:  '',
          thumb: '../image/data/preview-product.png'
        })
      }
      return bannerValue;
    },
  },
  computed: {

    setEnableAndDisable() {
      return store.state.enableAndDisable === true ? 'Habilitado' : 'Desabilitado';
    },
    getStoreBanners(){
      return store.state.jsonBannersMounted.banner;
    }
  },

  watch: {
    bannerName(newName) {
      DATA.banners.map((findBannerById, __) => {
        if (store.state.bannerId === findBannerById.banner_id) {
          findBannerById.name = newName;
          this.bannerName = findBannerById.name;
        }
      });
    },

    setEnableAndDisable() {
      return store.state.enableAndDisable === true ? 'Habilitado' : 'Desabilitado';
    },

    setBannerListLayout(newVal) {
      return newVal;
    },
  },

  mounted() {
    this.selecrDefaultBannerSelected();
  },
};
