<script setup lang="ts">
import { ref, onMounted, computed, watch } from "vue";
import { useQuasar } from "quasar";

/**
 * importType
 */
import type { QTableProps } from "quasar";
import type { Schedule } from "@/modules/04_system/interface/response/Main";
import type { ScheduleCreate } from "@/modules/04_system/interface/request/Main";
import type { ItemsTeb } from "@/modules/04_system/interface/index/Main";

/**
 * import components
 */
import FormDialog from "@/modules/04_system/components/formDialog.vue";
import formSchedule from "./formSchedule .vue";
/**
 * importStore
 */
import { useCounterMixin } from "@/stores/mixin";
import { useDataStore } from "@/modules/04_system/stores/main";
import { storeToRefs } from "pinia";

/**
 * use
 */
const $q = useQuasar();
const {
  showLoader,
  hideLoader,
  date2Thai,
  dialogRemove,
  dialogConfirm,
  dialogMessageNotify,
  onSearchDataTable,
  convertDatetimeToAPI,
} = useCounterMixin();
const {
  getSchedule,
  createSchedule,
  editSchedule,
  deleteSchedule,
  toggleSchedule,
} = useDataStore();
const storeData = useDataStore();
const { restoreRunTotal, dataSchedule } = storeToRefs(storeData);

const idEditSchedule = ref<string>("");
const openDialog = ref<boolean>(false);

const prevFormDataschedule = ref<ScheduleCreate>({
  timeStartEvery: "",
  type: "",
  date: [],
  name: "",
  time: "",
  schedule: "",
});

const formDataschedule = ref<ScheduleCreate>({
  timeStartEvery: "",
  type: "",
  date: [],
  name: "",
  time: "",
  schedule: "",
  startAt: new Date(),
});

/**
 * Table
 */
