<template>
  <div class="position-relative">
    <form @submit.prevent="save()">
      <!-- <div class="form-row form-group p-0">
        <label class="col-md-4" for="title">موضوعات</label>
        <div class="col-md-8">
          <div v-for="(metaItem, index) in metaItems">
            <span :key="'meta' + metaItem.id" class="title text__12">
              {{ metaItem.title }}
            </span>
            <span
              style="color:blue"
              v-if="index < metaItems.length - 1"
              class="tavasi tavasi-Component-22--1"
            ></span>
          </template>
        </div>
      </div> -->
      <!-- <div class="form-row form-group">
      <label class="col-md-2" for="profile">نمایه</label>
      <select
        id="profile"
        name="profile"
        v-model="projectId"
        class="form-control col-md-10 "
      >
        <option v-for="item in profiles" :key="item.id" :value="item.id">
          {{ item.title }}
        </option>
      </select>
      </div>
      -->
      <div class="form-row form-group p-0">
        <label class="col-md-4" for="title">فهرست موضوعی</label>
        <div class="col-md-8">
          <div class="row form-group">
            <select
              @change="projectChanged"
              v-model="subjectProjectId"
              class="form-control col-md-9"
            >
              <option :value="undefined" selected disabled>
                انتخاب فهرست موضوعی
              </option>

              <option v-for="item in projects" :key="item.id" :value="item.id">
                {{ item.title }}
              </option>
            </select>
          </div>
        </div>
      </div>

      <div class="form-row form-group p-0" v-if="comboListCount">
        <label class="col-md-3" for="subject">موضوع</label>
        <div class="col-md-9">
          <div
            v-for="(comboItem, key) in comboListCount"
            :key="key"
            class="row mx-0 d-flex align-items-center form-group"
          >
            <select
              id="subject"
              name="subject"
              class="form-control col-md-9"
              @change="getSubjects($event, comboItem)"
              v-model="arrayOfSubjectId[key]"
            >
              <option :value="undefined" selected disabled>انتخاب موضوع</option>

              <option
                v-for="(item, key) in subjects[key]"
                :key="item.id"
                :value="item.id"
              >
                {{ item.title }}
                &nbsp; ({{ item.children }})
              </option>
            </select>

            <!-- <div class="col-md-4 remov_button "> -->
            <div class="col-auto d-flex">
              <button-component
                v-if="key == comboListCount - 1 && !isGuest"
                classes=" btn btn-default popUp-tab__clear button_giveup px-1"
                @click="openNewSubjectForm(comboItem)"
                buttonText=""
              >
                <span class="tavasi tavasi-Component-133--1"></span>
              </button-component>

              <button-component
                v-if="key == comboListCount - 1 && !isGuest"
                classes=" btn btn-default popUp-tab__clear button_giveup px-1"
                @click="removeSubject(key)"
                buttonText=""
              >
                <span class="tavasi tavasi-Component-295--1"></span>
              </button-component>
            </div>
          </div>
        </div>
      </div>
      <div
        class="form-row form-group p-0 submit_button d-flex justify-content-end"
      >
        <button-component
          v-if="!isGuest"
          type="submit"
          classes="btn-outline-primary"
          buttonText="افزودن"
          :buttonLoading="buttonLoading"
          @click="save()"
        ></button-component>
      </div>

      <div class="form-row form-group p-0">
        <!-- <the-content-loading v-if="fetchingData"></the-content-loading> -->

        <!-- <template v-else> -->
        <my-table
          height="auto"
          :hasSearch="false"
          :hasEdit="false"
          :hasDetails="false"
          :fetchingData="fetchingData"
          :items="itemSubject"
          :tableActions="tableActions"
          :tableColumns="tableColumns"
          :paginationInfo="pagination"
          :sortingInfo="sorting"
          @page-changed="pageChanged"
          @page-limit-changed="pageLimitChanged"
          @delete-table-item="deleteItem"
          @sort-changed="sortChanged"
        />
        <!-- </template> -->
      </div>

      <!-- <div class="form-row form-group mb-0 p-0">
      <div class="col-12 d-flex justify-content-between">
        <div class="d-flex">
        
          <button-component
            classes="btn-default"
            @click="closeModal()"
            buttonText="بستن"
            :buttonLoading="buttonLoading"
          ></button-component>
        </div>
      </div>
    </div> -->
    </form>

    <div class="new-subject-form-container" v-if="showSubjectForm">
      <!-- <list-form
        :selectedItem="{}"
        :parentId="arrayOfSubjectId[arrayOfSubjectId.length - 1]"
        apiName="subject"
        @close-modal="closeNewSubjectForm"
        @update-list="addNewItemToCombo"
      ></list-form> -->

      <!-- :selectedItem="selectedItem"
            :parentId="parentId"
            :apiName="apiName"
            @close-modal="closeModal"
            @update-list="updateList"
            @delete-item="deleteItem" -->
    </div>
  </div>
