<template>
  <div class="wrapper">
    <the-sidebar
      :showUserAvatar="!isMajlesBuild"
      :menu="sidbarMenu"
      class="hiddens"
    ></the-sidebar>
    <main>
      <header>
        <div class="logo-and-dropdown">
          <img :src="logoPhoto()" alt="" class="logo" />
        </div>

        <div class="avatar">
          <user-avatar-dropdown class="nav-item rounded-circle">
            <router-link :to="{ name: 'searchAbout' }" class="dropdown-item"
              >درباره ما</router-link
            >
            <router-link :to="{ name: 'searchConnect' }" class="dropdown-item"
              >تماس با ما</router-link
            >
          </user-avatar-dropdown>
        </div>
      </header>
      <div class="dropdown mb-3 mt-2">
        <div class="dropdown me-auto text__13 sortlist" ref="dropdownSortlist">
          <button
            class="btn dropdown-toggle"
            type="button"
            data-bs-toggle="dropdown"
            aria-expanded="false"
          >
            <span style="color: #adbec4"> افزودن مورد جدید:&nbsp;&nbsp; </span>
            <span> {{ titleSelected }}</span>
          </button>
          <div class="dropdown-menu">
            <button
              class="dropdown-item text__13"
              v-for="(item, index) in schemasGetter"
              @click.prevent="setItemDropdown(item, item.label)"
              :key="index"
            >
              {{ item.label }}
            </button>
          </div>
        </div>
      </div>
      <section class="mt-3">
        <div>
          <div class="accordion" id="accordionExample">
            <div
              class="card rounded-0"
              v-for="(innerGroupItem, j) in activeSchemaGetter?.property"
              :key="j"
            >
              <div class="card-header" :id="'heading' + j" style="height: 4em">
                <div class="d-flex justify-content-between">
                  <p style="font-size: 12px; color: black">
                    {{ innerGroupItem.title }}
                  </p>
                  <button
                    class="btn btn-link btn-block text-end collapsed button-meno"
                    type="button"
                    data-bs-toggle="collapse"
                    :data-bs-target="'#collapse' + j"
                    aria-expanded="false"
                    :aria-controls="'collapse' + j"
                  >
                    <span class="tavasi tavasi-Component-358--1"></span>
                  </button>
                </div>
              </div>

              <div
                :id="'collapse' + j"
                class="collapse"
                :class="{ show: 'collapse' + j == 'collapse0' }"
                :aria-labelledby="'heading' + j"
                data-parent="#accordionExample"
              >
                <div class="card-body">
                  <form>
                    <component
                      v-for="(formElement, index) in innerGroupItem.items"
                      :key="index"
                      :formElement="formElement"
                      :inputClass="handlerInputClass(formElement)"
                      :labelClass="'col-md-3'"
                      :rows="formElement.rows"
                      :is="
                        returnComponentName(innerGroupItem, formElement.type)
                      "
                      @take-value="saveComponentValue($event, formElement)"
                      @keydown="saveKeydown($event)"
                      class="component"
                    ></component>
                    <div
                      class=""
                      style="
                        position: relative;
                        display: flex;
                        justify-content: flex-end;
                      "
                    >
                      <button
                        type="submit"
                        class="btn btn-primary"
                        style="font-size: 11px"
                        v-can="innerGroupItem.key + '_edit'"
                        @click.prevent="addNewEntity(activeSchemaGetter)"
                      >
                        ثبت
                      </button>
                    </div>
                  </form>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    </main>
  </div>
</template>
<script>
import { mapState, mapActions } from "pinia";

import sidbarMenu from "~/pages/search/json/menu.json";
import newEntityBuilder from "~/pages/search/json/newEntityBuilder.json";
import searchApi from "~/apis/searchApi";
import { useStorage } from "@vueuse/core";

