<template>
  <div class="menu-bar__content home-list p-3">
    <div class="home-list-header">
      <div class="d-flex justify-content-between">
        <div class="home-list-header form-control w-30">
          <span class="main-page_total-1_a"> خالص ماهانه :</span
          ><span class="main-page_total-1_b mr-1">{{ useFullTime }}</span>
        </div>
        <div class="home-list-header form-control mr-1 ml-1 w-30">
          <span class="main-page_total-2_a"> کل ماهانه :</span
          ><span class="main-page_total-2_b mr-1">{{ allTime }}</span>
        </div>
        <div class="home-list-header form-control w-30">
          <span class="main-page_total-1_a"> میانگین روزانه:</span
          ><span class="main-page_total-1_b mr-1">{{ dailyAve }}</span>
        </div>
      </div>
      <div class="alert alert-secondary" role="alert">
        <select
          id="month-select"
          class="form-control ml-1"
          v-model="selectedMonth"
          @change="getWorkingHoursInformation()"
        >
          <option v-for="month in months" :key="month" :value="month">
            {{ getPersianMonthName(month) }}
          </option>
        </select>
        <div class="col-1 main-page_date-icon-left">
          <span class="btn" title="ماه قبل" >
            <svg class="icon icon-Component3601">
              <use xlink:href="#icon-Component3601"></use>
            </svg>
          </span>
        </div>
        <select
          id="year-select"
          class="form-control"
          v-model="selectedYear"
          @change="getWorkingHoursInformation()"
        >
          <option v-for="year in years" :key="year" :value="year">
            {{ year }}
          </option>
        </select>
      </div>
    </div>

    <div class="accordion" id="accordionExample">
      <div class="card">
        <div class="card-header col-12">
          <!-- <h2 class="mb-0"> -->
          <button
            class="btn d-flex justify-content-between collapsed w-100 pr-0"
            type="button"
            data-toggle="collapse"
          >
            <span class="card-header_titles text-1 col-3">روز </span>
            <span class="card-header_titles text-2 col-3"> تاریخ </span>
            <span class="card-header_titles text-3 col-3">
              <!-- <span class="card-header_titles-icon">
                <svg class="icon icon-arrow-down">
                  <use xlink:href="#icon-arrow-down"></use>
                </svg>
              </span> -->
              جمع کل</span
            >
            <span class="card-header_titles text-4 col-3">
              <!-- <span class="card-header_titles-icon">
                <svg class="icon icon-arrow-up-1">
                  <use xlink:href="#icon-arrow-up-1"></use>
                </svg>
              </span> -->
              بلاتکلیف</span
            >
            <span class="card-header_titles text-5"></span>
            <i
              class="card-header_titles rotate-icon tavasi tavasi-Component-22--1"
            ></i>
            <!-- </div> -->
          </button>
          <!-- </h2> -->
        </div>
      </div>
    </div>
    <div class="accordion" id="accordionExample">
      <div class="card" v-for="items in list" :key="items.id">
        <div class="card-header col-12" :id="'heading' + items.id">
          <!-- <h2 class="mb-0"> -->
          <button
            class="btn d-flex justify-content-between collapsed w-100 pr-0"
            type="button"
            data-toggle="collapse"
            :data-target="'#collapse' + items.id"
            :aria-controls="'collapse' + items.id"
            @click.stop="selectDate(items)"
            :aria-expanded="isOpenAccordion(items.id)"
          >
            <!-- <div class="card-header_titles"> -->
            <span class="card-header_titles text-1 col-3"
              >{{ getDayOfWeekFromTimestamp(items.taskDate) }}
            </span>
            <span class="card-header_titles text-2 col-3">{{
              items.oldDate
            }}</span>
            <span class="card-header_titles text-3 col-3">
              <!-- <span class="card-header_titles-icon">
                <svg class="icon icon-arrow-down">
                  <use xlink:href="#icon-arrow-down"></use>
                </svg>
              </span> -->
              {{ items.minuteDay }}</span
            >
            <span class="card-header_titles text-4 col-3">
              <!-- <span class="card-header_titles-icon">
                <svg class="icon icon-arrow-up-1">
                  <use xlink:href="#icon-arrow-up-1"></use>
                </svg>
              </span> -->
              {{ items.noWork }}</span
            >
            <span class="card-header_titles text-5">{{
              items.noWorkTime
            }}</span>
            <i
              :class="{ rotated: rotated }"
              class="card-header_titles rotate-icon tavasi tavasi-Component-22--1"
            ></i>
            <!-- </div> -->
          </button>
          <!-- </h2> -->
        </div>

        <div
          v-if="isOpenAccordion(items.id)"
          :id="'collapse' + items.id"
          class="collapse show"
          :aria-labelledby="'heading' + items.id"
          data-parent="#accordionExample"
        >
          <div class="card-body">
            <span class="card-body_items item-1">مدل سازی</span>
            <span class="card-body_items item-2">اجرائیات</span>
            <span class="card-body_items item-3">120</span>
            <span class="card-body_items item-4"></span>
            <span class="card-body_items item-5">{{ items.description }} </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import taskApi from "~/apis/taskApi";
