<template>
  <div class="position-relative">
    <form action="">
      <div class="row" v-if="statosPag == 0">
        <div class="col-12 borders mb-2">
          <p class="col-md-4" for="title">فهرست معیار ها :</p>
          <select
            class="form-control"
            style="border: 1px solid #495057"
            v-model="item"
          >
            <option :value="undefined" selected disabled>
              انتخاب از فهرست معیار ها
            </option>

            <option
              :key="index"
              :value="crition"
              v-for="(crition, index) in critions"
            >
              {{ crition.title }}
            </option>
          </select>

          <div class="d-flex mt-2">
            <div>
              <p>موضوع:</p>
            </div>
            <div
              v-for="(item, index) in data.entity.subject"
              style="cursor: pointer"
              @click.prevent="getDataCriterionsSubject(item.id)"
            >
              <p id="item.id" class="me-1 text-primary">
                {{ item.title
                }}<span class="me-1 text-muted" style="cursor: auto">،</span>
              </p>
            </div>
          </div>
        </div>
        <div v-if="criterionsSubject.length" class="col-12 mt-4 borders1">
          <P>فهرست معیار های مرتبط با موضوع :</P>
          <div class="list-crition-select mt-3" v-if="show">
            <div
              v-for="(crition, index) in criterionsSubject"
              class="crition-select d-flex flex-column bd-highlight mt-4 mb-4"
            >
              <div class="d-flex crition-select-item mb-3">
                <div class="form-check">
                  <input
                    class="form-check-input"
                    type="checkbox"
                    :value="crition"
                    v-model="lists"
                    :id="index"
                  />
                </div>
                <div>
                  <p class="text__16" style="color: inherit">
                    {{ crition.title }}
                  </p>
                </div>
              </div>
              <!-- <div>
              <p class="text__14" style="color: #92a2b2">
                <span>مطلوب :</span> {{ crition.favorite }}
              </p>
            </div> -->
              <div>
                <p class="text__14" style="color: #92a2b2">
                  <span>توضیحات :</span> {{ crition.text }}
                </p>
              </div>
            </div>
          </div>
          <div v-if="show == false" style="color: #6c757d">
            <p>روی یک موضوع کلیک کنید</p>
          </div>
        </div>

        <div class="col-12 mt-2">
          <p>معیار های انتخاب شده :</p>
          <div class="list-crition" v-if="lists.length >= 1" ref="parent">
            <div
              v-for="(list, index) in lists"
              class="critions d-flex flex-column bd-highlight"
            >
              <div class="d-flex justify-content-between">
                <div class="d-flex">
                  <p :id="list.id" class="me-1 mb-1 crition" :ref="list.id">
                    <span>{{ index + 1 }}) </span>{{ list.title }}
                  </p>
                  <button
                    type="button"
                    class="close"
                    @click.prevent="activeFormIndex = index"
                  ></button>
                </div>
                <button
                  type="button"
                  class="close"
                  @click.prevent="removCrition(index, list)"
                >
                  ×
                </button>
              </div>

              <div v-if="activeFormIndex == index" class="d-flex">
                <input
                  class="form-control form-control-sm"
                  type="text"
                  placeholder="توضیحات"
                  v-model="itemDescription"
                  @keyup.enter="submit(itemDescription, list)"
                />
                <button
                  type="button"
                  class="close text-primary"
                  @click.prevent="closeModal()"
                >
                  ×
                </button>
              </div>
            </div>
          </div>
          <div
            class="list-crition"
            v-if="lists.length == 0"
            style="color: #6c757d"
          >
            <p>از لیست بالا موردی را انتخابکنید</p>
          </div>
        </div>

        <div class="popUp-tab__buttons">
          <div class="d-flex justify-content-between flex-grow-1">
            <span>&nbsp;</span>
            <div data-v-e8ee7a26="" class="d-flex">
              <button
                type="button"
                class="btn btn-outline-primary"
                @click.prevent="saveProperty()"
              >
                افزودن
              </button>
            </div>
          </div>
        </div>
      </div>

      <div class="row" v-if="statosPag == 1">
        <div class="col-12 mb-2">
          <div class="menu-multiselect">
            <select
              class="form-control"
              style="border: 1px solid #495057"
              v-model="itemSelect.entity_id"
            >
              <option :value="undefined" selected disabled>
                انتخاب از فهرست معیار ها
              </option>

              <option
                :key="index"
                :value="crition.id"
                v-for="(crition, index) in critions"
              >
                {{ crition.title }}
              </option>
            </select>
          </div>
        </div>
        <div class="col-12 mb-2">
          <div class="form-row form-group p-0">
            <label class="col-md-12" for="description">توضیحات</label>
            <textarea
              class="col-md-12 h-auto mb-2"
              v-model="itemSelect.description"
              name="description"
              cols="30"
              rows="5"
              placeholder="توضیحات را وارد کنید"
              style="overflow: auto"
            ></textarea>
          </div>
        </div>
        <div class="popUp-tab__buttons">
          <div class="d-flex justify-content-between flex-grow-1">
            <button
              class="btn delete-btn btn-outline-danger"
              @click.prevent="removCrition(0, itemSelect)"
            >
              حذف
            </button>
            <div data-v-e8ee7a26="" class="d-flex">
              <button
                type="button"
                class="popUp-tab__clear btn"
                @click.prevent="closeModal"
              >
                لغو
              </button>
              <button
                type="button"
                class="btn btn-outline-primary"
                @click.prevent="saveEditCriterion()"
              >
                ذخیره
              </button>
            </div>
          </div>
        </div>
      </div>
    </form>
  </div>
