<template>
  <div class="d-flex flex-column" style="min-height: calc(100dvh - 4em)">
    <div class="container-fluid flex-grow-1 d-flex flex-column">
      <div class="row">
        <div class="col-12 py-3 border-bottom mb-3">
          <div class="row">
            <div class="col-auto">
              <div class="d-flex align-items-center">
                <router-link
                  class="btn btn-primary"
                  :to="{
                    name: 'lawDraftList',
                  }"
                >
                  <svg class="icon icon-forward-2">
                    <use xlink:href="#icon-forward-2"></use>
                  </svg>
                  بازگشت
                </router-link>
                <div class="d-flex flex-column align-items-start me-2">
                  <h4 class="m-0">
                    {{ "ثبت " + draftActiveSchemaGetter?.label }}
                  </h4>
                  <p
                    v-if="draftActiveSchemaGetter?.tabs?.length"
                    class="text__light text__13 d-none d-md-block mb-0"
                  >
                    شما در مرحله ({{
                      draftActiveSchemaGetter?.tabs[currentStep].title
                    }})هستید.
                  </p>
                </div>
              </div>
            </div>
            <div class="col" v-if="Boolean(entity?.islock)">
              <div class="d-flex">
                <div class="alert alert-warning mb-0 py-1" role="alert">
                  داده جاری به دلیل ثبت نهایی قفل شده است و قابل تغییر نمی باشد.

                  <button
                    @click.prevent="unlockLawModal"
                    class="btn btn-primary me-3"
                  >
                    بازکردن کردن قفل
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="col-12 steps-and-prev-next-box">
          <div class="row align-items-center">
            <div class="col-auto">
              <button
                @click.prevent="prevStep"
                type="button"
                class="btn btn-primary"
              >
                <svg class="icon icon-Component-71--1">
                  <use xlink:href="#icon-Component-71--1"></use>
                </svg>
                قبلی
              </button>
            </div>
            <div class="col">
              <wizard
                :currentStepProp="currentStep"
                :steps="draftActiveSchemaGetter?.tabs"
                @step-changed="onStepChanged"
              ></wizard>
              <p
                v-if="draftActiveSchemaGetter?.tabs?.length"
                class="text__light text__13 d-block d-md-none d-flex justify-content-center mt-2"
              >
                شما در مرحله ({{
                  draftActiveSchemaGetter?.tabs[currentStep].title
                }})هستید.
              </p>
            </div>
            <div class="col-auto">
              <button
                @click.prevent="nextStep"
                type="button"
                class="btn btn-primary"
                
              >
                <svg class="icon icon-Component-71--1" style="transform: rotate(180deg);">
                  <use xlink:href="#icon-Component-71--1"></use>
                </svg>
                بعدی
              </button>
            </div>
          </div>
        </div>
      </div>
      <div class="row flex-grow-1 overflow-auto mt-md-5">
        <div class="col">
          <component
            :key="renderComponent"
            :formElements="formElements"
            :entity="entity"
            :entityProp="entity"
            :is="activeComponent"
            @saveProperty="saveProperty"
            @lock-component="lockComponent"
            ref="formRef"
          ></component>
        </div>
      </div>
    </div>
    <!-- <div class="row">
      <div class="col-12 d-flex justify-content-between border-top mt-2">
        <div class="col-auto align-self-end mt-3">
          <button
            @click.prevent="prevStep"
            type="button"
            class="btn btn-primary"
          >
            <svg class="icon icon-Component-71--1">
              <use xlink:href="#icon-Component-71--1"></use>
            </svg>
            قبلی
          </button>
        </div>
        <div class="col-auto align-self-end mt-3">
          <button
            @click.prevent="nextStep"
            type="button"
            class="btn btn-primary"
          >
            <svg class="icon icon-Component-71--2">
              <use xlink:href="#icon-Component-71--2"></use>
            </svg>
            بعدی
          </button>
        </div>
      </div>
    </div> -->
  </div>
</template>

<script>
import { mapState, mapActions } from "pinia";

import entityApi from "~/apis/entityApi";
import repoApi from "~/apis/repoApi";