export default {
  beforeMount() {
    this.httpService = new HttpService(import.meta.env.VITE_REPO_BASE_URL);
  },
  mounted() {
    this.titleSelected = this.activeSchemaGetter.label;
  },
  watch: {
    $route: {
      handler: function (to, from) {
        console.log("to", to);
        console.log("from", from);
      },
    },
  },
  data() {
    return {
      sidbarMenu: sidbarMenu,
      newEntityBuilder: newEntityBuilder,
      httpService: undefined,
      listUpdatedText: {},
      titleSelected: "",
      newEntityId: undefined,
    };
  },
  computed: {
    ...mapState({
      organNameGetter: "organNameGetter",
      schemasGetter: "schemasGetter",
      activeSchemaGetter: "activeSchemaGetter",
    }),
  },
  methods: {
    ...mapActions(["schemasSetter", "activeSchemaSetter"]),
    returnComponentName(innerGroupItem, type) {
      if (type == "textarea") return "TextareaComponent";
      else if (type == "select") return "SelectComponent";
      else if (type == "date") return "DateComponent";
      else return "InputComponent";
    },
    saveComponentValue(value, formElement) {
      // console.log("🚀 ~ saveComponentValue ~ formElement:", formElement);
      // console.log("🚀 ~ saveComponentValue ~ value:", value);
      //در صورت تغییر نگهداری می شود تا وقتی کلید ثبت زد، ذخیره شود
      // if (this.activeSchemaGetter[formElement.key] != value) {
      //   this.listUpdatedText[formElement.key] = value;
      // }
      if (value !== "") {
        this.listUpdatedText[formElement.key] = value;
      }
    },
    getSchemas() {
      this.httpService
        .postRequest(searchApi.schema.list, {
          organ: this.organNameGetter,
          system: "entityCreate",
          build_state: buildState(),
        })
        .then((response) => {
          console.log(response);
        
          let newEntitySchema = useStorage("newEntitySchema", undefined);
          newEntitySchema.value =  response.data.entityCreate;


          this.schemasSetter(response.data.entityCreate);

          let activeSchema = response.data.entityCreate[0];

          this.activeSchemaSetter(activeSchema);
          
          let activeNewEntitySchema = useStorage("activeNewEntitySchema", undefined);
          activeNewEntitySchema.value =  activeSchema;
        });
    },
    setItemDropdown(item, title) {
      this.titleSelected = title;
      this.activeSchemaSetter(item);
      console.log("item", item);
    },
    handlerInputClass(item) {
      if (item.type == "textarea") {
        return "col-md-12";
      } else if (item.type == "date" || item.type == "select") {
        return "col-md-3";
      } else {
        return "col-md-8";
      }
      // console.log(item);
    },
    addNewEntity(item) {
      if (this.newEntityId !== undefined) {
        this.updateNewEntity(item);
      } else {
        let url = searchApi.newEntity.add;
        url = url.replace("{{index_key}}", item.key);

        const formData = {
          meta: JSON.stringify(this.listUpdatedText),
        };
        this.httpService.postRequest(url, formData).then((res) => {
          this.newEntityId = res._id;
          console.log(res);
        });
      }
    },
    updateNewEntity(item) {
      let url = searchApi.newEntity.update;
      url = url.replace("{{index_key}}", item.key);
      url = url.replace("{{id}}", this.newEntityId);
      const formData = {
        meta: JSON.stringify(this.listUpdatedText),
      };
      this.httpService.postRequest(url, formData).then((res) => {
        // this.newEntityId = res._id;
        console.log("update", res);
      });
    },
  },
};
</script>
<style lang="scss">
main {
  //   background-color: red;
  margin-right: 6em;
  height: 100dvh;
  header {
    height: 6em;
    // background-color: green;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #a7a098;

    .logo-and-dropdown {
      display: flex;
      align-items: center;
      justify-content: flex-start;

      .dropdown {
        margin-right: 2em;
      }
      .logo {
        width: 40%;
      }
    }
  }
  section {
    height: calc(100dvh - 10em);
    overflow: auto;
    // background-color: aqua;
  }
}
.button-meno {
  font-size: 12px;
  transform: rotate(90deg);
  width: 10px;
  height: 10px;
  margin-top: 15px;
  text-decoration: none;
  span:hover {
    color: #00b6e3;
  }
}
// .select-text {
//   text-align: right;
//   background-color: #fff;
//   font-size: 14px;
//   border-radius: 8px;
//   border-color: #f1f1f1;
//   padding: 6px;
//   &:hover {
//     border-color: #afbac6;
//   }
// }
.component {
  input {
    border-radius: 0.5rem;
    border-color: var(--primary-color);
    font-size: 14px;
    // color: #afbac6;
    &:focus {
      border-color: var(--primary-color);
    }
  }
  label {
    font-size: 15px;
    &:focus {
      border-color: var(--primary-color);
    }
  }
  select {
    border-radius: 0.5rem;
    border-color: var(--primary-color);
    font-size: 14px;
    // color: #afbac6;
    &:focus {
      border-color: var(--primary-color);
    }
  }
  textarea {
    border-radius: 0.5rem;
    border-color: var(--primary-color);
    padding: 1em;
    &:focus {
      border-color: var(--primary-color);
    }
  }
}
.accordion {
  margin: 0 4em;
}
@media (max-width: 575.98px) {
  main {
    margin-right: 0;
    header {
      .logo-and-dropdown {
        .logo {
          display: none;
        }
      }
    }
  }
}
@media only screen and (min-width: 576px) and (max-width: 767.98px) {
  main {
    margin-right: 0;
    header {
      .logo-and-dropdown {
        .logo {
          display: none;
        }
      }
    }
  }
}
@media only screen and (min-width: 768px) and (max-width: 991.98px) {
  main {
    margin-right: 5em;
  }
}
@media only screen and (min-width: 992px) and (max-width: 1199.98px) {
  main {
    margin-right: 5em;
  }
}
@media (min-width: 1200px) {
}
</style>