import axios from 'axios';

export default {
  name: 'SearchProduct',
  components: {
    BaseButton: () => import(/* webpackChunkName: "BaseButton" */ '@elements/BaseButton/index.vue'),
    BaseModal: () => import(/* webpackChunkName: "BaseModal" */ '@components/BaseModal/index.vue'),
    SearchProductItem: () =>
      import(/* webpackChunkName: "SearchProductItem" */ '@components/SearchProduct/SearchProductItem/index.vue'),
    draggable: () => import(/* webpackChunkName: "draggable" */ 'vuedraggable'),
  },
  props: {
    open: {
      type: Boolean,
      default: false,
    },
    singleSelect: {
      type: Boolean,
      default: false,
    },
    productsAlreadySelected: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      loading: false,
      searchField: '',
      productsFound: [],
      productsSelected: [],
    };
  },
  watch: {
    open() {
      if (!this.singleSelect) {
        this.productsSelected = [...this.productsAlreadySelected];
      }
    },
  },
  computed: {
    products() {
      return this.productsFound.map(productFound => {
        const productFoundIsSelected = this.productsSelected.findIndex(
          productSelected => productSelected.product_id == productFound.product_id
        );
        productFound.selected = productFoundIsSelected != -1;
        return productFound;
      });
    },
    productsSelectedAmount() {
      return this.productsSelected.length;
    },
  },
  methods: {
    onClose() {
      if (window.confirm('As alterações não serão salvas. Você realmente quer sair?')) {
        this.productsFound = [];
        this.searchField = '';
        this.$emit('close');
      }
    },
    onSearchProducts() {
      const method = 'get';
      const url = 'index.php?route=catalog/product/autocomplete';
      const token = document.body.dataset.token;
      const value = this.searchField;
      const filter_name = value;

      this.loading = true;

      clearTimeout(this.delayTimerSearch);
      this.delayTimerSearch = setTimeout(() => {
        if (!filter_name) {
          this.productsFound = [];
          this.loading = false;
          return;
        }

        axios({
          method,
          url,
          params: {
            token,
            filter_name,
          },
        })
          .then(({ data }) => {
            if (data) {
              this.productsFound = data;
            }
          })
          .catch(() => {
            this.alert = {
              type: 'warning',
              message: 'Aconteceu algo de inesperado, por favor tente novamente!',
            };
          })
          .finally(() => {
            this.loading = false;
          });
      }, 1000);
    },
    onClearSearchField() {
      this.searchField = '';
      this.productsFound = [];
    },
    onClickProduct(clickedProduct, clickedProductIndex) {
      if (this.singleSelect) {
        this.$emit('products-selected', clickedProduct);
        this.productsFound = [];
        this.searchField = '';
        this.$emit('close');
        return;
      }

      const productIndex = this.productsSelected.findIndex(product => product.product_id == clickedProduct.product_id);
      if (productIndex != -1) {
        this.productsFound[clickedProductIndex].selected = false;
        this.productsSelected.splice(productIndex, 1);
      } else {
        this.productsFound[clickedProductIndex].selected = true;
        this.productsSelected = [...this.productsSelected, clickedProduct];
      }
    },
    onRemoveProduct(clickedProductIndex) {
      this.productsSelected.splice(clickedProductIndex, 1);
    },
    onApplyProductsSelected() {
      this.$emit('products-selected', this.productsSelected);
      this.productsFound = [];
      this.searchField = '';
      this.$emit('close');
    },
  },
};