const filter = ref<string>("");
const visibleColumns = ref<string[]>([
  "name",
  "type",
  "date",
  "startAt",
  "status",
]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "name",
    align: "left",
    label: "ชื่อของข้อมูลสำรองใหม่",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "type",
    align: "center",
    label: "ตารางการข้อมูลสำรองใหม่",
    sortable: true,
    // field: (v) => date2Thai(v, false, true),
    field: "type",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "date",
    align: "left",
    label: "เวลาการทำข้อมูลสำรองใหม่",
    sortable: true,
    // field: (v) => date2Thai(v, false, true),
    field: "date",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },

  {
    name: "startAt",
    align: "left",
    label: "วันที่เริ่มการสำรองข้อมูล",
    sortable: true,
    field: "startAt",
    format(val, row) {
      return date2Thai(val, false, true);
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "status",
    align: "center",
    label: "สถานะ",
    sortable: true,
    field: "status",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

function assignDataformDataschedule(data: Schedule) {
  typeTime.value = data.time !== "" ? "set" : "start";

  idEditSchedule.value = data.id;
  prevFormDataschedule.value = {
    timeStartEvery: data.timeStartEvery,
    type: data.type,
    date: [],
    name: data.name,
    time: data.time,
    schedule: data.schedule,
    startAt: data.startAt,
  };

  const tempValue = data.date.split(" ");

  tempValue.forEach((element) => {
    prevFormDataschedule.value.date.push(element);
  });

  formDataschedule.value = { ...prevFormDataschedule.value };

  tab.value = data.type;
}

/**
 * function submit() เเปลงค่าให้เป็น แบบ cron ก่อนส่งไปยัง backend
 *
 */
function convertFormToCron() {
  let allValues = formDataschedule.value.date.join(" ").split(" ");

  let uniqueValues = [...new Set(allValues)];

  let result = uniqueValues.join(",");

  let [hour, minute] = formDataschedule.value.time.split(":");

  let time = `${minute} ${hour}`;

  if (formDataschedule.value.type === "daily") {
    if (typeTime.value.includes("set")) {
      formDataschedule.value.schedule = `0 ${time} * * *`;
    } else {
      formDataschedule.value.schedule = `0 0 */${formDataschedule.value.timeStartEvery} * * *`;
    }
  }

  if (formDataschedule.value.type === "weekly") {
    formDataschedule.value.schedule = `0 ${time} * * ${result}`;
  }

  if (formDataschedule.value.type === "monthly") {
    formDataschedule.value.schedule = `0 ${time} ${result} * *`;
  }
}

/**
 * function submit() ตั้งเวลา backup
 *
 */
function onSubmit() {
  if (
    (formDataschedule.value.type === "weekly" ||
      formDataschedule.value.type === "monthly") &&
    formDataschedule.value.date.length === 0
  ) {
    dialogMessageNotify($q, "กรุณาเลือกวันสำรองข้อมูล");
  } else {
    dialogConfirm($q, async () => {
      showLoader();
      if (typeOnSubmit.value === "create") {
        await createSchedule({
          ...formDataschedule.value,
          startAt: convertDatetimeToAPI(formDataschedule.value.startAt as Date),
        });
      }
      if (typeOnSubmit.value === "edit") {
        await editSchedule(idEditSchedule.value, {
          ...formDataschedule.value,
          startAt: convertDatetimeToAPI(formDataschedule.value.startAt as Date),
        });
      }
      getSchedule();
      hideLoader();
      openDialog.value = false;
      clearForm();
    });
  }
}

/**
 * function ลบรายการข้อมูลสำรอง
 * @param id รายการสำรอง
 */
function onDelete(id: string) {
  dialogRemove($q, async () => {
    showLoader();
    await deleteSchedule(id);
    await getSchedule();
  });
}

const typeOnSubmit = ref<"edit" | "create">("create");
const typeTime = ref<string>("set");
const tab = ref<string>("daily");
const tabItems = ref<ItemsTeb[]>([
  { name: "daily", label: "ทุกวัน", icon: "" },
  { name: "weekly", label: "ทุกสัปดาห์", icon: "" },
  { name: "monthly", label: "ทุกเดือน", icon: "" },
]);

const dayColors: { [key: string]: string } = {
  mon: "#FFC700", // Yellow
  tue: "#FF69B4", // Pink
  wed: "#008000", // Green
  thu: "#FFA500", // Orange
  fri: "#0000FF", // Blue
  sat: "#800080", // Purple
  sun: "#FF0000", // Red
};

const dayNames: { [key: string]: string } = {
  mon: "จ", // Yellow
  tue: "อ", // Pink
  wed: "พ", // Green
  thu: "พฤ", // Orange
  fri: "ศ", // Blue
  sat: "ส", // Purple
  sun: "อา", // Red
};

const typeSchedule: { [key: string]: string } = {
  daily: "รายวัน",
  weekly: "รายสัปดาห์",
  monthly: "รายเดือน",
};

function clearForm() {
  formDataschedule.value.timeStartEvery = "";
  formDataschedule.value.type = "";
  formDataschedule.value.date = [];
  formDataschedule.value.name = "";
  formDataschedule.value.time = "";
  formDataschedule.value.schedule = "";
}
const dataMain = ref<Schedule[]>([]);
function serchDataTable() {
  dataSchedule.value = onSearchDataTable(
    filter.value,
    dataMain.value,
    columns.value ? columns.value : []
  );
}

watch(tab, () => {
  if (tab.value === formDataschedule.value.type) {
    formDataschedule.value = { ...prevFormDataschedule.value };
  }
  if (tab.value !== formDataschedule.value.type) {
    formDataschedule.value.date = [];
    formDataschedule.value.time = "";
    formDataschedule.value.timeStartEvery = "";
    typeTime.value = "set";
  }
});

onMounted(async () => {
  await getSchedule();
  dataMain.value = dataSchedule.value;
});
</script>

<template>
  <q-card-section class="q-pa-none q-mt-sm">
    <div class="items-center col-12 row q-gutter-x-sm q-mb-sm">
      <q-btn
        color="primary"
        icon="add"
        label="ตั้งเวลาสำรองข้อมูล"
        @click="
          () => {
            typeOnSubmit = 'create';
            openDialog = true;
            clearForm();
          }
        "
      >
        <q-tooltip>ตั้งเวลาสำรองข้อมูล </q-tooltip>
      </q-btn>

      <q-space />

      <q-input
        borderless
        dense
        outlined
        v-model="filter"
        placeholder="ค้นหา"
        @keydown.enter.pervent="serchDataTable"
      >
        <template v-slot:append>
          <q-icon name="search" />
        </template>
      </q-input>
      <q-select
        v-model="visibleColumns"
        multiple
        outlined
        dense
        options-dense
        :display-value="$q.lang.table.columns"
        emit-value
        map-options
        :options="columns"
        option-value="name"
        style="min-width: 140px"
      />
    </div>

    <d-table
      :rows="dataSchedule"
      :columns="columns"
      row-key="name"
      :visible-columns="visibleColumns"
    >
      <template v-slot:header="props">
        <q-tr :props="props">
          <q-th v-for="(col, i) in props.cols" :key="col.name" :props="props">
            {{ col.label }}
          </q-th>
          <q-th></q-th>
        </q-tr>
      </template>
      <template v-slot:body="props">
        <q-tr :props="props">
          <q-td v-if="visibleColumns.includes('name')">
            {{ props.row.name }}
          </q-td>
          <q-td class="text-center" v-if="visibleColumns.includes('type')">
            <q-badge
              rounded
              style="color: #007aff; background: #ededed"
              :label="typeSchedule[props.row.type]"
            />
          </q-td>
          <q-td v-if="visibleColumns.includes('date')">
            <div class="column">
              <div class="col-6">{{ props.row.time }}</div>

              <div
                class="col-6 q-gutter-x-sm"
                v-if="props.row.type.includes('daily')"
              >
                <q-badge
                  rounded
                  style="color: #fefefe; background: #242121"
                  :label="
                    props.row.timeStartEvery !== ''
                      ? `ทุก ${props.row.timeStartEvery} ชั่วโมง`
                      : 'ทุกวัน'
                  "
                />
              </div>

              <div
                class="col-6 q-gutter-x-sm"
                v-if="props.row.type.includes('weekly')"
              >
                <q-badge
                  v-for="(t, i) in props.row.date.split(' ')"
                  rounded
                  :style="`color: #fefefe; background: ${dayColors[t]}`"
                  :label="dayNames[t]"
                />
              </div>

              <div
                class="col-6 q-gutter-x-sm"
                v-if="props.row.type.includes('monthly')"
              >
                <q-badge
                  v-for="(t, i) in props.row.date.split(' ')"
                  rounded
                  style="color: #fefefe; background: #242121"
                  :label="`ทุกวันที่ ${t}`"
                />
              </div>
            </div>
          </q-td>
          <q-td v-if="visibleColumns.includes('startAt')">
            {{ date2Thai(props.row.startAt, true, false) }}
          </q-td>
          <q-td v-if="visibleColumns.includes('status')">
            <q-toggle
              size="lg"
              v-model="props.row.enabled"
              @click.stop="
                () => {
                  toggleSchedule(props.row.id);
                }
              "
            />
          </q-td>
          <q-td>
            <q-btn
              dense
              flat
              round
              icon="edit"
              color="edit"
              @click.petvent="
                () => {
                  typeOnSubmit = 'edit';
                  assignDataformDataschedule({ ...props.row });
                  openDialog = true;
                }
              "
            >
              <q-tooltip>แก้ไขการสำรองข้อมูล</q-tooltip>
            </q-btn>

            <q-btn
              dense
              flat
              round
              :disable="restoreRunTotal !== 0"
              icon="delete"
              color="red"
              @click.petvent="onDelete(props.row.id)"
            >
              <q-tooltip>ลบรายการสำรองข้อมูล</q-tooltip>
            </q-btn>
          </q-td>
        </q-tr>
      </template>
    </d-table>
  </q-card-section>

  <FormDialog
    v-model:openDialog="openDialog"
    :title="`${
      typeOnSubmit === 'create' ? 'สร้าง' : 'แก้ไข'
    }ข้อมูลสำรองใหม่ ตั้งตารางเวลา`"
    :close="() => (openDialog = false)"
    :submit="
      () => {
        formDataschedule.type = tab;

        if (formDataschedule.startAt !== undefined) {
          formDataschedule.startAt = new Date(
            formDataschedule.startAt as Date
          ).toISOString();
        }
        convertFormToCron();

        onSubmit();
      }
    "
  >
    <q-card flast bordered>
      <q-tabs
        v-model="tab"
        dense
        align="left"
        inline-label
        class="bg-white text-grey"
        active-color="primary"
        indicator-color="primary"
      >
        <div v-for="item in tabItems">
          <q-tab :name="item.name" :label="item.label" />
        </div>
      </q-tabs>
      <q-separator />

      <div class="q-pa-sm">
        <formSchedule
          v-model:name="formDataschedule.name"
          v-model:type-time="typeTime"
          v-model:time="formDataschedule.time"
          v-model:time-start-every="formDataschedule.timeStartEvery"
          v-model:start-at="formDataschedule.startAt"
          v-model:date="formDataschedule.date"
          v-model:tab="tab"
        />
      </div>
    </q-card>
  </FormDialog>
</template>

<style scoped></style>