</template>

<script>
// import HttpService from "~/services/httpService";
import apis from "~/apis/listApi";
import { mapState, mapActions } from "pinia";
import { useAuthStore } from "~/stores/authStore";
import { useSearchStore } from "@search/stores/searchStore";

export default {
  props: {
    metaItems: {
      default() {
        return [];
      },
    },
    // called from jahat entity list subjecting.
    projectTagsName: {
      default: undefined,
    },
  },
  emits: ["update-list", "close-modal", "delete-item"],
  mounted() {
    // this.httpService = new HttpService(import.meta.env.VITE_LIST_BASE_URL);
    this.getProjects();
    this.itemSubject = this.selectedItemGetter?.subject;
  },
  data() {
    return {
      showSubjectForm: false,
      tableActions: [
        {
          showOutside: true,

          show: true,
          icon: "tavasi tavasi-Component-295--1",
          title: "حذف",
          to: {
            name: "undefined",
          },
          selected: false,
          disabled: false,
          howToOpen: "",
          href: "",
          class: "delete-btn",
          action: "delete-table-item",
          // can: "subject-",
        },
      ],
      tableColumns: [
        {
          key: "title",
          title: "عنوان",
        },
        {
          key: "path",
          title: "مسیر",
        },
      ],
      sorting: {
        sortby: "created",
        sortorder: undefined, // asc | none
      },
      pagination: {
        pages: 0,
        total: 0,
        page: 1,
        offset: 0, // page * per_page
        limit: 100, //per_page
      },
      httpService: undefined,
      fetchingData: false,
      itemSubject: [],
      subjectProjectId: undefined,
      projects: [],
      comboListCount: 0,
      arrayOfSubjectId: [],
      subjects: {},
      buttonLoading: false,

      selectedItemClone: {
        id: undefined,
        title: "",
        number: "",
        resource: "",
        date_text: "",
        text: "",
        projectid: this.subjectProjectId,
        item_type: "text",
      },
    };
  },
  computed: {
    ...mapState(useAuthStore, ["isGuest"]),
    ...mapState(useSearchStore, ["selectedProjectGetter", "selectedItemGetter"]),
  },

  methods: {
    ...mapActions(useSearchStore, ["SET_SELECTED_PROJECT"]),

    pageChanged({ pageNumber, limit }) {
      let page = paging.pageNumber;
      page -= 1;
      this.pagination.offset = page * paging.limit;
      this.pagination.limit = paging.limit;
      this.pagination.page = paging.pageNumber;

      this.countInPage = limit;

      this.getProjects();
    },
    pageLimitChanged(paging) {
      this.resetPagination();
      this.pagination.limit = paging.limit;

      this.getProjects();
    },
    sortChanged(sorting) {
      // keep limit status.
      // reset page and offset values.
      this.pagination.page = this.pagination.offset = 0;
      this.sorting = sorting;

      this.getProjects();
    },
    removeSubject(index) {
      this.arrayOfSubjectId.splice(index, 1);
      this.comboListCount--;
    },

    async getProjects() {
      const payload = {
        isown: 3,
        type: 3,
        tags: this.projectTagsName,
        ...this.sorting,
        ...this.pagination,
      };

      try {
        const { $api } = useNuxtApp();
        const response = await $api(apis.projects.list, {
          method: "POST",
          baseURL: listUrl(),
          body: payload,
        });

        this.projects = response.data;

        // called from jahat entity list subjecting.
        if (this.projectTagsName) {
          this.subjectProjectId = this.projects[0].id;
          this.SET_SELECTED_PROJECT(this.projects[0]);
          this.getSubjects(0, 0);
        }

        this.getItemSubject();
      } catch (err) {}
      // this.httpService
      //   .formDataRequest(apis.projects.list, payload)
      //   .then((response) => {
      //     this.projects = response.data;

      //     // called from jahat entity list subjecting.
      //     if (this.projectTagsName) {
      //       this.subjectProjectId = this.projects[0].id;
      //       this.SET_SELECTED_PROJECT(this.projects[0]);
      //       this.getSubjects(0, 0);
      //     }

      //     this.getItemSubject();
      //   });
    },
    projectChanged() {
      this.comboListCount = 0;
      this.arrayOfSubjectId = [];
      this.subjects = {};

      this.getSubjects(0, 0);
    },

    async getSubjects(ev, index) {
      const parentItem = typeof ev == "object" ? ev.target.value : 0;
      const payload = {
        projectid: this.subjectProjectId,
        parent: parentItem,
        sortby: "id",
        offset: 0,
        limit: 100,
      };

      try {
        const { $api } = useNuxtApp();
        const response = await $api(apis.subject.list, {
          method: "POST",
          baseURL: listUrl(),
          body: payload,
        });
        if (response.data.length) {
          this.subjects[index] = response.data;
          this.comboListCount = ++index;
          this.arrayOfSubjectId = this.arrayOfSubjectId.slice(0, index);
        }

        this.getItemSubject();
      } catch (err) {}

      // this.httpService
      //   .formDataRequest(apis.subject.list, payload)
      //   .then((response) => {
      //     if (response.data.length) {
      //       this.subjects[index] = response.data;
      //       this.comboListCount = ++index;
      //       this.arrayOfSubjectId = this.arrayOfSubjectId.slice(0, index);
      //     }

      //     this.getItemSubject();
      //   });
    },

    async getItemSubject() {
      if (this.fetchingData) return;
      this.fetchingData = true;

      const payload = {
        projectid: this.selectedProjectGetter?.id,
        id: this.selectedItemGetter?.id,
        sortby: "id",
        offset: 0,
        limit: 100,
      };

      try {
        const { $api } = useNuxtApp();
        const response = await $api(apis.item.subject, {
          method: "POST",
          baseURL: listUrl(),
          body: payload,
        });
        if (response.data.length) {
          {
            const myResponse = structuredClone(response.data);
            myResponse.forEach((element) => {
              const stringPath = element.path.map((mapItem) => mapItem.title);
              element.path = stringPath.join("/");
            });

            this.itemSubject = myResponse;
          }
        } else this.itemSubject = [];

        this.fetchingData = false;
      } catch (err) {
        this.fetchingData = false;
      }

      // this.httpService
      //   .formDataRequest(apis.item.subject, payload)
      //   .then((response) => {
      //     if (response.data.length) {
      //       {
      //         const myResponse = structuredClone(response.data);
      //         myResponse.forEach((element) => {
      //           const stringPath = element.path.map((mapItem) => mapItem.title);
      //           element.path = stringPath.join("/");
      //         });

      //         this.itemSubject = myResponse;
      //       }
      //     } else this.itemSubject = [];

      //     this.fetchingData = false;
      //   })
      //   .catch(() => (this.fetchingData = false));
    },
    async save() {
      if (this.isGuest) return;

      if (this.buttonLoading) return;
      this.buttonLoading = true;

      const formData = {
        projectid: this.subjectProjectId,
        subjectid: this.arrayOfSubjectId[this.arrayOfSubjectId.length - 1],
        itemid: this.selectedItemGetter?.id,
        listid: undefined,
      };

      if (formData.subjectid === undefined) {
        this.mySwalToast({
          title: "موضوع انتخاب نشده است.",
          html: null,
          icon: "error",
        });
        this.buttonLoading = false;
        return;
      }

      try {
        const { $api } = useNuxtApp();
        const response = await $api(apis.subjectRelation.add, {
          method: "POST",
          baseURL: listUrl(),
          body: formData,
        });
        this.mySwalToast({
          title: response.message,
          html: null,
          icon: "success",
        });
        this.getItemSubject();
      } catch (err) {
        this.mySwalToast({
          title: err.response.data.message,
          html: null,
          icon: "error",
        });
        this.buttonLoading = false;
      }

      // this.httpService
      //   .formDataRequest(apis.subjectRelation.add, formData)
      //   .then((response) => {
      //     this.mySwalToast({
      //       title: response.message,
      //       html: null,
      //       icon: "success",
      //     });
      //     this.getItemSubject();
      //   })
      //   .catch((err) => {
      //     this.mySwalToast({
      //       title: err.response.data.message,
      //       html: null,
      //       icon: "error",
      //     });
      //   })
      //   .finally(() => {
      //     this.buttonLoading = false;
      //   });
    },

    deleteItem(tableRowItemIndex) {
      if (this.isGuest) return;

      const data = {
        projectid: this.itemSubject[tableRowItemIndex].project_id,
        itemid: this.selectedItemGetter?.id,
        subjectid: this.itemSubject[tableRowItemIndex].id,
      };

      this.mySwalConfirm({
        title: "هشدار",
        html: "از حذف رابطه موضوع مطمئن هستید؟",
        icon: "warning",
      }).then(async (result) => {
        if (result.isConfirmed) {
          try {
            const { $api } = useNuxtApp();
            const res = await $api(apis.subjectRelation.delete, {
              method: "POST",
              baseURL: listUrl(),
              body: data,
            });
            tthis.itemSubject.splice(tableRowItemIndex, 1);

            this.mySwalToast({
              title: res.data.message,
              html: undefined,
              icon: "success",
            });
          } catch (err) {}

          // this.httpService
          //   .formDataRequest(apis.subjectRelation.delete, data)
          //   .then((res) => {
          //     this.itemSubject.splice(tableRowItemIndex, 1);

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

    closeNewSubjectForm() {
      this.showSubjectForm = false;
    },
    openNewSubjectForm() {
      this.showSubjectForm = true;
    },
    async addNewItemToCombo(comboItem, itemId = 0, listId = 0) {
      if (this.isGuest) return;
      const payload = {
        itemid: itemId,
        listid: listId,
        listtype: this.listTypeId ?? 0,
        projectid: this.selectedProjectGetter?.id,
      };

      try {
        const { $api } = useNuxtApp();
        const res = await $api(apis.subject.add, {
          method: "POST",
          baseURL: listUrl(),
          body: payload,
        });
        this.mySwalToast({
          title: "تبریک",
          html: res.data.message,
          icon: "success",
        });
      } catch (err) {}

      // this.httpService
      //   .formDataRequest(apis.subject.add, payload)
      //   .then((res) => {
      //     this.mySwalToast({
      //       title: "تبریک",
      //       html: res.data.message,
      //       icon: "success",
      //     });

      /* todo: 
        1-add item to the current combo.
        2-close form.
        */
      // });
    },
  },
};
</script>

<style lang="scss" scoped>
.new-subject-form-container {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background: #fff;
  box-shadow: 0px 0px 17px 1px #eee;
  padding: 1em;
  width: 70%;
  margin: auto;
  height: 50%;
}

.form-control {
  // border-radius: 0 20px 20px 0;
  font-size: 14px;
  font-weight: 300;
  text-align: right;
  color: #707b87;
  height: 100%;
  // border-color: transparent;
  padding-right: 0;
  padding-left: 0;
}
.remov_button {
  top: 20px;
  right: 60%;
}
.submit_button {
  // position: relative;
  // right: 90px !important;
}

.form-control::-webkit-input-placeholder {
  /* Chrome/Opera/Safari */
  color: pink;
}
.form-control::-moz-placeholder {
  /* Firefox 19+ */
  color: pink;
}
.form-control:-ms-input-placeholder {
  /* IE 10+ */
  color: pink;
}
.form-control:-moz-placeholder {
  /* Firefox 18- */
  color: pink;
}
</style>