<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import type { PropType } from "vue";
import { useQuasar } from "quasar";
import { useRoute } from "vue-router";
import { tokenParsed } from "@/plugins/auth";

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

import type {
  Information,
  DataOption,
} from "@/modules/03_recruiting/interface/index/Main";

import {
  defaultInformation,
  changeData,
} from "@/modules/03_recruiting/interface/index/Main";
import HeaderTop from "@/modules/03_recruiting/components/top.vue";

const props = defineProps({
  prefixOptions: {
    type: Array as PropType<DataOption[]>,
    required: true,
  },
  religionOptions: {
    type: Array as PropType<DataOption[]>,
    required: true,
  },
  provinceOptions: {
    type: Array as PropType<DataOption[]>,
    required: true,
  },
  status: {
    type: String,
    required: true,
  },
  form: {
    type: Object,
    required: true,
  },
});

const $q = useQuasar();
const route = useRoute();
const mixin = useCounterMixin();
const { date2Thai, calAge, success } = mixin;

const districtOptions = ref<DataOption[]>([]);
const candidateId = ref<string>(route.params.candidateId.toString());
const edit = ref<boolean>(true);
const myform = ref<any>({});
const img = ref<string>("");
const opNat = ref(["ไทย"]);
const fileProfile = ref<File[]>([]);

const { messageError, showLoader, hideLoader } = mixin;

const emit = defineEmits(["update:form"]);

/** ดึงข้อมูล */
async function fetchData() {
  showLoader();
  await http
    .get(config.API.candidateInformation(candidateId.value))
    .then((res) => {
      const data = res.data.result;
      defaultInformation.value.prefixId = data.prefixId;
      defaultInformation.value.lastname = data.lastName;
      defaultInformation.value.provinceId = data.citizenProvinceId;
      defaultInformation.value.districtId = data.citizenDistrictId;
      defaultInformation.value.birthDate =
        data.dateOfBirth == null ? null : new Date(data.dateOfBirth);
      defaultInformation.value.cardIdDate =
        data.citizenDate == null ? null : new Date(data.citizenDate);
      defaultInformation.value.cardid = data.citizenId;
      defaultInformation.value.firstname = data.firstName;
      defaultInformation.value.religionId = data.religionId;
      defaultInformation.value.nationality = data.nationality;
      defaultInformation.value.email = data.email;
      defaultInformation.value.phone = data.mobilePhone;
      defaultInformation.value.tel = data.telephone;
      defaultInformation.value.knowledge = data.knowledge;
    })
    .catch(async () => {
      const user = await tokenParsed();
      defaultInformation.value.email = user ? user.email : "";
      defaultInformation.value.firstname = user ? user.given_name : "";
      defaultInformation.value.lastname = user ? user.family_name : "";
    })
    .finally(() => {
      hideLoader();
    });
}

