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 ScriptSearchProduct from '@components/SearchProduct/scripts.js';
import SearchProduct from '@components/SearchProduct/index.vue';
import { ValidationObserver, ValidationProvider } from 'vee-validate';
import {v4 as uuidv4} from "uuid";
import formMixin from '@mixins/formMixin';
import axios from "axios";


export default {
  name: 'ProductsBannerHomePage',
  components: {
    BaseCheckbox: () => import(/* webpackChunkName: "BaseCheckbox" */ '@elements/BaseCheckbox/index.vue'),
    BaseVueToggles: () => import(/* webpackChunkName: "BaseVueToggles" */ '@elements/BaseVueToggles/index.vue'),
    BaseCard,
    ValidationObserver,
    ValidationProvider,
    BaseInput: () => import(/* webpackChunkName: "BaseInput" */ '@elements/BaseInput/index.vue'),
    ScriptSearchProduct,
    BaseSelect,
    SearchProduct,
    BaseButton,
  },
  mixins: [formMixin],
  props: {},
  data() {
    return {
      analyze: '',
      analyze_id: 0,
      quantity: 0,
      banner_group_order: 0,
      banner_order: 0,
      new: false,
      thumb: '',
      open: false,
      title: '',
      loading: false,
      searchField: '',
      productsFound: [],
      productsSelected: [],
      Type_ModelBannerProduct: DATA.Type_ModelBannerProduct,
      isActived: false,
      description: '',
      codeProduct: '',
      bannerType: '',
      date_end: '',
      date_initial: '',
      productMetadata: [],
      openModalSearchProduct: false,
    };
  },
  methods: {
    formartDate(date) {
      const day = ('0' + date.getDate()).slice(-2);
      const month = ('0' + (date.getMonth() + 1)).slice(-2);
      const year = date.getFullYear();

      return day + '/' + month + '/' + year;
    },
    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));
    },
    onToggleSearchProduct(){
      this.open = false;
    },
    onProductsSelected(product){
      this.title = product.name;
      this.productsInformationSettings.image = product.image;
      this.productsInformationSettings.product_id = product.product_id;
      this.thumb = product.thumb_large;
    },
    getAllSettingsDataProduct() {
      DATA.banner_extensions.banner_homepage.banner_product.map(data => {
        if(store.state.product_id === data.analyze_id) {
          this.analyze = data.analyze;
          this.analyze_id = data.analyze_id;
          this.productsInformationSettings.banner_model = data.banner_model;
          this.quantity = data.quantity;
          this.banner_group_order = data.banner_group_order;
          this.banner_order = data.banner_order;
          this.new - data.new;
          this.thumb = data.thumb;
          this.title = data.banner_product_description['1'].title
          this.date_initial = data.date_initial;
          this.date_end = data.date_end;
        }
      })
    },

    descriptionFunc() {
      let productBanner = [];

      let objectCloneWithInsertNewData = {
        analyze:    this.analyze,
        analyze_id: this.analyze_id,
        quantity: this.quantity,
        banner_group_order: this.banner_group_order,
        banner_model: this.productsInformationSettings.banner_model,
        banner_order: this.banner_order,
        banner_product_description: { 1: { title: this.title } },
        date_end: this.date_end,
        date_initial: this.date_initial,
        image: this.productsInformationSettings.image,
        new: this.new,
        product_id: this.productsInformationSettings.product_id,
        thumb: this.thumb,
      };

      store.state.jsonBannersMounted.banner_product.map((value) => {
        if(value.analyze_id === store.state.product_id){
          productBanner.push(objectCloneWithInsertNewData);
        }else{
          productBanner.push(value);
        }
      });

      DATA.banner_extensions.banner_homepage.banner_product = productBanner;
      store.state.jsonBannersMounted.banner_product = productBanner;
      this.addCookies(productBanner);
    },

    openSearchProductsModal(screenName) {
      store.commit('openUpdateSettings', screenName);
    },

    closeSearchProductsModal() {
      this.openModalSearchProduct = false;
    },

    activeAdvancedOptions() {
      this.isActived = true;
    },

    setBannerProductDescription() {
      if (store.state.flagCreateNewProduct === 'create') {
        const analyze_id_provider = uuidv4();

        this.analyze_id = analyze_id_provider;
        this.analyze = 'true';

        let objectEmptyWithInsertNewData = {
          analyze: true,
          analyze_id: analyze_id_provider,
          quantity: '0',
          banner_group_order: '0',
          banner_model: 'model-1',
          banner_order: 0,
          banner_product_description: {
            1: {
              title: 'Clique para encontrar o produto que deseja',
            },
          },
          date_end: '',
          date_initial: '',
          image: '../image/data/preview-product.png',
          new: '',
          product_id: '',
          thumb: '',
        };
        store.commit('setAllProductsFound', objectEmptyWithInsertNewData);
      } else {
        DATA.banner_extensions.banner_homepage.banner_product.map(productInformation => {
          if (productInformation.analyze_id === store.state.product_id) {

            let objectCloneWithInsertNewData = {
              analyze: productInformation.analyze,
              analyze_id: productInformation.analyze_id,
              quantity: productInformation.quantity,
              banner_group_order: productInformation.banner_group_order,
              banner_model: productInformation.banner_model,
              banner_order: 0,
              banner_product_description: { 1: { title: productInformation.banner_product_description['1'].title } },
              date_end: productInformation.date_end,
              date_initial: productInformation.date_initial,
              image: productInformation.image,
              new: productInformation.new,
              product_id: productInformation.product_id,
              thumb: productInformation.image,
            };

            store.commit('setAllProductsFound', objectCloneWithInsertNewData);
          }
        });

        Object.keys(DATA.Type_ModelBannerProduct).map((bannerProductModelKeys) => {
          if (this.productsInformationSettings.banner_model === bannerProductModelKeys) {
            this.productsInformationSettings.banner_model = bannerProductModelKeys;
          }
        });
      }
    },
    addModifications(){
      const getInputValue = document.querySelector('.get-value');
      const getProductCodeValue = document.querySelector('.get-code-value');
      const getimageSourceValue = document.querySelector('.img-link-value');

      if(store.state.flagCreateNewProduct === 'create') {
        let objectProduct = {
          analyze: this.analyze,
          analyze_id: this.analyze_id,
          quantity: this.quantity,
          banner_group_order: this.banner_order,
          banner_model: this.productsInformationSettings.banner_model,
          banner_order: this.banner_order,
          banner_product_description: { 1: { title: this.title } },
          date_end: this.date_end,
          date_initial: this.date_initial,
          image: this.productsInformationSettings.image,
          new: this.new,
          product_id: this.productsInformationSettings.product_id,
          thumb: this.thumb,
        };
        DATA.banner_extensions.banner_homepage.banner_product.push(objectProduct);
      } else {
        DATA.banner_extensions.banner_homepage.banner_product.map(data => {
          if(store.state.product_id === data.analyze_id) {
            data.banner_product_description['1'].title = this.title;
            data.product_id = this.productsInformationSettings.product_id;
            data.banner_model = this.productsInformationSettings.banner_model,
              data.image = this.productsInformationSettings.image;
            data.thumb = this.thumb;
            data.date_end = this.date_end;
            data.new = this.new;
            data.date_initial = this.date_initial;
          }
        })
      }
      store.commit('openUpdateSettings', 'HomePage');

      this.descriptionFunc();
    },

    addCookies(values){
      this.setCookiesAxios({produto: 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'));
    },
    insertNewProductInBannerHomePage() {
      this.$refs.validationObserver.validate().then(valid => {
        if (valid) {
          this.addModifications();
        }else{
          notificationMsg(this.getLanguage('text_error_validate'),'error');
        }
      });
    },

    onClickBackToHomePage(screenName) {
      store.commit('setScreenName', screenName);
    },
    getLanguage(label){
      return store.state.language[label];
    },
  },

  computed: {
    stateTela(){
      return store.state.screenName
    },
    productsInformationSettings() {
      return store.state.productSelectedWithSearch;
    },
  },
  mounted() {
    this.setBannerProductDescription();
    this.getAllSettingsDataProduct();
  },
};
