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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";

import type {
  FormData,
  MyObjectRoundRef,
} from "@/modules/09_leave/interface/response/round";

import DialogHeader from "@/components/DialogHeader.vue";

const $q = useQuasar();

const mixin = useCounterMixin();
const { dialogConfirm, success, messageError, showLoader, hideLoader } = mixin;
const isRead = defineModel<boolean>("isRead", { required: true });
/** propsData จาก RoundMain */
const props = defineProps({
  modal: {
    type: Boolean,
    require: true,
  },
  editCheck: {
    type: String,
    require: true,
  },
  fetchData: {
    type: Function,
    require: true,
  },
  closeDialog: {
    type: Function,
    require: true,
  },
  detailData: {
    type: Object,
    require: false,
  },
});

/** Ref INPUT เวลา*/
const amRef = ref<Object | null>(null);
const amOutRef = ref<Object | null>(null);
const pmRef = ref<Object | null>(null);
const pmOutRef = ref<Object | null>(null);
const objectRound: MyObjectRoundRef = {
  startTimeMorning: amRef,
  endTimeMorning: amOutRef,
  startTimeAfternoon: pmRef,
  endTimeAfternoon: pmOutRef,
};

const formDate = reactive<any>({
  startTimeMorning: {
    hours: new Date().getHours(),
    minutes: new Date().getMinutes(),
  },
  endTimeMorning: {
    hours: new Date().getHours(),
    minutes: new Date().getMinutes(),
  },
  startTimeAfternoon: {
    hours: new Date().getHours(),
    minutes: new Date().getMinutes(),
  },
  endTimeAfternoon: {
    hours: new Date().getHours(),
    minutes: new Date().getMinutes(),
  },
});

/** Form ข้อมูล */
const formData = reactive<FormData>({
  startTimeMorning: "",
  endTimeMorning: "",
  startTimeAfternoon: "",
  endTimeAfternoon: "",
  description: "",
  isDefault: false,
  isActive: false,
});

/**FunctionCheckbox แก้ไขสถานะ */
function checkDefault() {
  if (formData.isDefault === true) {
    formData.isActive = true;
  }
}

/** Function validateForm*/
function validateForm() {
  const hasError = [];
  for (const key in objectRound) {
    if (Object.prototype.hasOwnProperty.call(objectRound, key)) {
      const property = objectRound[key];
      if (property.value && typeof property.value.validate === "function") {
        const isValid = property.value.validate();
        hasError.push(isValid);
      }
    }
  }
  if (hasError.every((result) => result === true)) {
    onSubmit();
  }
}

/** Function ยืนยันการบันทึกข้อมูล*/
function onSubmit() {
  dialogConfirm(
    $q,
    async () => {
      const dataId = props.detailData?.id;
      props.editCheck === "add" ? postRoundDuty() : putRoundDuty(dataId);
    },
    "ยืนยันการบันทึกข้อมูล",
    "ต้องการยืนยันการบันทึกข้อมูลนี้หรือไม่ ?"
  );
}