</template>

<script>

import repoApi from "~/apis/repoApi";
import { mapState, mapActions } from "pinia";
import { propertyMixin } from "~/chat/mixins/propertyMixin";

export default {
  mixins: [propertyMixin],
  props: {
    data: { type: Object, default: () => ({}) },
  },
  beforeMount() {
    if (this.data.index == -1) {
      this.statosPag = 0;
      this.indexItemEdited = this.data.index;
    } else {
      this.statosPag = 1;
      this.indexItemEdited = this.data.index;
    }
  },
  mounted() {
    this.httpServiceJahat = new HttpService(import.meta.env.VITE_REPO_BASE_URL);
    this.getCritions();
    if (this.data.entity?.crition) {
      this.data.entity.crition.forEach((element) => {
        this.lists.push({
          id: element.entity_id,
          title: element.entity_title,

          description: element.description,
        });
      });
    }

    this.itemSelect = {
      entity_id: this.lists[this.indexItemEdited].id,
      entity_title: this.lists[this.indexItemEdited].title,
      description: this.lists[this.indexItemEdited].description,
    };
  },
  data() {
    return {
      indexItemEdited: undefined,
      statosPag: 0,
      criterionsSubject: "",
      activeFormIndex: undefined,
      itemDescription: "",
      critions: [],
      item: undefined,
      itemSelect: "",
      lists: [],
      listCritions: [],
      httpServiceJahat: undefined,
      pagination: {
        page: 1,
        pages: 0,
        total: 0,
        offset: 0,
        limit: 500,
      },
      show: false,
    };
  },
  watch: {
    item(newVal) {
      this.lists.push({
        id: newVal.id,
        title: newVal.title,
      });
    },
  },

  computed: {
    ...mapState("list", ["selectedProjectGetter", "selectedItemGetter"]),
  },

  methods: {
    ...mapActions("list", ["SET_SELECTED_PROJECT"]),
    getDataCriterionsSubject(id) {
      const subject_id = id;
      const url = repoApi.public.bysubject
        .replace("{{from}}", "0")
        .replace("{{countInPage}}", "10")
        .replace("{{index_key}}", "crition")
        .replace("{{subject_id}}", subject_id);
      this.httpServiceJahat.getRequest(url).then((res) => {
        const list = [];
        res.hits.hits.forEach((item, key) => {
          list.push({
            id: item._source.id,
            title: item._source.title,

            text: item._source.text,
          });
        });
        this.criterionsSubject = list;
        this.show = true;
      });
    },
    saveEditCriterion() {
      let url =
        "jahat" +
        "/" +
        repoApi.property.edit +
        `/${this.data.entity.id}/${this.data.keyName}`;
      url += "/id/" + this.itemSelect.entity_id;

      const formData = {
        [this.data.keyName]: this.itemSelect,
      };

      this.httpServiceJahat.postRequest(url, formData).then((res) => {
        // console.log(res);
        mySwalToast({
          title: "    ثبت شد.",
          html: "",
        });
        this.$emit("close-modal");
      });
    },
    saveProperty() {
      var listCritions = this.data.entity.crition;
      var list = this.lists;
      let url = repoApi.crition.add.replace(
        "{{issue_id}}",
        this.data.entity.id
      );
      if (listCritions) {
        const filteredList = list.filter(
          (newItem) =>
            !listCritions.find((oldItem) => oldItem.entity_id === newItem.id)
        );
        filteredList.forEach((element) => {
          const value = {
            entity_id: element.id,
            entity_title: element.title,
            description: element.description,
          };

          const formData = {
            crition: value,
          };

          this.httpServiceJahat.postRequest(url, formData).then((res) => {
            // console.log(res);
            mySwalToast({
              title: "    ثبت شد.",
              html: "",
            });
          });
        });
      } else {
        list.forEach((element) => {
          const value = {
            entity_id: element.id,
            entity_title: element.title,
            description: element.description,
          };
          const formData = {
            crition: value,
          };

          this.httpServiceJahat.postRequest(url, formData).then((res) => {
            // console.log(res);
            mySwalToast({
              title: "    ثبت شد.",
              html: "",
            });
          });
        });
      }
      this.$emit("close-modal");
    },
    getCritions() {
      if (this.fetchingData) return;
      this.fetchingData = true;

      let url =
        repoApi.entity.list.replace("{{type}}", this.data.keyName) +
        `/${this.pagination.offset}/${this.pagination.limit}`;
      url += "/date_create/desc";

      this.httpServiceJahat.getRequest(url).then((res) => {
        const list = [];
        res.hits.hits.forEach((item, key) => {
          // console.log(item)

          list.push({
            id: item._source.id,
            title: item._source.title,
          });
        });
        this.critions = list;
        this.listCritions = this.critions.splice(0, 7);

        this.fetchingData = false;
      });
    },
    removCrition(i, item) {
      var index = i;
      var list = [];
      list = this.lists;
      let url = "";
      if (item.id) {
        url = repoApi.crition.delete
          .replace("{{issue_id}}", this.data.entity.id)
          .replace("{{crition_id}}", item.id);
      } else {
        url = repoApi.crition.delete
          .replace("{{issue_id}}", this.data.entity.id)
          .replace("{{crition_id}}", item.entity_id);
      }
      mySwalConfirm({
        title: "هشدار",
        html: "از حذف این بخش مطمئن هستید؟",
        icon: "warning",
      }).then((result) => {
        if (result.isConfirmed) {
          this.httpServiceJahat.postRequest(url).then((res) => {
            mySwalToast({
              title: "تبریک",
              html: res.data.message,
              icon: "success",
            });
          });

          var lists = list.splice(index, 1);
        }

        if (this.statosPag == 1) {
          this.$emit("close-modal");
        }
      });
    },
    submit(item, list) {
      let mylist = list;
      mylist.description = item;
    },
    closeModal() {
      this.activeFormIndex = undefined;
      this.itemDescription = undefined;
    },
  },

};
</script>
<style lang="scss" scoped>
.my-profile {
  padding-bottom: 0 !important;
}
.my-profile__form {
  padding-top: 0 !important;
}
.green {
  background-color: green;
}
.btn-secondarys {
  color: #6c757d;
  background-color: #fff;
  border-color: #6c757d;
  border-radius: 7px;
}

