import axios from 'axios';

const typeSearch = {
  products:{
    url: 'index.php?route=catalog/product/autocomplete',
    caption: 'Produtos Selecionados',
    placeholder: 'Buscar Produtos',
  },
  customers: {
    url: 'index.php?route=sale/customer/autocomplete',
    caption: 'Clientes Selecionados',
    placeholder: 'Buscar Clientes',
  },
  addresses: {
    url: 'index.php?route=sale/customer/autocompleteAddress',
    caption: 'Endereços Selecionados',
    placeholder: 'Buscar Endereços',
  },
};
export default {
  name: 'TheSearch',
  components: {
    BaseButton: () => import(/* webpackChunkName: "BaseButton" */ '@elements/BaseButton/index.vue'),
    BaseModal: () => import(/* webpackChunkName: "BaseModal" */ '@components/BaseModal/index.vue'),
    SearchItem: () =>
      import(/* webpackChunkName: "SearchItem" */ '@components/TheSearch/SearchItem/index.vue'),
    draggable: () => import(/* webpackChunkName: "draggable" */ 'vuedraggable'),
  },
  props: {
    open: {
      type: Boolean,
      default: false,
    },
    singleSelect: {
      type: Boolean,
      default: false,
    },
    searchOnOpen: {
      type: Boolean,
      default: false,
    },
    itemsAlreadySelected: {
      type: Array,
      default: () => [],
    },
    typeSearch:{
      type: String,
      default: 'products',
      validator(value) {
        return ['products', 'customers', 'addresses'].indexOf(value) !== -1;
      },
    },
    aditionalParam: {
      type: Number | String,
      default: ''
    },
  },
  data() {
    return {
      loading: false,
      searchField: '',
      itemsFound: [],
      itemsSelected: [],
      searchPlaceholder: '',
      searchCaption: '',
    };
  },
  watch: {
    open() {
      if(this.searchOnOpen){
        this.onSearchItems();
      }

      if (!this.singleSelect) {
        this.itemsSelected = [...this.itemsAlreadySelected];
      }

      this.searchCaption = this.getSearchCaption;
      this.searchPlaceholder = this.getSearchPlaceholder;
    },
  },
  computed: {
    items() {
      return this.itemsFound.map(itemFound => {
        const itemFoundIsSelected = this.itemsSelected.findIndex(
          itemSelected => itemSelected.id == itemFound.id
        );
        itemFound.selected = itemFoundIsSelected != -1;
        return itemFound;
      });
    },
    itemsSelectedAmount() {
      return this.itemsSelected.length;
    },
    url(){
      return typeSearch[this.typeSearch].url;
    },
    getSearchCaption(){
      return typeSearch[this.typeSearch].caption;
    },
    getSearchPlaceholder(){
      return typeSearch[this.typeSearch].placeholder;
    },
  },
  methods: {
    onClose() {
      if (window.confirm('As alterações não serão salvas. Você realmente quer sair?')) {
        this.itemsFound = [];
        this.searchField = '';
        this.$emit('close');
      }
    },
    onSearchItems() {
      const method = 'get';
      const token = document.body.dataset.token;
      const value = this.searchField;
      const filter_name = value;
      const aditional_param = this.aditionalParam;

      let params = {};
      if(aditional_param){
        params = {
          token,
          filter_name,
          aditional_param
        };
      } else {
        params = {
          token,
          filter_name,
        };
      }

      this.loading = true;

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

        axios({
          method,
          url:this.url,
          params: params,
        })
        .then(({ data }) => {
          if (data) {
            const parseFunction = {
              'products': this.parseProducts(data),
              'customers': this.parseCustomers(data),
              'addresses': this.parseAddresses(data),
            };

            const registers = parseFunction[this.typeSearch];
            if(registers){
              this.itemsFound = registers;
            }
          }
        })
        .catch(() => {
          this.alert = {
            type: 'warning',
            message: 'Aconteceu algo de inesperado, por favor tente novamente!',
          };
        })
        .finally(() => {
          this.loading = false;
        });
      }, 1000);
    },
    parseProducts(data){
      return data.map(item => ({
        id: item.product_id,
        description: item.name,
        thumb: item.thumb,
        info: item,
      }));
    },
    parseCustomers(data){
      return data.map(item => ({
        id: item.customer_id,
        description: item.name,
        thumb: '',
        info: item,
      }));
    },
    parseAddresses(data){
      return data.map(item => ({
        id: item.address_id,
        description: item.apelido ?
                     (item.apelido + " - " + item.address_1 + ", " + item.numero + ", " + item.address_2) :
                     (item.address_1 + ", " + item.numero + ", " + item.address_2) ,
        secondDescription: item.city + ", " + item.zone_code + " - CEP: " + item.postcode,
        thumb: '',
        info: item,
      }));
    },
    onClearSearchField() {
      this.searchField = '';
      this.itemsFound = [];
    },
    onClickItem(clickedItem, clickedItemIndex) {
      if (this.singleSelect) {
        if (window.confirm('As informações serão salvas. Você realmente quer selecionar este registro?')){
          this.$emit('items-selected', clickedItem);
          this.itemsFound = [];
          this.searchField = '';
          this.$emit('close');
          return;
        }
      } else {
        const itemIndex = this.itemsSelected.findIndex(item => item.id == clickedItem.id);
        if (itemIndex != -1) {
          this.itemsFound[clickedItemIndex].selected = false;
          this.itemsSelected.splice(itemIndex, 1);
        } else {
          this.itemsFound[clickedItemIndex].selected = true;
          this.itemsSelected = [...this.itemsSelected, clickedItem];
        }
      }
    },
    onRemoveItem(clickedItemIndex) {
      this.itemsSelected.splice(clickedItemIndex, 1);
    },
    onApplyItemsSelected() {
      this.$emit('items-selected', this.itemsSelected);
      this.itemsFound = [];
      this.searchField = '';
      this.$emit('close');
    },
  },
};
