<template>
  <div>
    <div
      class="field is-grouped mb-4 border-bottom"
      v-if="1 < 0"
    >
      <div
        class="control pl-2"
        v-if="mode !== 'simple'"
      >
        <a
          class="mr-1"
          @click="previousYear()"
        >
          <Icon
            name="ic:baseline-keyboard-double-arrow-left"
            :size="18"
          />
        </a>
        <a
          @click="previousMonth()"
          v-if="type === 'days'"
        >
          <Icon
            name="ic:baseline-keyboard-arrow-left"
            :size="18"
          />
        </a>
      </div>
      <div class="control is-expanded has-text-centered">
        <span
          class="fsb-16 hyperlink mr-3"
          @click="type = 'months'"
          v-if="type === 'days'"
          >{{ `Tháng ${month}` }}</span
        >
        <span
          class="fsb-16 hyperlink"
          @click="type = 'years'"
          >{{ caption || year }}</span
        >
      </div>
      <div
        class="control pr-2"
        v-if="mode !== 'simple'"
      >
        <a
          class="mr-1"
          @click="nextMonth()"
          v-if="type === 'days'"
        >
          <Icon
            name="ic:baseline-keyboard-arrow-right"
            :size="18"
          />
        </a>
        <a @click="nextYear()">
          <Icon
            name="ic:baseline-keyboard-double-arrow-right"
            :size="18"
          />
        </a>
      </div>
    </div>
    <div v-if="type === 'days'">
      <div
        :class="`columns mx-0 ${i === weeks.length - 1 ? 'mb-1' : ''}`"
        v-for="(v, i) in weeks"
        :key="i"
      >
        <div
          class="column px-3 py-1 has-text-centered"
          v-for="(m, h) in v.dates"
          :key="h"
          style="min-height: 100px"
          :style="`border-right: 1px solid #DCDCDC; border-bottom: 1px solid #DCDCDC; ${(viewport > 1 && h === 0) || viewport === 1 ? 'border-left: 1px solid #DCDCDC;' : ''}
      ${i === 0 ? 'border-top: 1px solid #DCDCDC;' : ''}`"
        >
          <p
            class="mb-1"
            v-if="i === 0"
          >
            <b>{{ $find(dateOfWeek, { id: h }).text }}</b>
          </p>
          <span
            class="has-background-primary has-text-white px-1 py-1"
            v-if="m.date === today"
            >{{ m.dayPrint }}</span
          >
          <span v-else>{{ m.dayPrint }}</span>
          <div
            class="has-text-left fs-15 mt-1"
            v-if="m.event && m.currentMonth === m.mothCondition"
          >
            <p
              :class="`pt-1 ${j === m.event.length - 1 ? '' : 'border-bottom'}`"
              v-for="(h, j) in m.event"
            >
              <Icon
                :name="h.icon"
                :size="18"
              />
              <a
                class="ml-3"
                @click="openEvent(h)"
                >{{ h.text }}</a
              >
            </p>
          </div>
        </div>
      </div>
    </div>
    <Modal
      @close="showmodal = undefined"
      v-bind="showmodal"
      v-if="showmodal"
    ></Modal>
  </div>
</template>
<script>
export default {
  props: ["date", "events", "mode", "vyear", "vmonth"],
  data() {
    return {
      dates: [],
      dateOfWeek: [
        { id: 0, text: "CN" },
        { id: 1, text: "T2" },
        { id: 2, text: "T3" },
        { id: 3, text: "T4" },
        { id: 4, text: "T5" },
        { id: 5, text: "T6" },
        { id: 6, text: "T7" },
      ],
      weeks: [],
      today: this.$dayjs().format("YYYY/MM/DD"),
      year: undefined,
      month: undefined,
      type: "days",
      caption: undefined,
      action: undefined,
      curdate: undefined,
      showmodal: undefined,
      viewport: 5,
    };
  },
  created() {
    this.showDate();
  },
  watch: {
    date(newVal) {
      if (newVal) this.showDate();
    },
    vmonth() {
      this.showDate();
    },
    events() {
      this.showDate();
    },
  },
  methods: {
    async openEvent(event) {
      let row = await this.$getdata("sale", {
        first: true,
        filter: { id: event.sale },
      });
      this.showmodal = {
        title: "Bán hàng",
        height: "500px",
        width: "90%",
        component: "sale/Sale",
        vbind: { row: row, highlight: event.id },
      };
    },
    compiledComponent(value) {
      return {
        template: `${value}`,
      };
    },
    showDate() {
      this.curdate = this.date ? this.date.replaceAll("-", "/") : undefined;
      this.year = this.$dayjs(this.curdate || this.today).year();
      this.month = this.$dayjs(this.curdate || this.today).month() + 1;
      if (this.vyear) this.year = this.$copy(this.vyear);
      if (this.vmonth) this.month = this.$copy(this.vmonth);
      this.getDates();
    },
    chooseToday() {
      this.$emit("date", this.today.replaceAll("/", "-"));
      this.year = this.$dayjs(this.today).year();
      this.month = this.$dayjs(this.today).month() + 1;
      this.getDates();
    },
    changeCaption(v) {
      this.caption = v;
    },
    selectMonth(v) {
      this.month = v;
      this.getDates();
      this.type = "days";
    },
    selectYear(v) {
      this.year = v;
      this.getDates();
      this.type = "days";
    },
    getDates() {
      this.caption = undefined;
      this.dates = this.allDaysInMonth(this.year, this.month);
      this.dates.map((v) => {
        let event = this.events ? this.$filter(this.events, { isodate: v.date }) : undefined;
        if (event.length > 0) v.event = event;
      });
      this.weeks = this.$unique(this.dates, ["week"]).map((v) => {
        return { week: v.week };
      });
      this.weeks.map((v) => {
        v.dates = this.dates.filter((x) => x.week === v.week);
      });
    },
    nextMonth() {
      let month = this.month + 1;
      if (month > 12) {
        month = 1;
        this.year += 1;
      }
      this.month = month;
      this.getDates();
    },
    previousMonth() {
      let month = this.month - 1;
      if (month === 0) {
        month = 12;
        this.year -= 1;
      }
      this.month = month;
      this.getDates();
    },
    nextYear() {
      if (this.type === "years") return (this.action = { name: "next", id: this.$id() });
      this.year += 1;
      this.getDates();
    },
    previousYear() {
      if (this.type === "years") return (this.action = { name: "previous", id: this.$id() });
      this.year -= 1;
      this.getDates();
    },
    choose(m) {
      this.$emit("date", m.date.replaceAll("/", "-"));
    },
    createDate(v, x, y) {
      return (
        v + "/" + (x < 10 ? "0" + x.toString() : x.toString()) + "/" + (y < 10 ? "0" + y.toString() : y.toString())
      );
    },
    allDaysInMonth(year, month) {
      let days = Array.from({ length: this.$dayjs(this.createDate(year, month, 1)).daysInMonth() }, (_, i) => i + 1);
      let arr = [];
      days.map((v) => {
        for (let i = 0; i < 7; i++) {
          let thedate = this.$dayjs(this.createDate(year, month, v)).weekday(i);
          let date = this.$dayjs(new Date(thedate.$d)).format("YYYY/MM/DD");
          let dayPrint = this.$dayjs(new Date(thedate.$d)).format("DD");
          let mothCondition = this.$dayjs(date).month() + 1;
          let currentMonth = month;
          let found = arr.find((x) => x.date === date);
          if (!found) {
            let dayOfWeek = this.$dayjs(date).day();
            let week = this.$dayjs(date).week();
            let ele = {
              date: date,
              week: week,
              day: v,
              dayOfWeek: dayOfWeek,
              dayPrint: dayPrint,
              mothCondition: mothCondition,
              currentMonth: currentMonth,
            };
            arr.push(ele);
          }
        }
      });
      return arr;
    },
  },
};
</script>
