<template>
  <div class="main-page container-fluid">
    <div class="row d-flex justify-content-center">
      <div class="col-12 main-page_header d-flex">
        <!-- <SelectTemplate class="col-sm-12 col-md-2  task-Form-category">

        </SelectTemplate> -->
        <div class="col-12 main-page_date mt-3 d-flex align-items-center">
          <div class="flex-grow-1">
            <h4 class="main-page_date-daysweek m-0">{{ weekDay }}</h4>
            <div class="d-flex justify-content-center">
              <div class="row d-flex justify-content-center">
                <div class="main-page_date-icon-right col-auto px-1">
                  <span class="d-flex btn" title="روز بعد" @click="nextDay()">
                    <svg class="icon icon-Component-358--1">
                      <use xlink:href="#icon-Component-358--1"></use>
                    </svg>
                    <span class="nextDay">بعدی</span>
                  </span>
                </div>
                <div class="form-outline day col-auto px-1 coolinput">
                  <label class="form-label text" for="typeNumber">روز:</label>
                  <input
                    name="input"
                    v-model.number="workDay"
                    min="0"
                    max="32"
                    placeholder="--"
                    type="number"
                    id="typeNumber"
                    class="main-page_date form-control input"
                  />
                </div>
                <div class="form-outline form-outline2 col-auto px-1 coolinput">
                  <label class="form-label text" for="typeNumber">ماه:</label>
                  <input
                    v-model.number="workMonth"
                    min="01"
                    max="12"
                    placeholder="--"
                    type="number"
                    id="typeNumber"
                    class="main-page_date form-control input"
                  />
                </div>
                <div class="form-outline year col-auto px-1 coolinput">
                  <label class="form-label text" for="typeNumber">سال:</label>
                  <input
                    min="1400"
                    v-model.number="workYear"
                    placeholder="14--"
                    type="number"
                    id="typeNumber"
                    class="main-page_date form-control input"
                  />
                </div>
                <div class="main-page_date-icon-left col-auto px-1">
                  <span class="d-flex btn" title="روز قبل" @click="prevDay()">
                    <span class="prevDay">قبلی</span>
                    <svg class="icon icon-Component3601">
                      <use xlink:href="#icon-Component3601"></use>
                    </svg>
                  </span>
                </div>
              </div>
            </div>
          </div>

          <div
            v-can="'times_user_search'"
            class="coolinput select-template d-flex align-items-center mb-2 mb-md-0 ms-lg-2"
          >
            <label class="multiselect-lable text no-wrap width-auto" for="users"
              >جستجوی کاربر:</label
            >
            <multiselect
              class="multiselect template form-control input w-auto"
              id="users"
              track-by="user_id"
              placeholder="جستجوی..."
              v-model="selectedUser"
              :show-labels="false"
              :options="foundUsers"
              :searchable="true"
              :preserve-search="true"
              :internal-search="false"
              :clearOnSelect="false"
              :clear-on-select="false"
              :close-on-select="true"
              :options-limit="300"
              :limit="3"
              :limit-text="limitText"
              :max-height="350"
              :customLabel="
                (item) => {
                  return `${item.first_name} ${item.last_name}`;
                }
              "
              @search-change="asyncFind"
              @select="addUserToGroup"
              @close="resetFoundUsers"
            >
            </multiselect>
          </div>
          <!-- <div class="coolinput select-template d-flex align-items-center">
            <label class="multiselect-lable text" for="input">نوع قالب</label>
            <multiselect
              class="multiselect template form-control input w-auto"
              v-model="templateValue"
              :options="multiSelectOptions"
              :max-height="250"
              @select="setTagTemplate"
              label="name"
              track-by="title"
            ></multiselect>
          </div> -->
        </div>
      </div>
    </div>

    <div class="main-page_body">
      <div class="main-page_body-form-outline">
        <hours-form
          v-for="(hourswork, index) in hoursForms"
          :key="index"
          :itemIndex="index"
          :hourswork="hourswork"
          :hoursFormsLenght="hoursForms.length"
          @add-new-record="openFormHoursInformation(index)"
          @delete-form-hours="deleteFormHoursInformation(index)"
          @save-form-hours="saveHoursWork(hourswork, index)"
        ></hours-form>
      </div>

      <div class="overlay3 overlay3-entrance1 3-entrance2 3-entrance3">
        <div class="main-page_body-items labels d-flex align-items-center">
          <label
            v-if="templateValue.title == 'multi-org_workbase'"
            class="col-1 label-0"
            style="background-color: #97f295 !important"
            >سازمان</label
          >
          <label class="col-2 label-1">*دسته</label>
          <label class="col-3 label-2">*عنوان</label>
          <label class="col-1 label-3">*مدت</label>
          <label class="col-4 label-Description">چالش،پیشنهاد،توضیح</label>
        </div>
      </div>
      <div class="tasks_form">
        <task-form
          v-for="(taskForm, index) in taskForms"
          :key="index"
          :hoursFormsLenght="index"
          :taskForm="taskForm"
          :itemIndex="index"
          :templateValue="templateValue"
          @add-new-record="openFormTaskInformation()"
          @close-form-tasks="closeFormTaskInformation(taskForm.id, index)"
          @save-form-tasks="postInTaskWork"
        ></task-form>
      </div>
      <div
        class="main-page_body-items record d-flex justify-content-center align-items-center col-12"
      >
        <span
          title="رکورد جدید"
          @click="openFormTaskInformation()"
          class="btn main-page_body-items-icon-record align-items-center"
        >
          <svg class="icon icon-Component-133--1">
            <use xlink:href="#icon-Component-133--1"></use>
          </svg>
          <span class="main-page_body-items-text-record">رکورد جدید</span>
        </span>
      </div>
      <div class="main-page_body-items total d-flex align-items-center col-12">
        <label class="col total-all-text"
          >جمع کل : <span class="total-all-number ms-3">{{ sum }}</span></label
        >

        <label class="col indecisive"
          >بلاتکلیف : <span class="indecisive-number">{{ noWork }}</span></label
        >
        <div class="main-page_body-items-move-copy in-desktop mt-2">
          <div class="btn-move move ms-3">
            <PersianDatepicker
              title="انتقال"
              label="انتقال محتوا به تاریخ دیگر"
              class="date-picker text-move"
              v-model="dateValueMove"
              format="YYYY-MM-DD"
              display-format="jYYYY-jMM-jDD"
              @input="PostDateToMoveInformation()"
            />
            <span class="svgIcon-move" title="انتقال">
              <svg class="icon icon-forward">
                <use xlink:href="#icon-forward"></use>
              </svg>
            </span>
          </div>
          <div class="copy btn-copy">
            <PersianDatepicker
              title="کپی"
              label="کپی محتوا به تاریخ دیگر"
              class="date-picker text-copy"
              v-model="dateValueCopy"
              format="YYYY-MM-DD"
              display-format="jYYYY-jMM-jDD"
              @input="PostDateToCopyInformation()"
            />
            <span class="svgIcon-copy" title="کپی">
              <svg class="icon icon-copy2">
                <use xlink:href="#icon-copy2"></use>
              </svg>
            </span>
          </div>
        </div>
        <div class="main-page_body-items-move-copy in-mobile mt-2">
          <div class="btn-move move ms-3">
            <PersianDatepicker
              title="انتقال"
              label="انتقال"
              class="date-picker text-move"
              v-model="dateValueMove"
              format="YYYY-MM-DD"
              display-format="jYYYY-jMM-jDD"
              @input="PostDateToMoveInformation()"
            />

            <span class="svgIcon-move" title="انتقال">
              <svg class="icon icon-forward">
                <use xlink:href="#icon-forward"></use>
              </svg>
            </span>
          </div>
          <div class="copy btn-copy">
            <PersianDatepicker
              title="کپی"
              label="کپی"
              class="date-picker text-copy"
              v-model="dateValueCopy"
              format="YYYY-MM-DD"
              display-format="jYYYY-jMM-jDD"
              @input="PostDateToCopyInformation()"
            />
            <span class="svgIcon-copy" title="کپی">
              <svg class="icon icon-copy2">
                <use xlink:href="#icon-copy2"></use>
              </svg>
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// import ImageUploader from "vue-image-upload-resize";
// import keyValueApi from "@apis/keyValueApi";
// import { mapActions, mapGetters, mapMutations } from "vuex";
import taskApi from "@task/apis/taskApi";
// import HttpService from "@services/httpService";
// import VuePersianDatetimePicker from "vue-persian-datetime-picker";
import { p2e } from "@plugins/persianNumber";
// import { mapGetters, mapMutations } from "vuex";
import { mapState, mapActions } from "pinia";
import { useAuthStore } from "~/stores/authStore";

