<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { useQuasar } from 'quasar'
import moment from 'moment'
import http from '@/plugins/http'
import config from '@/app.config'

import type { FormRef } from '@/interface/index/Main'
import type { FormTimeStemp } from '@/interface/response/checkin'

// importStores
import { useCounterMixin } from '@/stores/mixin'
// importType

const $q = useQuasar()
const mixin = useCounterMixin()
const { date2Thai, success, dialogConfirm } = mixin

const props = defineProps({
  dataById: {
    type: Object,
    default: null,
  },
  closePopup: {
    type: Function,
    required: true,
  },
  fetchData: {
    type: Function,
    require: true,
  },
})

const dataByIdVal = ref<any>([])
const date = ref<Date | null>(null)
const checkboxIn = ref<boolean>(false)
const checkboxOut = ref<boolean>(false)
const reason = ref<string>('')
const statusAction = ref<boolean>(false)

const dateNow = ref<Date>(new Date())
const timeNoew = ref<string>('')

function updateClock() {
  const date = Date.now()
  const hh = moment(date).format('HH')
  const mm = moment(date).format('mm')
  timeNoew.value = `${hh}:${mm} น.`
}

const dateRef = ref<object | null>(null)
const reasonRef = ref<object | null>(null)

const objectRef: FormRef = {
  date: dateRef,
  reason: reasonRef,
}
const checkstatusBox = ref<boolean>(false)

/** function checkValidate*/
function onCkickSave() {
  const hasError = []
  for (const key in objectRef) {
    if (Object.prototype.hasOwnProperty.call(objectRef, key)) {
      const property = objectRef[key]
      if (property.value && typeof property.value.validate === 'function') {
        const isValid = property.value.validate()
        hasError.push(isValid)
      }
    }
  }
  if (checkboxIn.value === false && checkboxOut.value === false) {
    checkstatusBox.value = true
  }
  if (
    hasError.every(
      (result) => result === true && checkstatusBox.value === false
    )
  ) {
    dialogConfirm($q, async () => {
      const data: FormTimeStemp = {
        checkDate: date.value,
        checkInEdit: checkboxIn.value,
        checkOutEdit: checkboxOut.value,
        description: reason.value,
      }
      createListTime(data)
    })
  } else {
    console.log('ไม่ผ่าน ')
  }
}

/**
 * function  เพิ่มลงเวลากรณีพิเศษ
 * @param data body Request
 */
async function createListTime(data: FormTimeStemp) {
  await http
    .post(config.API.createTimeStamp(), data)
    .then(() => {
      success($q, 'บันทึกข้อมูลสำเร็จ')
    })
    .catch((err) => {
      console.log(err)
    })
    .finally(() => {
      props.closePopup?.()
      props.fetchData?.()
    })
}

/** Hook */
onMounted(() => {
  updateClock()
  dataByIdVal.value = props.dataById

  if (dataByIdVal.value == null) {
    statusAction.value = true
  } else {
    date.value = new Date(dataByIdVal.value.checkInDateTime)
  }
})

watch(
  [() => checkboxIn.value, () => checkboxOut.value],
  ([newCheckboxIn, newCheckboxOut]) => {
    if (checkstatusBox.value) {
      if (newCheckboxIn || newCheckboxOut) {
        checkstatusBox.value = false
      }
    }
  }
)
</script>
<template>
  <q-card-section class="col q-pt-none">
    <div class="row q-pa-sm q-col-q-gutter-sm">
      <q-card
        flat
        bordered
        :class="$q.screen.gt.xs ? 'col-12 bg-grey-1' : 'col-12 '"
      >
        <q-card-section class="bg-primary text-white q-pa-sm">
          <div class="text-center text-bold">เวลาปัจจุบัน</div>
        </q-card-section>
        <!-- <div class="q-pa-sm text-primary">เวลาปัจจุบัน</div> -->
        <q-card-section class="text-center q-pa-sm">
          <div class="row q-gutter-md">
            <div class="col">{{ date2Thai(dateNow) }}</div>
            <div class="col">{{ timeNoew }}</div>
          </div>
        </q-card-section>
      </q-card>

      <q-card flat bordered class="col-12 q-mt-sm" v-if="statusAction">
        <div class="q-pa-sm">
          <datepicker
            v-model="date"
            :locale="'th'"
            autoApply
            :enableTimePicker="false"
            week-start="0"
            outlined
          >
            <template #year="{ year }">
              {{ year + 543 }}
            </template>
            <template #year-overlay-value="{ value }">
              {{ parseInt(value + 543) }}
            </template>
            <template #trigger>
              <q-input
                ref="dateRef"
                outlined
                dense
                :model-value="date !== null ? date2Thai(date) : null"
                :label="`${'วันที่ขอแก้ไข'}`"
                :rules="[(val) => !!val || 'กรุณาเลือกวันที่']"
                lazy-rules
                hide-bottom-space
              >
                <template v-slot:prepend>
                  <q-icon
                    name="event"
                    class="cursor-pointer"
                    style="color: var(--q-primary)"
                  >
                  </q-icon>
                </template>
              </q-input> </template
          ></datepicker>
        </div>
      </q-card>

      <q-card flat bordered class="q-pa-sm col-12 bg-grey-1 q-mt-sm" v-else>
        <div class="row q-gutter-md text-grey-5">
          <div class="col-1">
            <q-icon color="grey-5" name="calendar_today" />
          </div>
          <div class="col">{{ dataByIdVal.checkInDate }}</div>
        </div>
      </q-card>

      <q-card
        flat
        bordered
        class="q-pa-sm col-12 q-mt-sm"
        :style="{
          borderColor: checkstatusBox ? '#B22222' : '',
          borderWidth: checkstatusBox ? '2px' : '',
        }"
      >
        <div class="row q-gutter-xs">
          <div class="col-12">
            <q-checkbox
              keep-color
              color="primary"
              v-model="checkboxIn"
              label="ขอแก้ไขเวลาเข้างาน"
            />
          </div>
          <div class="col-12">
            <q-checkbox
              keep-color
              v-model="checkboxOut"
              color="primary"
              label="ขอแก้ไขเวลาออกงาน"
            />
          </div>
        </div>
      </q-card>

      <div
        v-if="checkstatusBox"
        class="text-red-9 q-pa-sm"
        style="font-size: 10px"
      >
        กรุณาเลือก
      </div>

      <q-card flat bordered class="q-pa-sm col-12 q-mt-sm">
        <q-input
          ref="reasonRef"
          dense
          outlined
          v-model="reason"
          label="เหตุผล"
          type="textarea"
          :rows="4"
          label-color="grey-5"
          :rules="[(val) => !!val || 'กรุณากรอกเหตุผล']"
          lazy-rules
          hide-bottom-space
          class="custom-aqua-border"
        />
      </q-card>
    </div>
  </q-card-section>
  <q-separator />
  <q-card-actions align="right">
    <q-btn dense color="secondary" label="บันทึก" @click="onCkickSave" />
  </q-card-actions>
</template>

<style scoped></style>