/** ดึงข้อมูล รูปภาพ */
async function fetchImgData() {
  showLoader();
  await http
    .get(config.API.candidateProfile(candidateId.value))
    .then((res) => {
      const data = res.data.result;
      img.value = data;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
    });
}
/** อัพโหลด รูปภาพ */
async function uploadImage(e: any) {
  let input = e.target.files;
  if (input.length > 0) {
    const formData = new FormData();
    formData.append("", input[0]);
    await http
      .put(config.API.candidateProfile(candidateId.value), formData)
      .then((res) => {
        success($q, "อัปโหลดรูปสำเร็จ");
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(async () => {
        await fetchImgData();
        fileProfile.value = [];
      });
    return;
  }
}

/**
 * ดึงข้อมูลเขต
 * @param id อำเภอ
 */
async function fetchDistrict(id: string) {
  showLoader();
  await http
    .get(config.API.listDistrict(id))
    .then((res) => {
      const data = res.data.result;
      let option: DataOption[] = [];
      data.map((r: DataOption) => {
        option.push({ id: r.id.toString(), name: r.name.toString() });
      });
      districtOptions.value = option;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

function getClass(val: boolean) {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
}

watch(myform, async (count: any) => {
  emit("update:form", count);
});

watch(defaultInformation, async (count: Information) => {
  await changeData("information", count);
});

onMounted(async () => {
  await fetchData();
  await fetchImgData();
  if (defaultInformation.value.provinceId != null)
    await fetchDistrict(defaultInformation.value.provinceId);
});
</script>

<template>
  <HeaderTop
    v-model:edit="edit"
    header="ข้อมูลส่วนตัว"
    icon="mdi-account"
    :addData="true"
    :editOnly="false"
    :editData="false"
  />
  <!-- :changeBtn="changeBtn" -->
  <q-form
    ref="myform"
    class="col-12 row q-col-gutter-x-sm justify-center q-col-gutter-sm"
  >
    <div
      class="row col-xs-12 col-sm-12 col-md-10 items-center q-col-gutter-x-sm q-col-gutter-y-xs"
    >
      <div class="col-xs-12 col-sm-4 col-md-4">
        <q-input
          :class="getClass(status == 'checkRegister' || status == 'payment')"
          :outlined="status == 'checkRegister' || status == 'payment'"
          dense
          type="tel"
          mask="#############"
          :counter="
            status == 'checkRegister' || status == 'payment' ? true : false
          "
          lazy-rules
          :readonly="!(status == 'checkRegister' || status == 'payment')"
          :borderless="!(status == 'checkRegister' || status == 'payment')"
          v-model="defaultInformation.cardid"
          maxlength="13"
          :rules="[
            (val) => val.length == 13 || `${'กรุณากรอก เลขประจำตัวประชาชน'}`,
            (val) =>
              /^[0-9]*$/.test(val) ||
              `${'กรุณากรอกเลขประจำตัวประชาชนให้ถูกต้อง'}`,
          ]"
          label="เลขประจำตัวประชาชน"
        />
      </div>
      <div class="col-xs-12 col-sm-2 col-md-2">
        <q-select
          :class="getClass(status == 'checkRegister' || status == 'payment')"
          :readonly="!(status == 'checkRegister' || status == 'payment')"
          :borderless="!(status == 'checkRegister' || status == 'payment')"
          :rules="[(val:string) => !!val || `${'กรุณาเลือก คำนำหน้าชื่อ'}`]"
          :outlined="status == 'checkRegister' || status == 'payment'"
          dense
          lazy-rules
          v-model="defaultInformation.prefixId"
          emit-value
          map-options
          option-label="name"
          :options="prefixOptions"
          option-value="id"
          :label="`${'คำนำหน้าชื่อ'}`"
        />
      </div>
      <div class="col-xs-12 col-sm-3 col-md-3">
        <q-input
          :class="getClass(status == 'checkRegister' || status == 'payment')"
          :outlined="status == 'checkRegister' || status == 'payment'"
          dense
          lazy-rules
          :readonly="!(status == 'checkRegister' || status == 'payment')"
          :borderless="!(status == 'checkRegister' || status == 'payment')"
          v-model="defaultInformation.firstname"
          :rules="[(val:string) => !!val || `${'กรุณากรอก ชื่อ'}`]"
          :label="`${'ชื่อ (ภาษาไทย)'}`"
        />
      </div>
      <div class="col-xs-12 col-sm-3 col-md-3">
        <q-input
          :class="getClass(status == 'checkRegister' || status == 'payment')"
          :outlined="status == 'checkRegister' || status == 'payment'"
          dense
          lazy-rules
          :readonly="!(status == 'checkRegister' || status == 'payment')"
          :borderless="!(status == 'checkRegister' || status == 'payment')"
          v-model="defaultInformation.lastname"
          :rules="[(val:string) => !!val || `${'กรุณากรอก นามสกุล'}`]"
          :label="`${'นามสกุล (ภาษาไทย)'}`"
        />
      </div>
      <div class="col-xs-12 col-sm-3 col-md-3">
        <q-select
          :class="getClass(status == 'checkRegister' || status == 'payment')"
          :readonly="!(status == 'checkRegister' || status == 'payment')"
          :borderless="!(status == 'checkRegister' || status == 'payment')"
          :rules="[(val:string) => !!val || `${'กรุณากรอก สัญชาติ'}`]"
          :outlined="status == 'checkRegister' || status == 'payment'"
          dense
          lazy-rules
          v-model="defaultInformation.nationality"
          :options="opNat"
          :label="`${'สัญชาติ'}`"
        />
      </div>
      <div class="col-xs-12 col-sm-3 col-md-3">
        <q-select
          :class="getClass(status == 'checkRegister' || status == 'payment')"
          :readonly="!(status == 'checkRegister' || status == 'payment')"
          :borderless="!(status == 'checkRegister' || status == 'payment')"
          :rules="[(val:string) => !!val || `${'กรุณาเลือก ศาสนา'}`]"
          :outlined="status == 'checkRegister' || status == 'payment'"
          dense
          lazy-rules
          v-model="defaultInformation.religionId"
          emit-value
          map-options
          option-label="name"
          :options="religionOptions"
          option-value="id"
          :label="`${'ศาสนา'}`"
        />
      </div>
      <div class="col-xs-12 col-sm-3 col-md-3">
        <datepicker
          v-model="defaultInformation.birthDate"
          :locale="'th'"
          autoApply
          :enableTimePicker="false"
          week-start="0"
          :max-date="new Date()"
          :disabled="!(status == 'checkRegister' || status == 'payment')"
        >
          <template #year="{ year }">
            {{ year + 543 }}
          </template>
          <template #year-overlay-value="{ value }">
            {{ parseInt(value + 543) }}
          </template>
          <template #trigger>
            <q-input
              :class="
                getClass(status == 'checkRegister' || status == 'payment')
              "
              :outlined="status == 'checkRegister' || status == 'payment'"
              dense
              :readonly="!(status == 'checkRegister' || status == 'payment')"
              :borderless="!(status == 'checkRegister' || status == 'payment')"
              :model-value="
                defaultInformation.birthDate == null
                  ? null
                  : date2Thai(defaultInformation.birthDate)
              "
              :rules="[(val:string) => !!val || `${'กรุณาเลือก วัน/เดือน/ปี เกิด'}`]"
              :label="`${'วัน/เดือน/ปี เกิด'}`"
            >
              <template v-slot:prepend>
                <q-icon
                  name="mdi-calendar-outline"
                  class="cursor-pointer"
                  size="22px"
                  :style="
                    status == 'checkRegister' || status == 'payment'
                      ? 'color: var(--q-primary)'
                      : 'color: var(--q-grey)'
                  "
                >
                </q-icon>
              </template>
            </q-input>
          </template>
        </datepicker>
      </div>
      <div class="col-xs-12 col-sm-3 col-md-3 q-pb-md">
        <q-input
          :class="getClass(status == 'checkRegister' || status == 'payment')"
          dense
          lazy-rules
          readonly
          borderless
          :style="
            !(status == 'checkRegister' || status == 'payment')
              ? ''
              : 'padding:0 12px;'
          "
          :model-value="
            defaultInformation.birthDate == null
              ? null
              : calAge(defaultInformation.birthDate)
          "
          :label="`${'อายุ'}`"
        />
      </div>
      <div class="col-xs-12 col-sm-3 col-md-3">
        <q-input
          :outlined="status == 'checkRegister' || status == 'payment'"
          dense
          :counter="
            status == 'checkRegister' || status == 'payment' ? true : false
          "
          lazy-rules
          type="tel"
          mask="##########"
          maxlength="10"
          :class="getClass(status == 'checkRegister' || status == 'payment')"
          :readonly="!(status == 'checkRegister' || status == 'payment')"
          :borderless="!(status == 'checkRegister' || status == 'payment')"
          v-model="defaultInformation.tel"
          :rules="[
            (val) => !!val || '* กรุณากรอกข้อมูลหมายเลขโทรศัพท์',
            (val) =>
              (val.length >= 9 && val.length <= 10 && val.startsWith('0')) ||
              'กรุณากรอกข้อมูลหมายเลขโทรศัพท์ให้ถูกต้อง',
          ]"
          :label="`${'เบอร์โทร'}`"
        />
      </div>
      <div class="col-xs-12 col-sm-3 col-md-3 q-pb-md">
        <q-input
          :class="getClass(status == 'checkRegister' || status == 'payment')"
          dense
          lazy-rules
          readonly
          borderless
          style="padding: 0 12px"
          v-model="defaultInformation.email"
          label="E-mail address"
        />
      </div>
    </div>
    <div class="row col-xs-12 col-sm-3 col-md-2 justify-center">
      <div
        class="containerimage row justify-center col-xs-6 col-sm-10 col-md-12"
      >
        <label for="file-upload" class="col-12 row">
          <q-img v-if="img == ''" src="@/assets/avatar_user.jpg" class="col-12">
            <div
              class="overlay"
              v-if="status == 'checkRegister' || status == 'payment'"
            >
              <q-icon name="mdi-camera" />
              <br />อัปเดต
            </div>
          </q-img>
          <q-img v-else :src="img" class="col-12">
            <div
              class="overlay"
              v-if="status == 'checkRegister' || status == 'payment'"
            >
              <q-icon name="mdi-camera" />
              <br />อัปเดต
            </div>
          </q-img>
        </label>
        <input
          id="file-upload"
          type="file"
          accept="image/*"
          @change="uploadImage"
          v-if="status == 'checkRegister' || status == 'payment'"
        />
      </div>
    </div>
  </q-form>
</template>

<style>
.containerimage {
  position: relative;
  width: 100%;
}

.q-img {
  display: block;
  width: 100%;
  max-height: 170px;
  padding: 1%;
  border-radius: 8px;
  border: solid 2px rgba(168, 168, 168, 0.055) !important;
  box-shadow: 0 2px 3px 0 rgba(0, 0, 0, 0.048), 0 3px 6px 0 rgba(0, 0, 0, 0.097);
}

.overlay {
  position: absolute;
  bottom: 0;
  background: rgb(0, 0, 0);
  background: rgba(0, 0, 0, 0.7);
  color: #f1f1f1;
  transition: 0.5s ease;
  width: 100%;
  height: 70px;
  opacity: 0;
  color: white;
  text-align: center;
  cursor: pointer;
  padding: 5% 0 5% 0;
}

.containerimage:hover .overlay {
  opacity: 1;
}

.q-field__bottom {
  padding: 5px 10px 0px 0px;
}

input[type="file"] {
  display: none;
}
.custom-file-upload {
  border: 1px solid #ccc;
  display: inline-block;
  padding: 6px 12px;
  cursor: pointer;
}
</style>
