<template>
  <div>
    <the-content-loading v-if="fetchingData"></the-content-loading>

    <div v-else>
      <form v-if="properties.length" class="form" @submit.prevent="onSubmit()">
        <div v-for="(property, index) in properties" :key="property.title" class="form-row form-group">
          <label class="col-1" :for="'ta' + index">{{ property.title }} </label>

          <div class="col">
            <textarea class="form-control" :id="'ta' + index" :name="'ta' + index" :placeholder="property.title"
              v-model.trim="property.keys" rows="1"></textarea>
          </div>
        </div>

        <div class="form-row form-group mt-4">
          <div class="col d-flex">
            <button-component classes="btn-outline-primary" type="submit" :buttonText="'ذخیره'"
              :buttonLoading="buttonLoading"></button-component>
          </div>
        </div>
      </form>
      <no-data v-else />
    </div>

  </div>
</template>

<script>
import settingsApi from "~/apis/settingsApi";

export default {
  name: "searchAmplify",
  setup() {
    definePageMeta({
      name: "searchAmplify",
    });
  },
  data() {
    return {
      stopWords: '',
      fetchingData: false,
      buttonLoading: false,
      properties: [],
      payload: {},
    };
  },
  computed: {
  },

  methods: {
    getData() {
      if (this.fetchingData) return;
      this.fetchingData = true;

      var url = settingsApi.app.getByKey;
      url = url.replace("{{key_option}}", "search_amplify");
      // let url = apis.admin.get.replace('{{system}}', this.$route.meta.apiKey)

      ApiService.getRequest(url)
        .then((response) => {
          this.payload = response.data.hits.hits[0]._source;
          this.properties = JSON.parse(response.data.hits.hits[0]._source.value);
        })
        .catch((error) => {
        }).finally(() => {
          this.fetchingData = false;
        })
    },
    onSubmit() {
      if (this.buttonLoading) return;
      this.buttonLoading = true;

      // var url = apis.admin.save;
      // const payload = { ...this.payload, ...{ value: JSON.stringify(this.properties) } }

      var url = settingsApi.app.saveByKey;
      url = url.replace("{{key_option}}", "search_amplify");
      const payload = { value: JSON.stringify(this.properties) }


      ApiService.postRequest(url, payload)
        .then((response) => {
          this.mySwalToast({
            title: "تبریک",
            html: response.data.message,
            icon: "success",
          });
        })
        .catch((error) => {
        }).finally(() => {
          this.buttonLoading = false;
        })
    }
  },
  mounted() {
    this.getData();
  },
  watch: {
    //   $route: {
    //     handler: function () {
    //       this.$store.state.collapsed = false;
    //     },
    //     deep: true,
    //     immediate: true,
    //   },
  },
};
</script>