<!-- card ข้อมูลส่วนตัว -->
<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-2 col-md-2">
        <q-select
          :class="getClass(status == 'checkRegister' || status == 'payment')"
          :readonly="!(status == 'checkRegister' || status == 'payment')"
          :borderless="!(status == 'checkRegister' || status == 'payment')"
          :rules="[(val) => !!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-5 col-md-5">
        <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) => !!val || `${'กรุณากรอก ชื่อ'}`]"
          :label="`${'ชื่อ'}`"
        />
      </div>
      <div class="col-xs-12 col-sm-5 col-md-5">
        <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) => !!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.nationality"
          :rules="[(val) => !!val || `${'กรุณากรอก สัญชาติ'}`]"
          :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
              lazy-rules
              :readonly="!(status == 'checkRegister' || status == 'payment')"
              :borderless="!(status == 'checkRegister' || status == 'payment')"
              :model-value="
                defaultInformation.birthDate == null
                  ? null
                  : date2Thai(defaultInformation.birthDate)
              "
              :rules="[(val) => !!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-select
          :class="getClass(status == 'checkRegister' || status == 'payment')"
          :readonly="!(status == 'checkRegister' || status == 'payment')"
          :borderless="!(status == 'checkRegister' || status == 'payment')"
          :rules="[(val) => !!val || `${'กรุณาเลือก สถานภาพ'}`]"
          :outlined="status == 'checkRegister' || status == 'payment'"
          dense
          lazy-rules
          v-model="defaultInformation.relationshipId"
          emit-value
          map-options
          option-label="name"
          :options="relationshipOptions"
          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
          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-3 col-md-3">
        <q-select
          :class="getClass(status == 'checkRegister' || status == 'payment')"
          :readonly="!(status == 'checkRegister' || status == 'payment')"
          :borderless="!(status == 'checkRegister' || status == 'payment')"
          :rules="[(val) => !!val || `${'กรุณาเลือก จังหวัด'}`]"
          :outlined="status == 'checkRegister' || status == 'payment'"
          dense
          lazy-rules
          v-model="defaultInformation.provinceId"
          emit-value
          map-options
          option-label="name"
          :options="provinceOptions"
          option-value="id"
          :label="`${'ออกให้ ณ จังหวัด'}`"
          @update:model-value="(value) => selectProvince(value)"
        />
      </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) => !!val || `${'กรุณากรอกอำเภอ'}`]"
          :outlined="status == 'checkRegister' || status == 'payment'"
          dense
          lazy-rules
          v-model="defaultInformation.districtId"
          emit-value
          map-options
          option-label="name"
          :options="districtOptions"
          option-value="id"
          :label="`${'ออกให้ ณ อำเภอ'}`"
        />
      </div>

      <div class="col-xs-12 col-sm-3 col-md-3">
        <datepicker
          v-model="defaultInformation.cardIdDate"
          :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
              lazy-rules
              :readonly="!(status == 'checkRegister' || status == 'payment')"
              :borderless="!(status == 'checkRegister' || status == 'payment')"
              :model-value="
                defaultInformation.cardIdDate == null
                  ? null
                  : date2Thai(defaultInformation.cardIdDate)
              "
              :rules="[
                (val) => !!val || `${'กรุณาเลือก วัน/เดือน/ปี ที่ออกบัตร'}`,
              ]"
              :label="`${'วัน/เดือน/ปี ที่ออกบัตร'}`"
            >
              <template v-slot:prepend>
                <q-icon
                  name="mdi-calendar-outline"
                  class="cursor-pointer"
                  :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-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.length == 10 || `${'กรุณากรอก โทรศัพท์'}`,
            (val) =>
              /^[0-9]*$/.test(val) || `${'กรุณากรอกข้อมูลโทรศัพท์ให้ถูกต้อง'}`,
          ]"
          :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.phone"
          :rules="[
            (val) => val.length == 10 || `${'กรุณากรอก โทรศัพท์มือถือ'}`,
            (val) =>
              /^[0-9]*$/.test(val) ||
              `${'กรุณากรอกข้อมูลโทรศัพท์มือถือให้ถูกต้อง'}`,
          ]"
          :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>
    <div class="col-xs-12 col-sm-9 col-md-12">
      <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.knowledge"
        label="ความรู้ความสามารถพิเศษ"
        type="textarea"
      />
    </div>
  </q-form>
</template>
<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";
import type { PropType } from "vue";
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";
import { useRoute } from "vue-router";
import keycloak from "@/plugins/keycloak";
import { useQuasar } from "quasar";

const props = defineProps({
  prefixOptions: {
    type: Array as PropType<DataOption[]>,
    required: true,
  },
  relationshipOptions: {
    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 mixin = useCounterMixin();
const { date2Thai, calAge, modalError, success } = mixin;
const districtOptions = ref<DataOption[]>([]);
const route = useRoute();
const candidateId = ref<string>(route.params.candidateId.toString());
const edit = ref<boolean>(true);
const myform = ref<any>({});
const img = ref<string>("");
const fileProfile = ref<File[]>([]);

const { messageError, showLoader, hideLoader } = mixin;

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

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

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

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

const fetchData = async () => {
  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.relationshipId = data.relationshipId;
      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(() => {
      defaultInformation.value.email =
        keycloak.tokenParsed == null ? "" : keycloak.tokenParsed.email;
      defaultInformation.value.firstname =
        keycloak.tokenParsed == null ? "" : keycloak.tokenParsed.given_name;
      defaultInformation.value.lastname =
        keycloak.tokenParsed == null ? "" : keycloak.tokenParsed.family_name;
    })
    .finally(() => {
      hideLoader();
    });
};

const fetchImgData = async () => {
  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();
    });
};

const uploadImage = async (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;
  }
};

const selectProvince = (val: string) => {
  defaultInformation.value.districtId = "";
  myform.value.resetValidation();
  fetchDistrict(val);
};

const fetchDistrict = async (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();
    });
};

const getClass = (val: boolean) => {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
};
</script>

<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>
