import BaseCard from '@elements/BaseCard/index.vue';
import BaseSelect from '@elements/BaseSelect/index.vue';
import BaseButton from '@elements/BaseButton/index.vue';
import ImagesBannerHomePage from './index.vue';
import FileManager from '@components/FileManager/index.vue';
import store from '../../../GlobalContextStore/GlobalContexts';
import { ValidationObserver, ValidationProvider } from 'vee-validate';
import { v4 as uuidv4 } from 'uuid';
import formMixin from '@mixins/formMixin';
import axios from "axios";

export default {
  name: 'ImagesBannerHomePage',
  components: {
    BaseVueToggles: () => import(/* webpackChunkName: "BaseVueToggles" */ '@elements/BaseVueToggles/index.vue'),
    ImagesBannerHomePage,
    BaseButton,
    BaseSelect,
    ValidationObserver,
    ValidationProvider,
    BaseCard,
    BaseInput: () => import(/* webpackChunkName: "BaseInput" */ '@elements/BaseInput/index.vue'),
    FileManager,
  },
  mixins: [formMixin],
  data() {
    return {
      title: '',
      notImage: '../image/data/preview-product.png',
      openResp: false,
      open: false,
      imageSelected: '',
      imagePathUrl: '',
      setBannerSettingsImages: 'BannersSettingImages',
      Type_OpenLink: DATA.Type_OpenLink,
      imagesInterfacePreRender: [],
      bannerImageModule: [],
      bannerImageSupportModule: [],
      imageFullScreen: store.state.imageThumb,
      flagMethod: store.state.defineFlagMethod,
      link: '',
      banner_image_home_page: [
        {
          analyze: '',
          quantity: '',
          banner_group_order: '',
          banner_image_description: [
            {
              title: '',
            },
          ],
          banner_order: '',
          date_end: '',
          date_initial: '',
          image: '',
          image_responsive: '',
          link: '',
          new: '',
          target: '',
          thumb: '',
          thumb_responsive: '',
        },
      ],
      thumbResponsive: '',
      thumbLargeImage: '',
      titleBannerImage: '',
      analyze: '0',
      quantity: '0',
      image: '',
      image_responsive: '',
      banner_order: 0,
      target: '',
      analyze_id: '',
      analyze_id_banner_db: '',
      newData: 'false',
      date_initial: '',
      thumb: '',
      thumb_responsive: '',
      date_end: '',
      newBannerImageDataState: {},
      no_image: 'https://bb8.futurasistemas.com.br:9403/repl3/image/cache/no_image-40x40.jpg',
    };
  },

  methods: {
    setImageSelect() {
      this.imageSelected = store.state.imageLarge;
    },

    setBannerImageType(typeImage) {
      store.commit('setTypeImage', typeImage);
    },

    onClickOpenGalleryImage(galleryImageName) {
      store.commit('setScreenName', galleryImageName);
    },

    onClickBackToHomePage(screenName) {
      this.clearInfo();
      store.commit('setScreenName', screenName);
    },

    handleSetBannerImage(title) {
      this.titleBannerImage = title;
    },

    handleSetLinkImage(link) {
      this.link = link;
    },

    handleSetTarget(target) {
      this.target = target;
    },

    handleSetInitialDate(date_initial) {
      this.date_initial = date_initial;
    },

    handleSetFinalDate(date_end) {
      this.date_end = date_end;
    },

    getImagesBannerData() {
      DATA.banner_extensions.banner_homepage.banner_image.map((dataBannerImage) => {
        if (store.state.banner_analyzeId === dataBannerImage.analyze_id) {
          this.thumb = dataBannerImage.thumb;
          this.image = dataBannerImage.image;
          store.commit('setThumbImageLarge', dataBannerImage.thumb);
          this.thumbResponsive = dataBannerImage.thumb_responsive;
          this.image_responsive = dataBannerImage.image_responsive;

        }
      })

      store.state.banner_image_indexform.map(bannerImageData => {
        bannerImageData.map(findBannerImageByAnalyzeId => {
          if (store.state.banner_analyzeId === findBannerImageByAnalyzeId.analyze_id) {
            this.banner_image_home_page.map(imageBannerData => {
              imageBannerData.banner_image_description[0].title = findBannerImageByAnalyzeId.banner_image_description[1].title;
              imageBannerData.analyze = findBannerImageByAnalyzeId.analyze;
              this.analyze = findBannerImageByAnalyzeId.analyze;
              imageBannerData.analyze_id = findBannerImageByAnalyzeId.analyze_id;
              imageBannerData.quantity = findBannerImageByAnalyzeId.quantity;
              imageBannerData.banner_order = findBannerImageByAnalyzeId.banner_order;
              imageBannerData.date_end = findBannerImageByAnalyzeId.date_end;
              imageBannerData.date_initial = findBannerImageByAnalyzeId.date_initial;
              imageBannerData.image = findBannerImageByAnalyzeId.image;
              imageBannerData.image_responsive = findBannerImageByAnalyzeId.image_responsive;
              imageBannerData.link = findBannerImageByAnalyzeId.link;
              imageBannerData.new = findBannerImageByAnalyzeId.new;
              imageBannerData.target = findBannerImageByAnalyzeId.target;

              let bannerThumb = findBannerImageByAnalyzeId.thumb.replace('/cache', '');
              let thumbFiltred = bannerThumb.replace('-40x40', '');

              let bannerThumb_responsive = findBannerImageByAnalyzeId.thumb_responsive.replace('/cache', '');
              let thumbFiltred_responsive = bannerThumb_responsive.replace('-80x80', '');

              //Commit responsive image
              imageBannerData.thumb_responsive = thumbFiltred_responsive;

              store.commit('setThumbImageResponsive', thumbFiltred_responsive);
              store.commit('setAnalyzeIdIntoBannerImage', findBannerImageByAnalyzeId.analyze_id);

            });
          }
        });
      });
      this.thumbLargeImage = store.state.imageLarge;
    },
    clearInfo(){
      store.state.banner_analyzeId = '';
      store.state.imageLarge = '';
      this.openResp = false;
      this.open = false;
      this.imageSelected = '';
      this.imagePathUrl = '';
      this.setBannerSettingsImages = 'BannersSettingImages';
      this.Type_OpenLink = DATA.Type_OpenLink;
      this.imagesInterfacePreRender = [];
      this.bannerImageModule = [];
      this.bannerImageSupportModule = [];
      this.imageFullScreen = store.state.imageThumb;
      this.flagMethod = store.state.defineFlagMethod;
      this.link = '';
      this.thumbResponsive = '';
      this.thumbLargeImage = '';
      this.titleBannerImage = '';
      this.analyze = '1';
      this.quantity = '0';
      this.image = '';
      this.image_responsive = '';
      this.banner_order = 0;
      this.target = '';
      this.analyze_id = '';
      this.analyze_id_banner_db = '';
      this.newData = 'false';
      this.date_initial = '';
      this.thumb = '';
      this.thumb_responsive = '';
      this.date_end = '';
      this.newBannerImageDataState = {};
      this.no_image = '';
      this.banner_image_home_page = [
        {
          analyze: '',
          quantity: '',
          banner_group_order: '',
          banner_image_description: [
            {
              title: '',
            },
          ],
          banner_order: '',
          date_end: '',
          date_initial: '',
          image: '',
          image_responsive: '',
          link: '',
          new: '',
          target: '',
          thumb: '',
          thumb_responsive: '',
        },
      ]
    },
    addModifications(){

      if (store.state.defineFlagMethod === 'create') {
        this.addNewBannerImage();
      } else {


        DATA.banner_extensions.banner_homepage.banner_image.map((searchBannerImageByAnalyzeId, index) => {
          if (searchBannerImageByAnalyzeId.analyze_id === store.state.banner_analyzeId) {
            this.newBannerImageDataState = {
              analyze:                    this.analyze,
              analyze_id:                 searchBannerImageByAnalyzeId.analyze_id,
              quantity:                   searchBannerImageByAnalyzeId.quantity,
              new:                        searchBannerImageByAnalyzeId.new,
              banner_group_order:         searchBannerImageByAnalyzeId.banner_group_order,
              banner_order:               searchBannerImageByAnalyzeId.banner_order,
              banner_image_description:   { '1': { title: this.titleBannerImage } },
              link:                       this.link,
              target:                     this.target,
              image:                      this.image,
              image_responsive:           this.image_responsive,
              date_initial:               this.date_initial,
              thumb:                      this.thumbLargeImage,
              thumb_responsive:           this.thumbResponsive,
              date_end:                   this.date_end,
            };
          }
        });

        this.setStoreImgBanner(store.state.banner_analyzeId );
        this.clearInfo();
        store.commit('setScreenName', 'HomePage');
      }
    },
    addCookies(values){
      this.setCookiesAxios({imagem:JSON.stringify(values)})
    },
    setCookiesAxios($object){
      axios({
        headers: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method: 'post',
        url: DATA.cached,
        data: window.objectToParam($object),
      })
        .then((response) => {
        })
        .catch(()=>console.log('erro'));
    },
    setTypeUseWithFlagDetails() {
      this.$refs.validationObserver.validate().then(valid => {
        if (valid) {
          this.addModifications();
        }else{
          notificationMsg(this.getLanguage('text_error_validate'),'error');
        }
      });
    },
    setStoreImgBanner(idBanner){
      let imgBanner = [];
      store.state.jsonBannersMounted.banner_image.map((value) => {
          if(value.analyze_id === idBanner){
            let valueInfo = {
              analyze:                    this.analyze,
              analyze_id:                 value.analyze_id,
              quantity:                   value.quantity,
              new:                        false,
              banner_group_order:         (this.banner_group_order)? this.banner_group_order: value.banner_group_order,
              banner_order:               this.banner_order,
              banner_image_description:   { '1': { title: (this.titleBannerImage)? this.titleBannerImage : value.banner_image_description[1].title } },
              link:                       (this.link) ? this.link: value.link,
              target:                     (this.target) ? this.target: value.target,
              image:                      (this.image) ? this.image: value.image,
              image_responsive:           (this.image_responsive) ? this.image_responsive: value.image_responsive,
              date_initial:               (this.date_initial) ? this.date_initial: value.date_initial,
              thumb:                      (this.thumbLargeImage) ? this.thumbLargeImage: value.thumbLargeImage,
              thumb_responsive:           (this.thumbResponsive)? this.thumbResponsive: value.thumb_responsive,
              date_end:                   (this.date_end)? this.date_end: value.date_end
            };
            imgBanner.push(valueInfo);
          }else{
            imgBanner.push(value);
          }
        }
      );

      DATA.banner_extensions.banner_homepage.banner_image = imgBanner;
      store.state.jsonBannersMounted.banner_image = imgBanner;

      this.addCookies(imgBanner);
    },
    addNewBannerImage() {

      const analyze_id_provider = uuidv4();
      this.analyze_id = analyze_id_provider;

      store.commit('defineUUIDv4WithAnalyzeId', analyze_id_provider);

      const newBannerImageData = {
        new: this.newData,
        analyze_id: analyze_id_provider,
        banner_order: this.banner_order,
        analyze: this.analyze,
        quantity: this.quantity,
        banner_image_description: {
          '1': {
            title: this.titleBannerImage,
          },
        },
        link: this.link,
        target: this.target? this.target: "_blank",
        image: this.image,
        thumb: this.thumbLargeImage,
        image_responsive: this.image_responsive,
        thumb_responsive: this.thumbResponsive,
        date_initial: this.date_initial,
        date_end: this.date_end,
      };

      DATA.banner_extensions.banner_homepage.banner_image.push(newBannerImageData);
      store.state.jsonBannersMounted.banner_image = DATA.banner_extensions.banner_homepage.banner_image;
      this.addCookies(DATA.banner_extensions.banner_homepage.banner_image);

      store.commit('setScreenName', 'HomePage');
    },

    savePage() {
      store.commit('setBannerSettingsImagesUse', 'setBannerSettingsImagesUse');
    },

    getLanguage(label){
      return store.state.language[label];
    },
    onFinalDate(value) {
      if (value.length > 9) {
        const [day, month, year] = value.split('/');
        const date = new Date(year + '-' + month + '-' + (day)+'T21:00:00');
        const finalDate = new Date();
        if(date < finalDate) {
          notificationMsg(this.getLanguage('error_dataMax'), 'warning');
        }
      }
    },
    disabledFinalDate(date) {
      const disabledFinalDate = new Date(date.getTime() + 0 * 24 * 3600 * 1000);
      return disabledFinalDate < new Date(new Date().setHours(0, 0, 0, 0));
    },

    onSelectedFile({ filename, thumbnail , thumbnail_large}) {

      const link = [];
      link['icon'] = filename;
      link['iconPreview'] = thumbnail_large;
      this.thumbLargeImage = thumbnail_large;

      this.image = thumbnail.substr(thumbnail.indexOf('data/'),thumbnail.lastIndexOf("/") - (thumbnail.indexOf('data/')));
      this.image = this.image +'/'+filename;

    },

    onSelectedIcon(icon) {
      const link = [];
      link['icon'] = icon;
      link['iconPreview'] = icon;
    },
    onSelectedFileResp({ filename, thumbnail , thumbnail_large}) {

      const link = [];
      link['icon'] = filename;
      link['iconPreview'] = thumbnail_large;

      this.thumbResponsive = thumbnail_large;

      this.image_responsive = thumbnail.substr(thumbnail.indexOf('data/'),thumbnail.lastIndexOf("/") - (thumbnail.indexOf('data/')));
      this.image_responsive = this.image_responsive +'/'+filename;

    },

    onSelectedIconResp(icon) {
      const link = [];
      link['icon'] = icon;
      link['iconPreview'] = icon;
    },
    carregaInfo(){
      this.titleBannerImage = this.banner_image_home_page[0].banner_image_description[0].title;
      this.link = this.banner_image_home_page[0].link;
      this.quantity = this.banner_image_home_page[0].quantity;
      this.target = this.banner_image_home_page[0].target;
      this.date_initial = this.banner_image_home_page[0].date_initial;
      this.date_end = this.banner_image_home_page[0].date_end;
      this.analyze = this.banner_image_home_page[0].analyze;

      if(!this.target){
        this.target = '_self';
      }
      if(!this.thumbLargeImage){
        this.thumbLargeImage = '../image/data/preview-product.png';
      }
      if(!this.image){
        this.image = 'data/preview-product.png';
      }
      if(!this.image_responsive){
        this.image_responsive = 'data/preview-product.png';
      }

    }


  },

  mounted() {

    this.getImagesBannerData();
    this.carregaInfo();
  },

  computed: {
    getAnalyze_id_banner_db() {
      return store.state.analyze_id_banner_image;
    },

  },
};