export default {
  beforeMount() {
    // this.httpService = new HttpService();
    this.httpService = useNuxtApp()["$http"];
  },
  mounted() {
    this.setCurrentUserData();

    var d = new Date().toLocaleDateString("fa-IR");
    let items = d.split("/");

    let year = p2e(items[0]);
    let month = p2e(items[1]);
    let day = p2e(items[2]);
    let weekDay = new Date().toLocaleDateString("fa-IR", { weekday: "short" });
    this.setDate(day, month, year, weekDay);

    this.getDetailsDay();
    

    if(this.taskSchemaGetter?.organTypeOptions){
      this.multiSelectOptions = this.taskSchemaGetter?.organTypeOptions;
      this.templateValue = this.taskSchemaGetter?.organTypeOptions[0];
    }

  },

  data() {
    return {
      httpService: {},
      foundUsers: [],
      selectedUser: {
        id: undefined,
        user_id: undefined,
        first_name: undefined,
        last_name: undefined,
        username: undefined,
        full_name: undefined,
        avatar: undefined,
        color: undefined,
      },
      multiSelectOptions: [],
      templateValue: {
        name: "تک سازمانی - کارمحور",
        title: "single-org_workbase",
      },
      hoursForms: [
        {
          inTime: "",
          outTime: "",
          noWorkTime: "",
        },
      ],
      taskForms: [
        {
          organ: "",
          category: "",
          title: "",
          duration: "",
          description: "",
        },
      ],
      inTime: "",
      outTime: "",
      noWorkTime: "",
      workDay: "",
      workMonth: "",
      workYear: "",
      weekDay: "",
      // useFullTime: "",
      // allTime: "",
      taskId: "",
      noWork: "",
      sum: "",
      itemsId: "",
      loading: false,
      hoursformCount: 1,
      isMultiOrgan: false,
      dateValueCopy: "",
      dateValueMove: "",
    };
  },
  computed: {
    ...mapState(useAuthStore,["currentUser", "taskSchemaGetter"]),
  },
  methods: {
    setCurrentUserData() {
      this.selectedUser = {
        id: this.currentUser.user_id,
        user_id: this.currentUser.user_id,
        first_name: this.currentUser.user_data.first_name,
        last_name: this.currentUser.user_data.last_name,
        username: this.currentUser.user_data.username,
        full_name: null,
        avatar: this.currentUser.user_data.username,
        color: null,
      };
    },
    limitText(count) {
      return `و ${count} کاربر دیگر`;
    },
    asyncFind(query) {
      const url = this.loginMicroServiceName + "/user/suggestion";

      if (query.trim().length) {
        this.httpService.postRequest(url, { query }).then((response) => {
          this.foundUsers = response.data ?? [];
        });
      }
    },
    addUserToGroup(selectedUser) {
      this.$root.$emit("request-based-on-new-user-data", selectedUser.id);
    },
    resetFoundUsers() {
      // this.foundUsers = [];
      // this.fetchingData = false;
    },
    getDetailsDay() {
      this.hoursForms = [];
      let payload = {
        user_id: this.selectedUser.user_id,
      };
      const url = this.taskMicroServiceName + taskApi.workingHours.day;

      if (this.workDay) {
        payload.taskDate =
          this.workYear + "-" + this.workMonth + "-" + this.workDay;
      }

      this.httpService.postRequest(url, payload).then((res) => {
        if (res.hourswork?.length) {
          this.hoursForms = res.hourswork;
          this.itemsId = res.task_id;
        } else
          this.hoursForms.push({
            inTime: null,
            outTime: null,
            noWorkTime: null,
          });

        this.taskForms = res.data;
        this.taskForms.push({
          organ: "",
          category: "",
          title: "",
          duration: "",
          description: "",
        });
        this.noWork = res.day_sum.noWork;
        this.sum = res.day_sum.sum;

        let { day, month, year, weekDay } = res;
        this.setDate(day, month, year, weekDay);
      });
    },
    setDate(day, month, year, weekDay) {
      this.weekDay = weekDay;
      this.workDay = day;
      this.workMonth = month;
      this.workYear = year;
    },

    // openFormHoursInformation(index) {

    //   if (
    //     this.hoursForms[index].inTime !== null &&
    //     this.hoursForms[index].outTime !== null &&
    //     this.hoursForms[index].noWorkTime !== null
    //   ) {
    //     this.hoursForms.push({
    //       inTime: "",
    //       outTime: "",
    //       noWorkTime: "",
    //     });
    //     this.saveHoursWork();
    //   }
    // },
    openFormHoursInformation(index) {
      this.hoursformCount++;

      this.hoursForms.push({
        inTime: "",
        outTime: "",
        noWorkTime: "",
      });
    },
    deleteFormHoursInformation(index) {
      this.hoursformCount--;

      const url = this.taskMicroServiceName + taskApi.workingHours.deleteHours;
      let payload = { id: this.itemsId, index: this.hoursForms[index].index ?? (index + 1) };
      if (
        this.hoursForms[index].inTime != "" ||
        this.hoursForms[index].outTime != ""
      ) {
        this.mySwalConfirm({
          title: "هشدار!!!",
          html: "از حذف این مورد مطمئن هستید؟",
        }).then((result) => {
          if (result.isConfirmed) {
            this.httpService.postRequest(url, payload).then((response) => {
              this.getDetailsDay();
              this.mySwalToast({
                title: "تبریک",
                html: "مورد با موفقیت حذف شد",
                icon: "success",
              });
            });
          }
        });
      } else {
        this.hoursForms.splice(index, 1);
      }
    },
    openFormTaskInformation() {
      // if (this.itemsId == "") {
      //   this.saveHoursWork(this.hoursForms[0], 0, false);
      // }

      this.taskForms.push({
        organ: "",
        category: "",
        title: "",
        duration: "",
        description: "",
      });
    },
    closeFormTaskInformation(taskFormsId, index) {
      const url = this.taskMicroServiceName + taskApi.workingHours.delete;
      const payload = { id: taskFormsId };

      if (taskFormsId) {
        this.mySwalConfirm({
          title: "هشدار!!!",
          html: "از حذف این مورد مطمئن هستید؟",
        }).then((result) => {
          if (result.isConfirmed) {
            this.httpService.postRequest(url, payload).then((response) => {
              this.getDetailsDay();
              this.mySwalToast({
                title: "تبریک",
                html: "مورد با موفقیت حذف شد",
                icon: "success",
              });
            });
          }
        });
      } else if (
        this.taskForms[index].organ != "" ||
        this.taskForms[index].category != "" ||
        this.taskForms[index].duration != "" ||
        this.taskForms[index].title != ""
      ) {
        this.mySwalConfirm({
          title: "هشدار!!!",
          html: "از حذف این مورد مطمئن هستید؟",
        }).then((result) => {
          if (result.isConfirmed) {
            this.taskForms.splice(index, 1);
            this.mySwalToast({
              title: "تبریک",
              html: "مورد با موفقیت حذف شد",
              icon: "success",
            });
          }
        });
      } else {
        this.taskForms.splice(index, 1);
      }
    },
    validTime(value) {
      const regex = /^\d{1,2}:\d{1,2}$/gm;
      let isValid = value.match(regex);
      return isValid;
    },
    timeCorrect(value) {
      if (value == null) return value;
      value = value.trim();
      value = value.replace(".", ":");
      value = value.replace(" ", ":");

      if (value.indexOf(":") == -1) {
        if (value.length == 0) value = "00:00";
        else if (value.length == 1) value = "0" + value + ":00";
        else if (value.length == 2) value = value + ":00";
        else if (value.length == 3)
          value = "0" + value.substring(0, 1) + ":" + value.substring(1);
        else if (value.length == 4)
          value =
            value.substring(0, 2) + ":" + value.substring(2).padStart(2, "0");
        else if (value.length > 4)
          value = value.substring(0, 2) + ":" + value.substring(2, 2);
      }
      return value;
    },
    saveHoursWork(hourswork, index, refreshPage = true) {
      if (!this.validTime(hourswork.inTime)) {
        if (!hourswork.inTime) hourswork.inTime = "00:00";
        hourswork.inTime = timeCorrect(hourswork.inTime);
      }
      if (!this.validTime(hourswork.outTime)) {
        if (!hourswork.outTime) hourswork.outTime = "00:00";
        hourswork.outTime = timeCorrect(hourswork.outTime);
      }
      if (!this.validTime(hourswork.noWorkTime)) {
        if (!hourswork.noWorkTime) hourswork.noWorkTime = "00:00";
        hourswork.noWorkTime = timeCorrect(hourswork.noWorkTime);
      }

      const payload = {
        taskDate: this.workYear + "-" + this.workMonth + "-" + this.workDay,
        inTime: hourswork.inTime ?? "00:00",
        outTime: hourswork.outTime ?? "00:00",
        noWorkTime: hourswork.noWorkTime ?? "00:00",
        index: index + 1,
      };

      const url = this.taskMicroServiceName + taskApi.workingHours.add;
      this.httpService
        .postRequest(url, payload)
        .then((res) => {
          this.itemsId = res.id;

          // let { day, month, year, weekDay } = res;
          // this.setDate(day, month, year, weekDay);

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

        .finally(() => {
          // if (refreshPage) this.getWorkingHours(false);
          this.getDetailsDay();
        });
    },
    postInTaskWork(taskForm) {
      if (this.loading) return;
      this.loading = true;

      let payload = {
        id: taskForm.id ?? undefined,
        task_id: this.itemsId,
        category: taskForm.category,
        organ: taskForm.organ,
        title: taskForm.title,
        duration: taskForm.duration,
        description: taskForm.description,
      };

      let url = taskForm.id
        ? taskApi.workingHours.taskEdit
        : taskApi.workingHours.taskAdd;

      url = this.taskMicroServiceName + url;

      this.httpService
        .postRequest(url, payload)
        .then((res) => {
          this.mySwalToast({
            title: res.message,
          });

          this.getDetailsDay();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    setWorkDay(value) {
      this.workDay = 26;
    },
    nextDay(nextDay) {
      this.workDay += 1;
      this.getDetailsDay();
    },
    prevDay(prevDay) {
      if (this.workDay > 1) this.workDay -= 1;
      else {
        if (this.workMonth == 1) {
          this.workMonth = 12;
          this.workYear -= 1;
        } else {
          this.workMonth -= 1;
        }

        if (this.workMonth == 12) this.workDay = 29;
        else if (this.workMonth > 6) this.workDay = 30;
        //if(this.workMonth < 6)
        else this.workDay = 31;
      }

      this.getDetailsDay();
    },
    setCurrentDate(date) {
      this.workDay = date.day;
      this.workMonth = date.month;
      this.workYear = date.year;

      this.getDetailsDay();
    },
    setTagTemplate(newTag) {
      this.templateValue = newTag;
    },
    datefa(item) {
      var m = item;
      var d = new Date(m).toLocaleDateString("fa-IR");
      return d;
    },
    PostDateToMoveInformation() {
      let oldDateMove =
        this.workYear + "/" + this.workMonth + "/" + this.workDay;
      let newDateMove = this.datefa(this.dateValueMove);
      let payload = {
        user_id: this.$store.getters.currentUser.user_id,
        oldDate: oldDateMove,
        newDate: newDateMove,
        id: this.itemsId,
      };
      let payloadReplace = {
        user_id: this.$store.getters.currentUser.user_id,
        oldDate: oldDateMove,
        newDate: newDateMove,
        id: this.itemsId,
        replace: 1,
        append: 0,
      };
      let payloadAppend = {
        user_id: this.$store.getters.currentUser.user_id,
        oldDate: oldDateMove,
        newDate: newDateMove,
        id: this.itemsId,
        replace: 0,
        append: 1,
      };
      const url = this.taskMicroServiceName + taskApi.workingHours.move;
      this.mySwalConfirm({
        title: "هشدار!!!",
        html:
          "آیا از انتقال موارد از تاریخ:" +
          " " +
          "«" +
          oldDateMove +
          "»" +
          " " +
          "به تاریخ:" +
          " " +
          "«" +
          newDateMove +
          "»" +
          " " +
          "مطمئن هستید؟",
      }).then((result) => {
        if (result.isConfirmed) {
          this.httpService.postRequest(url, payload).then((response) => {
            // console.log(response);
            if (response?.check_replace == 1) {
              this.mySwalConfirm({
                title: "هشدار!!!",
                html: "برای این تاریخ موارد مشابه وجود دارد آیا مایل به اضافه یا جایگزینی هستید؟",
                showDenyButton: true,
                showCancelButton: true,
                confirmButtonText: "جایگزین",
                denyButtonText: `اضافه`,
              }).then((result) => {
                if (result.isConfirmed) {
                  this.httpService
                    .postRequest(url, payloadReplace)
                    .then((response) => {});
                  this.mySwalToast({
                    title: "تبریک",
                    html: "محتوا با موفقیت جایگزین شد",
                    icon: "success",
                  });
                  this.getDetailsDay();
                } else if (result.isDenied) {
                  this.httpService
                    .postRequest(url, payloadAppend)
                    .then((response) => {});
                  this.mySwalToast({
                    title: "تبریک",
                    html: "محتوا با موفقیت اضافه شد",
                    icon: "success",
                  });
                  this.getDetailsDay();
                }
              });
            } else {
              this.mySwalToast({
                title: "تبریک",
                html: "محتوا با موفقیت منتقل شد",
                icon: "success",
              });
              this.getDetailsDay();
            }
          });
        }
      });
    },
    PostDateToCopyInformation() {
      let oldDateCopy =
        this.workYear + "/" + this.workMonth + "/" + this.workDay;
      let newDateCopy = this.datefa(this.dateValueCopy);
      let payload = {
        user_id: this.$store.getters.currentUser.user_id,
        oldDate: oldDateCopy,
        newDate: newDateCopy,
        id: this.itemsId,
      };
      let payloadReplace = {
        user_id: this.$store.getters.currentUser.user_id,
        oldDate: oldDateCopy,
        newDate: newDateCopy,
        id: this.itemsId,
        replace: 1,
        append: 0,
      };
      let payloadAppend = {
        user_id: this.$store.getters.currentUser.user_id,
        oldDate: oldDateCopy,
        newDate: newDateCopy,
        id: this.itemsId,
        replace: 0,
        append: 1,
      };
      const url = this.taskMicroServiceName + taskApi.workingHours.copy;
      this.mySwalConfirm({
        title: "هشدار!!!",
        html:
          "آیا از کپی موارد از تاریخ:" +
          " " +
          "«" +
          oldDateCopy +
          "»" +
          " " +
          "به تاریخ:" +
          " " +
          "«" +
          newDateCopy +
          "»" +
          " " +
          "مطمئن هستید؟",
      }).then((result) => {
        if (result.isConfirmed) {
          this.httpService.postRequest(url, payload).then((response) => {
            if (response?.check_replace == 1) {
              this.mySwalConfirm({
                title: "هشدار!!!",
                html: "برای این تاریخ موارد مشابه وجود دارد آیا مایل به اضافه یا جایگزینی هستید؟",
                confirmButtonText: "جایگزین",
                denyButtonText: `اضافه`,
              }).then((result) => {
                if (result.isConfirmed) {
                  this.httpService
                    .postRequest(url, payloadReplace)
                    .then((response) => {});
                  this.mySwalToast({
                    title: "تبریک",
                    html: "محتوا با موفقیت جایگزین شد",
                    icon: "success",
                  });
                  this.getDetailsDay();
                } else if (result.isDenied) {
                  this.httpService
                    .postRequest(url, payloadAppend)
                    .then((response) => {});
                  this.mySwalToast({
                    title: "تبریک",
                    html: "محتوا با موفقیت اضافه شد",
                    icon: "success",
                  });
                  this.getDetailsDay();
                }
              });
            } else {
              this.mySwalToast({
                title: "تبریک",
                html: "موارد با موفقیت کپی شد",
                icon: "success",
              });
              this.getDetailsDay();
            }
          });
        }
      });
    },
  },
  components: {
    TaskForm: () => import("@task/components/TaskForm"),
    HoursForm: () => import("@task/components/HoursForm"),

    Multiselect: () => import("vue-multiselect"),
    datePicker: VuePersianDatetimePicker,
  },
};
</script>

<style lang="scss"></style>
