<template>
  <SettingsItem :label="label">
    <template #default>
      <input
        ref="productsInput"
        type="text"
        placeholder="Начните вводить название товара..."
        class="form-control"
        autocomplete="off"
      />
      <div class="well well-sm tw:h-90 tw:overflow-auto">
        <div v-if="isLoading">
          <i class="fa fa-spinner fa-spin"></i>
          Загрузка списка товаров...
        </div>
        <div v-else v-for="(product, index) in selectedProducts"
             class="tw:flex tw:items-center tw:mb-1">
          <button
            @click.prevent="removeItem(index)"
            class="btn btn-xs btn-danger"
          >
            <i class="fa fa-minus-circle"></i>
          </button>
          <div class="tw:ml-3">{{ product.name }}</div>
        </div>
      </div>
    </template>
    <template #help>
      <slot></slot>
    </template>
  </SettingsItem>
</template>

<script setup>
import SettingsItem from "@/components/SettingsItem.vue";
import {nextTick, onMounted, ref, watch} from "vue";
import {apiPost} from "@/utils/http.js";

const productsInput = ref(null);
const isLoading = ref(false);

const props = defineProps({
  label: {
    type: String,
    default: '',
  },
  placeholder: {
    type: String,
    default: ''
  },
  readonly: {
    type: Boolean,
    default: false,
  },
  rows: {
    type: Number,
    default: 5,
  },
});
const model = defineModel();

function removeItem(index) {
  model.value.splice(index, 1);
}

const selectedProducts = ref([]);
watch(
  model.value,
  async (ids) => {
    if (!ids?.length) {
      selectedProducts.value = [];
      return;
    }

    try {
      isLoading.value = true;
      const response = await apiPost('getProductsById', {
        product_ids: ids,
      });

      selectedProducts.value = response.data.data;
    } catch (err) {
      console.error(err);
    } finally {
      isLoading.value = false;
    }
  },
  {immediate: true}
);

onMounted(() => {
  nextTick(() => {
    if (productsInput.value) {
      $(productsInput.value).autocomplete({
        source: function (request, response) {
          $.ajax({
            url: `/admin/index.php?route=catalog/product/autocomplete&user_token=${window.TeleCart.user_token}&filter_name=${encodeURIComponent(request)}`,
            dataType: 'json',
            success: function (json) {
              response($.map(json, function (item) {
                return {
                  label: item['name'],
                  value: Number(item['product_id']),
                };
              }));
            }
          });
        },
        select: function (item) {
          model.value.push(item['value']);
        }
      });
    }
  });
});
</script>