export default {
  props: {
  },
  beforeMount() {
    this.httpService = new HttpService(import.meta.env.VITE_BASE_URL);
  },
  mounted() {
    let schemaExist = typeof this.draftSchemaGetter == "object";

    if (!schemaExist) {
      this.getSchemas().then(() => {
        this.initData();
      });
    } else {
      this.initData();
    }

    if (window.outerWidth < 992) {
      this.$store.commit("TOGGLE_SIDEBAR_MENU");
    }

    // setDocumentTitle();
  },
  data() {
    return {
      currentStep: 0,
      httpService: undefined,
      activeComponent: "",
      entity: {},
      data_changed: {},
      renderComponent: 1,
    };
  },
  computed: {
    ...mapState([
      "organNameGetter",
    ]),
    ...mapState("entity", [
      "draftSchemaGetter",
      "draftActiveSchemaGetter",
      "draftActiveStepGetter",
    ]),
    ...mapState(["isSidebarCollapsed", "currentUser"]),
    sidbarMenu() {
      if (isMajlesBuild()) return this.sidbarMenuMajles;
      else return this.sidbarMenuDefault;
    },
    formElements() {
      if (
        this.draftActiveSchemaGetter &&
        this.draftActiveSchemaGetter.tabs &&
        this.draftActiveSchemaGetter.tabs.length
      )
        return this.draftActiveSchemaGetter?.tabs[this.currentStep].items;
      return [];
    },
  },
  methods: {
    ...mapActions("entity", [
      "SET_ITEM_ENTITY",
      "draftSchemaSetter",
      "draftActiveSchemaSetter",
      "draftActiveStepSetter",
    ]),
    ...mapActions(["TOGGLE_PANEL"]),

    lockComponent(islock = 1){
      this.entity["islock"]=islock;
      // console.log(islock)
      // console.log(this.entity)
      // islock
      this.renderComponent++;
    },
    unlockLawModal() {
      const html =
        "با این عملیات، شما تمامی داده های مرتبط با این قانون و آثار تنقیحی آن را از مخزن اصلی حذف کرده و به مرحله قبل ثبت نهایی می رسانید. آیا مطئن به حذف داده های مذکور از مخزن اصلی هستید ؟!";
      this.mySwalConfirm({
        title: "هشدار!!!",
        html: html,
        icon: "error",
      }).then((result) => {
        if (result.isConfirmed) {
          this.unlockLaw();
        }
      });
    },
    async unlockLaw() {
      let to_key = this.draftActiveStepGetter?.to_index_key;

      let url = "";
      url = repoUrl() + repoApi.entity.draftUnlock;
      url = url.replace("{{appname}}", buildName());
      url = url.replace("{{index_key}}", this.draftActiveStepGetter.key);
      url = url.replace("{{entity_id}}", this.entity?._id);
      url = url.replace("{{to_index_key}}", to_key);

      return await this.httpService
        .postRequest(url, {})
        .then((res) => {
          this.entity = res._source;
          this.entity["_id"] = res._id;
          this.entity["id"] = res._id;
          this.renderComponent++;

          this.mySwalToast({
            html: res?.message ?? "با موفقیت عملیات انجام شد .",
          });
        })
        .catch((err) => {
          this.fetchingData = false;
          return err;
        });
    },
    initData() {
      let ativeSchema = this.draftSchemaGetter.find(
        (item) => item.key == "new"
      );

      this.draftActiveSchemaSetter(ativeSchema);
      this.draftActiveStepSetter(ativeSchema.tabs[this.currentStep]);
      this.getEntityInfo();
    },
    // /**
    //  * دریافت اطلاعات موجودیت بر اساس نوع و شناسه آن.
    //  * @param {String} _entityType - نوع موجودیت.
    //  * @param {String} _entityId - شناسه موجودیت.
    //  */

    getEntityInfo() {
      if (this.fetchingData) return;
      this.fetchingData = true;

      let id = this.$route.params?.id;

      if (!id) {
        this.entity = {};
        this.currentStep = 0;
        this.fetchingData = false;
        this.onStepChanged(
          this.draftActiveSchemaGetter?.tabs[this.currentStep]
        );
        this.renderComponent++;
        return;
      }

      // let key = this.$route.params.key;
      let key = this.draftActiveSchemaGetter?.index_key;

      let url = repoUrl() + repoApi.public.get;
      url = url.replace("{{index_key}}", key);
      url = url.replace("{{entity_id}}", id);

      this.httpService.getRequest(url).then((res) => {
        this.entity = res._source;
        this.entity["_id"] = res._id;
        this.entity["id"] = res._id;

        this.currentStep = this.entity.step;
        this.fetchingData = false;

        this.onStepChanged(
          this.draftActiveSchemaGetter?.tabs[this.currentStep]
        );
        this.renderComponent++;
      });
    },

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

      let dataChanged = {};
      if (!this.$refs.formRef?.isChanged())
        dataChanged["step"] = this.currentStep;
      else {
        dataChanged = this.$refs.formRef.formData;
        dataChanged["step"] = this.currentStep;
      }

      //  اگر تغییری نداشته باشیم، meta به صورت "{}" خواهد بود.
      if (!dataChanged && !JSON.stringify(dataChanged).length > 2) return;

      let id = this.$route.params.id ?? this.entity._id;

      // if (this.$route.params.id) {
      // id = this.$route.params.id ?? undefined;
      // } else id = this.entity._id ?? undefined;

      let url = "";
      if (id) {
        url = repoUrl() + repoApi.public.updateEntity;
        url = url.replace("{{id}}", id);
      } else {
        url = repoUrl() + repoApi.public.addEntity;
        // let r =  Math.random() * (99);
        // id = "df" + new Date().toLocaleDateString("fa-IR") + r
      }

      let key = this.draftActiveSchemaGetter?.index_key;
      url = url.replace("{{index_key}}", key);

      let formData = dataChanged;

      return await this.httpService
        .postRequest(url, formData)
        .then((res) => {
          this.entity = res._source;
          this.entity["_id"] = res._id;
          this.entity["id"] = res._id;

          this.mySwalToast({
            html: res?.message ?? "با موفقیت ثبت شد.",
          });
          this.fetchingData = false;
          return true;
        })
        .catch((err) => {
          this.fetchingData = false;
          return err;
        });
    },
    nextStep() {
      let step = this.currentStep + 1;
      if (step >= this.draftActiveSchemaGetter?.tabs.length) return;
      if (!this.draftActiveSchemaGetter?.tabs[step]) return;

      if (this.currentStep == 1) {
        this.$refs.formRef?.setLastChangedData();
      }

      if (
        this.$refs.formRef?.isChanged() &&
        this.currentStep != 2 &&
        this.currentStep < this.entity.step
      ) {
        this.mySwalConfirm({
          title: "هشدار!!!",
          html: `با تغییراتی که در اطلاعات این مرحله دادید، چنانچه در مراحل بعدی قبلا تغییر داشتید ، ممکن است  از دست  برود `,
          icon: "warning",
        }).then((result) => {
          if (result.isConfirmed) {
            this.currentStep = step;
            this.saveProperty().then(() => {
              this.onStepChanged(this.draftActiveSchemaGetter?.tabs[step]);
            });
          }
        });
      } else {
        this.currentStep = step;
        this.saveProperty().then(() => {
          this.onStepChanged(this.draftActiveSchemaGetter?.tabs[step]);
        });
      }
    },
    prevStep() {
      let step = this.currentStep - 1;
      if (step < 0) return;

      if (this.draftActiveSchemaGetter?.tabs[step])
        this.onStepChanged(this.draftActiveSchemaGetter?.tabs[step]);
    },
    onStepChanged(stepItem) {
      console.log(stepItem)
      if (!stepItem) return;
      this.activeComponent = stepItem.componentName;
      this.currentStep = stepItem.step;
      this.draftActiveStepSetter(stepItem);
    },

    /**
     * دریافت اطلاعات schema.
     */
    async getSchemas() {
      let url = repoUrl() + entityApi.schema.list;

      return await this.httpService
        .postRequest(url, {
          organ: this.organNameGetter,
          system: "edit",
        })
        .then((response) => {
          // console.log(response.data.edit);
          this.draftSchemaSetter(response.data.edit);
          let sch = response.data.edit.find((item) => item.key == "new");
          if (sch) this.draftActiveSchemaSetter(sch);
          // this.draftActiveSchemaSetter(response.data.edit[0]);
        })
        
    },
    /**
     * تغییر وضعیت نمایش منوی سایدبار.
     */
    toggleSidebarMenu() {
      this.$store.commit("TOGGLE_SIDEBAR_MENU");
    },
  },


};
</script>
<style scoped lang="scss">
.nav-tabs-container {
  display: flex;
  justify-content: center;
}
.filter-list-container {
  // padding-top: 0.5em;
  // // position: fixed;

  // z-index: 9;
  // width: 20em;
  height: 100dvh;
  .main-filter {
    display: none;
  }
  .mobile-mode {
    display: flex;
    justify-content: flex-end;

    .btn {
      border-radius: 50%;
      // font-size: 0.7rem;
      width: 2.5em;
      height: 2.5em;
      box-shadow: 0px 0px 7px 1px #eee;
      display: flex;
      justify-content: center;
      align-items: center;
      transform: translateX(1.5em);
      background-color: #eee;

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

  &.expanded {
    top: 0;
    bottom: 0;
    background: #fff;
    justify-content: center;
    box-shadow: -1px 0px 7px 1px #eee;
    width: 20em;
    .main-filter {
      display: block;
    }
  }
}
.main-filter {
  padding: 0 1em;
  overflow: auto;
}
.component_page {
  height: calc(100dvh - 11em);
  overflow: auto;
  padding-left: 1em;
  overflow-x: hidden;
}
.steps-and-prev-next-box {
  padding: 1em 1em 2.5em 1em;
  box-shadow: 0px 5px 8px 4px #eee;
  border-radius: 1em;
}
</style>