.btn-secondarys:hover {
  color: #00b6e3;
  background-color: #fff;
  border-color: #00b6e3;
}

.borders {
  position: relative;
}

.borders::before {
  content: "";
  border-bottom: solid #f1f1f1 1px;
  position: absolute;
  bottom: -14px;
  width: 96%;
}

.borders1 {
  position: relative;
}

.borders1::after {
  content: "";
  border-bottom: solid #f1f1f1 1px;
  position: absolute;
  bottom: -8px;
  width: 96%;
}

.list-crition {
  width: 100%;
  height: 140px;
  margin-top: 10px;
  overflow: hidden;
  overflow-y: auto;
}

// .critions:hover {
//   color: red;

//   p,
//   button {
//     color: inherit;
//   }
// }

.list-crition-select {
  width: 100%;
  height: 140px;
  margin-top: 10px;
  overflow: hidden;
  overflow-y: auto;
}

.crition-select-item:hover {
  color: #00b6e3;

  div {
    p {
      color: inherit;
    }
  }
}

.crition {
  color: #00b6e3;
}

.form-check-input {
  height: 14px !important;
}
.critions {
  &:hover {
    .search-item__actions {
      width: 5.6em;
      transition: all 0.5s;
      background: #fff;
      border-radius: 0 0.5em 0.5em 0;

      .tavasi-more-vert {
        transition: all 0.2s;
        display: none;
      }
    }
  }
}
.search-item__actions {
  position: relative;
  // left: 20px;
  width: 1.6em;
  // top: 1em;
  overflow: hidden;
  transition: all 0.5s;
  display: flex;
  align-items: center;

  .btn {
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      filter: brightness(0.9);
    }

    .niafam {
      color: #adbec4;
    }
  }
}
</style>
