<template>
  <div class="position-relative">
    <form>
      <div class="form-row text__14">
        <label for="">پاسخ به مساله </label>
        <span v-if="$route.name == 'issuesShow'" class="text-overflow">{{
          data.entity.title ?? data.entity.summary
        }}</span>

        <span v-else class="text-overflow">{{
          data.entity.entities.entity_title ?? data.entity.entities.summary
        }}</span>
      </div>
      <div class="form-row">
        <label for="">عنوان کوتاه: </label>
        <div class="input-container">
          <input
            type="text"
            ref="title"
            placeholder="عنوان کوتاه را وارد کنید"
            v-model="entity.title"
          />
          <div v-if="errors.title && errors.title.length > 0">
            <div
              class="error-input"
              v-for="(error, index) in errors.title"
              :key="index"
            >
              {{ error }}
            </div>
          </div>
        </div>
      </div>

      <div class="form-row">
        <label for="">چکیده </label>
        <div class="input-container">
          <textarea
            name=""
            id=""
            v-model="entity.summary"
            cols="30"
            rows="10"
            placeholder="چکیده ای از پاسخ را گویا بیان فرمایید"
          ></textarea>
          <div v-if="errors['summary'] && errors['summary'].length > 0">
            <div
              class="error-input"
              v-for="(error, index) in errors['summary']"
              :key="index"
            >
              {{ error }}
            </div>
          </div>
        </div>
      </div>
      <div class="form-row">
        <label for="">واژه گان کلیدی</label>
        <div class="input-container">
          <!-- <vue-select dir="rtl" multiple taggable  v-model="description.properties.keywords" :options="keywords" ></vue-select> -->
          <vue-select
            dir="rtl"
            taggable
            multiple
            push-tags
            v-model="entity.keywords"
            :options="keywords"
            :reduce="(option) => option.key"
            label="key"
          >
            <div slot="no-options"> جستجوی ... </div>
            <div slot="option" slot-scope="option">
              <div class="d-center">
                {{ option.key }}
                <span class="text__12" style="color: #ccc"
                  >&nbsp;{{ ` (${option.doc_count}) ` }}</span
                >
              </div>
            </div>
            <div slot="selected-option" slot-scope="option">
              <div class="selected d-center">
                {{ option.key }}
              </div>
            </div>
          </vue-select>

          <div v-if="errors['keywords'] && errors['keywords'].length > 0">
            <div
              class="error-input"
              v-for="(error, index) in errors['keywords']"
              :key="index"
            >
              {{ error }}
            </div>
          </div>
        </div>
      </div>

      <div class="popUp-tab__buttons">
        <div class="d-flex justify-content-between flex-grow-1">
          <span>&nbsp;</span>

          <div class="d-flex">
            <button
              title="لغو"
              @click.prevent="$emit('close-modal')"
              class="popUp-tab__clear btn"
              type="button"
            >
              لغو
            </button>
            <button
              type="button"
              class="popUp-tab__submit btn"
              @click.prevent="addAnswer(entity)"
            >
              ثبت
            </button>
          </div>
        </div>
      </div>
    </form>
  </div>
</template>

<script>
import { mapState } from "pinia";
import { entityMixin } from "@mixins/entity/entityMixin";
import { commonMixin } from "@mixins/entity/commonMixin";
import repoApi from "~/apis/repoApi";

export default {
  mixins: [entityMixin, commonMixin],
  props: {
    data: { type: Object, default: () => ({}) },
    issueData: { type: Object, default: () => ({}) },
  },
  
  data() {
    return {
      httpService: undefined,
      entity: {
        summary: "",
        title: "",
        keywords: [],
        // weight: 0,
      },
      // type_id: 3,
      keywords: [],
    };
  },
  

  methods: {
    // onSearch(search, loading) {
    //   if (search.length) {
    //     loading(true);
    //     this.search(loading, search, this);
    //   }
    // },
    // search: _.debounce((loading, search, vm) => {
    //   fetch(
    //     `https://api.github.com/search/repositories?q=${escape(search)}`
    //   ).then((res) => {
    //     res.json().then((json) => (vm.options = json.items));
    //     loading(false);
    //   });
    // }, 350),

    getKeywords() {
      let self = this;

      let url = repoApi.keywords.all;
      this.httpService.getRequest(url).then((res) => {
        // let data = {
        // id: item.count,
        // label: item.key,
        // };

        self.keywords = res.aggregations.keywords.buckets;
      });
    },
    addAnswer(my_entity) {
      if (!my_entity) my_entity = this.entity;

      my_entity.type_id = this.getEntityTypeId("answer");
      my_entity.entities = {
        entity_title: this.issueData._source.title,
        entity_id: this.issueData._source.id,
        realation_type: this.getRelationTypeId("answer"),
      };

      this.addEntity(my_entity).then((res) => {
        this.addToConversation(res, my_entity);
        this.setParentInAnswersAndIssues(res);

        this.mySwalToast({
          title: res.message,
          icon: "success",
        });

        setTimeout(() => {
          if (this.$route.name == "issuesShow")
          this.$emit("answer-added", this.data.entity.id);
        else this.$emit("close-modal");
      }, 1000);
      });
    },

    setParentInAnswersAndIssues(res) {
      let payload = {
        refrence_id: res._id,
        entity_type_id: this.$route.meta.entityType,
        prefrence_id: this.issueData._source.id,
      };
      let url = messageUrl()+ repoApi.messages.setparent;
      this.httpService.postRequest(url, payload).then((rese) => {
      });
    },
  },
  mounted() {
    this.getKeywords();
  },
};
</script>
<style scoped lang="scss">
@import "../../../assets/common/scss/mixin.scss";

img {
  height: auto;
  max-width: 2.5rem;
  margin-right: 1rem;
}

.d-center {
  display: flex;
  align-items: center;
}

.selected img {
  width: auto;
  max-height: 23px;
  margin-right: 0.5rem;
}

.v-select .dropdown li {
  border-bottom: 1px solid rgba(112, 128, 144, 0.1);
}

.v-select .dropdown li:last-child {
  border-bottom: none;
}

.v-select .dropdown li a {
  padding: 10px 20px;
  width: 100%;
  font-size: 1.25em;
  color: #3c3c3c;
}

.v-select .dropdown-menu .active > a {
  color: #fff;
}
.text-overflow {
  @include textOverflow(36em);
}
</style>