/** Function สร้างรอบการปฏิบัติงาน*/
async function postRoundDuty() {
  showLoader();
  await http
    .post(config.API.roundDutytime(), formData)
    .then(async () => {
      await props.fetchData?.();
      await props.closeDialog?.();
      success($q, "บันทึกข้อมูล");
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** Functiom แก้ไข้รอบการปฏิบัติงาน*/
async function putRoundDuty(id: string) {
  showLoader();
  const data = {
    description: formData.description,
    isDefault: formData.isDefault,
    isActive: formData.isActive,
  };
  await http
    .put(config.API.roundDutytimeByid(id), data)
    .then(async () => {
      await props.fetchData?.();
      await props.closeDialog?.();
      success($q, "บันทึกข้อมูล");
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

//** Function ปิด Popup */
function close() {
  props.closeDialog?.();
  isRead.value = false;
}

/***/
watch(
  () => props.modal,
  () => {
    if (props.editCheck === "add") {
      formData.startTimeMorning = "";
      formData.endTimeMorning = "";
      formData.startTimeAfternoon = "";
      formData.endTimeAfternoon = "";
      formData.description = "";
      formData.isDefault = false;
      formData.isActive = false;
    } else if (props.editCheck === "edit") {
      if (props.detailData) {
        formData.startTimeMorning = props.detailData.startTimeMorning;
        formData.endTimeMorning = props.detailData.endTimeMorning;
        formData.startTimeAfternoon = props.detailData.startTimeAfternoon;
        formData.endTimeAfternoon = props.detailData.endTimeAfternoon;
        formData.description = props.detailData.description;
        formData.isDefault = props.detailData.isDefault;
        formData.isActive = props.detailData.isActive;
      }
    }
  }
);
</script>

<template>
  <q-dialog v-model="props.modal" persistent>
    <q-card style="min-width: 350px" class="bg-grey-11">
      <form @submit.prevent="validateForm">
        <DialogHeader
          :tittle="
            props.editCheck === 'add'
              ? 'เพิ่มรอบการปฏิบัติงาน'
              : props.detailData
              ? isRead
                ? `รายละเอียดรอบ ${props.detailData.round}`
                : `แก้ไขรอบ ${props.detailData.round}`
              : ''
          "
          :close="close"
        />
        <q-separator color="grey-4" />
        <q-card-section style="max-height: 55vh" class="scroll q-pa-none">
          <div
            class="col q-ma-md q-pa-sm bg-white border_custom text-weight-medium"
          >
            <p style="color: #06884d; font-size: 16px">ครึ่งเช้า</p>
            <div class="row justify-between q-my-sm items-start">
              <p class="q-ma-none mt">เวลาเข้างาน</p>

              <datepicker
                menu-class-name="modalfix"
                v-model="formDate.startTimeMorning"
                time-picker
                :readonly="props.editCheck === 'edit' || isRead"
                :enableTimePicker="true"
                @update:model-value="(value:any)=>(formData.startTimeMorning = `${String(value.hours).padStart(2,'0')}:${String(value.minutes).padStart(2,'0')}`)"
              >
                <template #trigger>
                  <q-input
                    ref="amRef"
                    class="inputgreen"
                    :readonly="props.editCheck === 'edit' || isRead"
                    :outlined="props.editCheck === 'add'"
                    dense
                    borderless
                    :model-value="
                      formData.startTimeMorning
                        ? `${formData.startTimeMorning} น.`
                        : '--:-- --'
                    "
                    :rules="[
                  (val:string) => !!val || 'กรุณากรอกเวลาเข้างาน',
                  (val:string) => {
                    if (val && formData.endTimeMorning) {
                      if (val > formData.endTimeMorning) {
                        return 'ต้องน้อยกว่าเวลาออกงาน';
                      }
                      if (
                        val >= formData.startTimeAfternoon &&
                        val <= formData.endTimeAfternoon
                      ) {
                        return 'ช่วงเวลาทับซ้อนกับช่วงบ่าย';
                      }
                      if (val === formData.endTimeAfternoon) {
                        return 'เวลาเข้างานช่วงเช้าต้องไม่ซ้ำกับออกงานเช้า';
                      }
                    }
                    return true;
                  },
                ]"
                    hide-bottom-space
                    style="width: 140px"
                    ><template v-slot:append>
                      <q-icon
                        v-if="props.editCheck !== 'edit' && !isRead"
                        name="mdi-clock-outline"
                        size="15px"
                        color="dark"
                      ></q-icon> </template
                  ></q-input>
                </template>
                <template
                  #action-row="{ internalModelValue, selectDate, closePicker }"
                >
                  <div class="time_picker action-row q-gutter-sm">
                    <q-btn
                      label="ยกเลิก"
                      @click="closePicker"
                      color="grey"
                      outline
                    >
                    </q-btn>
                    <q-btn label="ตกลง" @click="selectDate" color="primary">
                    </q-btn>
                  </div>
                </template>
              </datepicker>
            </div>
            <q-separator inset />
            <div class="row items-start q-my-sm justify-between">
              <p class="q-ma-none mt">เวลาออกงาน</p>
              <datepicker
                menu-class-name="modalfix"
                v-model="formDate.endTimeMorning"
                time-picker
                :readonly="props.editCheck === 'edit' || isRead"
                :enableTimePicker="true"
                @update:model-value="(value:any)=>(formData.endTimeMorning = `${String(value.hours).padStart(2,'0')}:${String(value.minutes).padStart(2,'0')}`)"
              >
                <template #trigger>
                  <q-input
                    ref="amOutRef"
                    class="inputgreen"
                    :readonly="props.editCheck === 'edit' || isRead"
                    :outlined="props.editCheck === 'add'"
                    dense
                    :model-value="
                      formData.endTimeMorning
                        ? `${formData.endTimeMorning} น.`
                        : '--:-- --'
                    "
                    borderless
                    :rules="[
                  (val:string) => !!val || 'กรุณากรอกเวลาออกงาน',
                  (val:string) => {
                    if (val && formData.startTimeMorning) {
                      if (val < formData.startTimeMorning) {
                        return 'ต้องมากกว่าเวลาเข้างาน';
                      }
                      if (
                        val >= formData.startTimeAfternoon &&
                        val <= formData.endTimeAfternoon
                      ) {
                        return 'ช่วงเวลาทับซ้อนกับช่วงบ่าย';
                      }
                      if (val === formData.startTimeMorning) {
                        return 'เวลาออกงานช่วงเช้าต้องไม่ซ้ำกับเข้างานเช้า';
                      }
                    }
                    return true;
                  },
                ]"
                    hide-bottom-space
                    style="width: 140px"
                    ><template v-slot:append>
                      <q-icon
                        v-if="props.editCheck !== 'edit' && !isRead"
                        name="mdi-clock-outline"
                        size="15px"
                        color="dark"
                      ></q-icon> </template
                  ></q-input>
                </template>
                <template
                  #action-row="{ internalModelValue, selectDate, closePicker }"
                >
                  <div class="time_picker action-row q-gutter-sm">
                    <q-btn
                      label="ยกเลิก"
                      @click="closePicker"
                      color="grey"
                      outline
                    >
                    </q-btn>
                    <q-btn label="ตกลง" @click="selectDate" color="primary">
                    </q-btn>
                  </div>
                </template>
              </datepicker>
            </div>
          </div>

          <div
            class="col q-ma-md q-pa-sm bg-white border_custom text-weight-medium"
          >
            <p style="color: #06884d; font-size: 16px">ครึ่งบ่าย</p>
            <div class="row justify-between q-my-sm items-start">
              <p class="q-ma-none mt">เวลาเข้างาน</p>
              <datepicker
                menu-class-name="modalfix"
                v-model="formDate.startTimeAfternoon"
                time-picker
                :readonly="props.editCheck === 'edit' || isRead"
                :enableTimePicker="true"
                @update:model-value="(value:any)=>(formData.startTimeAfternoon = `${String(value.hours).padStart(2,'0')}:${String(value.minutes).padStart(2,'0')}`)"
              >
                <template #trigger>
                  <q-input
                    ref="pmRef"
                    :rules="[
                  (val:string) => !!val || 'กรุณากรอกเวลาเข้างาน',
                  (val:string) => {
                    if (val && formData.endTimeAfternoon) {
                      if (val > formData.endTimeAfternoon) {
                        return 'ต้องน้อยกว่าเวลาออกงาน';
                      }
                      if (
                        val >= formData.startTimeMorning &&
                        val <= formData.endTimeMorning
                      ) {
                        return 'ช่วงเวลาทับซ้อนกับช่วงเช้า';
                      }
                      if (val === formData.endTimeAfternoon) {
                        return 'เวลาเข้างานช่วงบ่ายต้องไม่ซ้ำกับออกงานช่วงบ่าย';
                      }
                    }
                    return true;
                  },
                ]"
                    class="inputgreen"
                    :readonly="props.editCheck === 'edit' || isRead"
                    :outlined="props.editCheck === 'add'"
                    dense
                    borderless
                    :model-value="
                      formData.startTimeAfternoon
                        ? `${formData.startTimeAfternoon} น.`
                        : '--:-- --'
                    "
                    hide-bottom-space
                    style="width: 140px"
                  >
                    <template v-slot:append>
                      <q-icon
                        v-if="props.editCheck !== 'edit' && !isRead"
                        name="mdi-clock-outline"
                        size="15px"
                        color="dark"
                      ></q-icon> </template
                  ></q-input>
                </template>
                <template
                  #action-row="{ internalModelValue, selectDate, closePicker }"
                >
                  <div class="time_picker action-row q-gutter-sm">
                    <q-btn
                      label="ยกเลิก"
                      @click="closePicker"
                      color="grey"
                      outline
                    >
                    </q-btn>
                    <q-btn label="ตกลง" @click="selectDate" color="primary">
                    </q-btn>
                  </div>
                </template>
              </datepicker>
            </div>
            <q-separator inset />
            <div class="row items-start q-my-sm justify-between">
              <p class="q-ma-none mt">เวลาออกงาน</p>
              <datepicker
                menu-class-name="modalfix"
                v-model="formDate.endTimeAfternoon"
                time-picker
                :readonly="props.editCheck === 'edit' || isRead"
                :enableTimePicker="true"
                @update:model-value="(value:any)=>(formData.endTimeAfternoon = `${String(value.hours).padStart(2,'0')}:${String(value.minutes).padStart(2,'0')}`)"
              >
                <template #trigger>
                  <q-input
                    ref="pmOutRef"
                    :rules="[
                  (val:string) => !!val || 'กรุณากรอกเวลาออกงาน',
                  (val:string) => {
                    if (val && formData.startTimeAfternoon) {
                      if (val < formData.startTimeAfternoon) {
                        return 'ต้องมากกว่าเวลาเข้างาน';
                      }
                      if (
                        val >= formData.startTimeMorning &&
                        val <= formData.endTimeMorning
                      ) {
                        return 'ช่วงเวลาทับซ้อนกับช่วงเช้า';
                      }
                      if (val === formData.startTimeAfternoon) {
                        return 'เวลาออกงานช่วงบ่ายต้องไม่ซ้ำกับเข้างานช่วงบ่าย';
                      }
                    }
                    return true;
                  },
                ]"
                    class="inputgreen"
                    :readonly="props.editCheck === 'edit' || isRead"
                    :outlined="props.editCheck === 'add'"
                    dense
                    :model-value="
                      formData.endTimeAfternoon
                        ? `${formData.endTimeAfternoon} น.`
                        : '--:-- --'
                    "
                    borderless
                    hide-bottom-space
                    style="width: 140px"
                  >
                    <template v-slot:append>
                      <q-icon
                        v-if="props.editCheck !== 'edit' && !isRead"
                        name="mdi-clock-outline"
                        size="15px"
                        color="dark"
                      ></q-icon>
                    </template>
                  </q-input>
                </template>
                <template
                  #action-row="{ internalModelValue, selectDate, closePicker }"
                >
                  <div class="time_picker action-row q-gutter-sm">
                    <q-btn
                      label="ยกเลิก"
                      @click="closePicker"
                      color="grey"
                      outline
                    >
                    </q-btn>
                    <q-btn label="ตกลง" @click="selectDate" color="primary">
                    </q-btn>
                  </div>
                </template>
              </datepicker>
            </div>
          </div>

          <q-input
            class="col-12 bg-white q-ma-md"
            outlined
            stack-label
            :readonly="isRead"
            v-model="formData.description"
            label="คำอธิบาย"
            hide-bottom-space
            type="textarea"
          />

          <div
            class="col q-ma-md q-pa-sm bg-white border_custom text-weight-medium"
          >
            <div class="row items-center q-my-sm justify-between">
              <p class="q-ma-none">เวลา Default</p>
              <label
                :class="`toggle-control ${isRead ? 'no-pointer-events' : ''}`"
              >
                <input
                  :readonly="isRead"
                  type="checkbox"
                  v-model="formData.isDefault"
                  @change="checkDefault()"
                />
                <span class="control"></span>
              </label>
            </div>
          </div>

          <div
            class="col q-ma-md q-pa-sm bg-white border_custom text-weight-medium"
          >
            <div class="row items-center q-my-sm justify-between">
              <p class="q-ma-none">สถานะการใช้งาน</p>
              <label
                :class="`toggle-control ${isRead ? 'no-pointer-events' : ''}`"
              >
                <input
                  type="checkbox"
                  v-model="formData.isActive"
                  :disabled="formData.isDefault"
                />
                <span class="control"></span>
              </label>
            </div>
          </div>
        </q-card-section>

        <q-separator color="grey-4" v-if="!isRead" />
        <div class="q-pa-sm" v-if="!isRead">
          <div class="row justify-end">
            <q-btn
              id="onSubmit"
              type="submit"
              dense
              unelevated
              label="บันทึก"
              color="public"
              class="q-px-md"
            >
              <q-tooltip>บันทึก</q-tooltip>
            </q-btn>
          </div>
        </div>
      </form>
    </q-card>
  </q-dialog>
</template>

<style scoped lang="scss">
@use "sass:math";
.mt {
  margin-top: 10px;
}
.border_custom {
  border-radius: 6px !important;
  border: 1px solid #e1e1e1;
}

.action-row {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  width: 100%;
}

$toggle-background-color-on: #06884d;
$toggle-background-color-off: darkgray;
$toggle-control-color: white;
$toggle-width: 40px;
$toggle-height: 25px;
$toggle-gutter: 3px;
$toggle-radius: 50%;
$toggle-control-speed: 0.15s;
$toggle-control-ease: ease-in;

// These are our computed variables
// change at your own risk.
$toggle-radius: math.div($toggle-height, 2);
$toggle-control-size: $toggle-height - ($toggle-gutter * 2);

.toggle-control {
  display: block;
  position: relative;
  padding-left: $toggle-width;
  margin-bottom: 12px;
  cursor: pointer;
  font-size: 22px;
  user-select: none;

  input {
    position: absolute;
    opacity: 0;
    cursor: pointer;
    height: 0;
    width: 0;
  }

  input:checked ~ .control {
    background-color: $toggle-background-color-on;

    &:after {
      left: $toggle-width - $toggle-control-size - $toggle-gutter;
    }
  }

  .control {
    position: absolute;
    top: -7px;
    left: -15px;
    height: $toggle-height;
    width: $toggle-width;
    border-radius: $toggle-radius;
    background-color: $toggle-background-color-off;
    transition: background-color $toggle-control-speed $toggle-control-ease;

    &:after {
      content: "";
      position: absolute;
      left: $toggle-gutter;
      top: $toggle-gutter;
      width: $toggle-control-size;
      height: $toggle-control-size;
      border-radius: $toggle-radius;
      background: $toggle-control-color;
      transition: left $toggle-control-speed $toggle-control-ease;
    }
  }
}
</style>