import {  mapState, mapActions } from "pinia";

import VuePersianDatetimePicker from "vue-persian-datetime-picker";
import { p2e } from "~/services/persianNumber";
import thiqatRoutes from "../../../routes/thiqatRoutes";

export default {
  // mixins: [dragDropMoveMixin],
  beforeMount() {
    this.httpService = new HttpService(
      import.meta.env.VITE_BASE_URL + taskUrl()
    );

    this.activeUserId = this.currentUser.user_id;
    // event fired from MainSection.vue.
    // const { $eventBus } = useNuxtApp();
    // $eventBus.on("request-based-on-new-user-data", (userId) => {
    //   this.activeUserId = userId;
    //   this.getWorkingHoursInformation(userId);
    // });
  },
  mounted() {
    var d = new Date().toLocaleDateString("fa-IR");
    let items = d.split("/");

    this.selectedYear = p2e(items[0]);
    this.selectedMonth = p2e(items[1]);

    this.getWorkingHoursInformation();
  },

  data() {
    return {
      months: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"],
      years: ["1400", "1401", "1402", "1403", "1404", "1405"],
      selectedMonth: "0",
      selectedYear: "1402",
      useFullTime: "",
      allTime: "",
      dailyAve: "",
      entranceTime: [],
      departureTime: [],
      uselessTime: [],
      list: [],
      selectedAccordion: null,
      rotated: false,
      activeUserId : undefined,
    };
  },

  computed: {
    // ...mapState([
    //   "isSidebarCollapsed",
    //   "getForwardItem",
    //   "userPermisionGetter",
    //   "getPanelStatus",
    //   "sidebarListStatusGetter",
    // ]),
    ...mapState("list", ["listGetter"]),
    ...mapState(["currentUser"]),
    taskUrl() {
      return import.meta.env.VITE_TASK;
    },
  },
  methods: {
    // ...mapActions([
    //   "TOGGLE_PANEL",
    //   "checkPermissions",
    //   "SET_SIDEBAR_LIST_STATUS",
    // ]),
    // ...mapActions("list", ["SET_LIST"]),

    getWorkingHoursInformation(userId = undefined) {
      const payload = {
        user_id: userId ?? this.activeUserId ,
        offset: 0,
        limit: 50,
        sortby: "taskDate",
        sortorder: "desc",
        year: this.selectedYear,
        month: this.selectedMonth,
      };
      const url = taskApi.workingHours.load;
      this.httpService
        .postRequest(url, payload)

        .then((res) => {
          this.list = res.data;
          this.useFullTime = res.useFullTime;
          this.allTime = res.allTime;
          this.dailyAve = res.dailyAve;
        })
        
    },
    getDetailsMonth() {
      this.hoursForms = [];
      let payload = {};
      const url = taskApi.workingHours.day;

      if (this.workMonth) {
        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;
    },
    datefa(item) {
      let m = item * 1000;
      let d = new Date(m).toLocaleDateString("fa-IR");
      return d;
    },
    getDayOfWeekFromTimestamp(timestamp) {
      let m = timestamp * 1000;
      let d = new Date(m);

      let options = { weekday: "long" };
      let dayOfWeek = new Intl.DateTimeFormat("fa-IR", options).format(d);

      return dayOfWeek;
    },
    toggleAccordion(accordionId) {
      if (this.selectedAccordion === accordionId) {
        this.selectedAccordion = null;
      } else {
        this.selectedAccordion = accordionId;
      }
      this.rotateIcon();
    },

    isOpenAccordion(accordionId) {
      return this.selectedAccordion === accordionId;
    },
    rotateIcon() {
      this.rotated = !this.rotated;
    },
    nextMonth(nextMonth) {
      this.workMonth += 1;
      this.getDetailsDay();
    },
    prevMonth(prevMonth) {
      this.workMonth-= 1;
      this.getDetailsDay();
    },

    
    selectDate(items) {
      if (items.oldDate) {
        let item = items.oldDate.split("-");
        let date = {};
        date.day = item[2];
        date.month = item[1];
        date.year = item[0];

        this.$emit("select-day", date);
      }
    },
    getPersianMonthName(month) {
      const monthNames = [
        "فروردین",
        "اردیبهشت",
        "خرداد",
        "تیر",
        "مرداد",
        "شهریور",
        "مهر",
        "آبان",
        "آذر",
        "دی",
        "بهمن",
        "اسفند",
      ];
      return monthNames[month - 1];
    },
  },

};
</script>
<style scoped lang="scss">
.home-list-header {
  &.form-control {
    padding: 0.175rem 0.35rem !important;
    box-shadow: 0 0.4688rem 2.1875rem rgba(4, 9, 20, 0.03),
      0 0.9375rem 1.4063rem rgba(4, 9, 20, 0.03),
      0 0.25rem 0.5313rem rgba(4, 9, 20, 0.03),
      0 0.125rem 0.1875rem rgba(4, 9, 20, 0.03);
      border: unset !important;
      border-radius: 0.25em;
      font-size: 0.9rem;
  }

}
</style>
