<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import type { PropType } from "vue";
import http from "@/plugins/http";
import config from "@/app.config";
import type {
  Address,
  DataOption,
} from "@/modules/03_recruiting/interface/index/Main";
import {
  defaultAddress,
  changeData,
} from "@/modules/03_recruiting/interface/index/Main";
import HeaderTop from "@/modules/03_recruiting/components/top.vue";
import { useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";

const props = defineProps({
  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 candidateId = ref<string>(route.params.candidateId.toString());
const edit = ref<boolean>(true);
const myform = ref<any>({});

const districtOptions = ref<DataOption[]>([]);
const districtCOptions = ref<DataOption[]>([]);
const subdistrictOptions = ref<DataOption[]>([]);
const subdistrictCOptions = ref<DataOption[]>([]);

const mixin = useCounterMixin();
const { messageError, showLoader, hideLoader } = mixin;
const emit = defineEmits(["update:form"]);

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

watch(defaultAddress, async (count: Address, prevCount: Address) => {
  await changeData("address", count);
});

onMounted(async () => {
  await fetchData();
  if (defaultAddress.value.provinceId != null)
    await fetchDistrict(defaultAddress.value.provinceId, "1");
  if (defaultAddress.value.provinceIdC != null)
    await fetchDistrict(defaultAddress.value.provinceIdC, "2");
  if (defaultAddress.value.districtId != null)
    await fetchSubDistrict(defaultAddress.value.districtId, "1");
  if (defaultAddress.value.districtIdC != null)
    await fetchSubDistrict(defaultAddress.value.districtIdC, "2");
});

const fetchData = async () => {
  await http
    .get(config.API.candidateAddress(candidateId.value))
    .then((res) => {
      const data = res.data.result;
      defaultAddress.value.address = data.registAddress;
      defaultAddress.value.addressC = data.currentAddress;
      defaultAddress.value.provinceId = data.registProvinceId;
      defaultAddress.value.provinceIdC = data.currentProvinceId;
      defaultAddress.value.districtId = data.registDistrictId;
      defaultAddress.value.districtIdC = data.currentDistrictId;
      defaultAddress.value.subdistrictId = data.registSubDistrictId;
      defaultAddress.value.subdistrictIdC = data.currentSubDistrictId;
      defaultAddress.value.code = data.registZipCode;
      defaultAddress.value.codeC = data.currentZipCode;
      defaultAddress.value.same =
        data.registSame == true ? "1" : data.registSame == false ? "0" : null;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const selectProvince = (e: string, name: string) => {
  if (name == "1") {
    defaultAddress.value.districtId = "";
    defaultAddress.value.subdistrictId = "";
    defaultAddress.value.code = null;
  } else {
    defaultAddress.value.districtIdC = "";
    defaultAddress.value.subdistrictIdC = "";
    defaultAddress.value.codeC = null;
  }
  myform.value.resetValidation();
  fetchDistrict(e, name);
};

const selectDistrict = (e: string, name: string) => {
  if (name == "1") {
    defaultAddress.value.subdistrictId = "";
    defaultAddress.value.code = null;
  } else {
    defaultAddress.value.subdistrictIdC = "";
    defaultAddress.value.codeC = null;
  }
  myform.value.resetValidation();
  fetchSubDistrict(e, name);
};

const selectSubDistrict = (e: string, name: string) => {
  if (name == "1") {
    const findcode = subdistrictOptions.value.filter((r) => r.id == e);
    const namecode = findcode.length > 0 ? findcode[0].zipCode : null;
    defaultAddress.value.code = namecode;
  } else {
    const findcode = subdistrictCOptions.value.filter((r) => r.id == e);
    const namecode = findcode.length > 0 ? findcode[0].zipCode : null;
    defaultAddress.value.codeC = namecode;
  }
};

const fetchDistrict = async (id: string, position: 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() });
      });
      if (position == "1") {
        districtOptions.value = option;
      } else {
        districtCOptions.value = option;
      }
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const fetchSubDistrict = async (id: string, position: string) => {
  showLoader();
  await http
    .get(config.API.listSubDistrict(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(),
          zipCode: r.zipCode != null ? r.zipCode : null,
        });
      });
      if (position == "1") {
        subdistrictOptions.value = option;
      } else {
        subdistrictCOptions.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>

<template>
  <HeaderTop
    v-model:edit="edit"
    header="ข้อมูลที่อยู่"
    icon="mdi-map-marker"
    :addData="true"
    :editOnly="false"
    :editData="false"
  />
  <q-form ref="myform">
    <div class="row col-12 items-center q-col-gutter-x-sm q-col-gutter-y-xs">
      <div class="col-xs-12">
        <q-input
          :class="getClass(status == 'checkRegister' || status == 'payment')"
          :outlined="status == 'checkRegister' || status == 'payment'"
          dense
          lazy-rules
          type="textarea"
          autogrow
          :readonly="!(status == 'checkRegister' || status == 'payment')"
          :borderless="!(status == 'checkRegister' || status == 'payment')"
          v-model="defaultAddress.address"
          :rules="[(val) => !!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="defaultAddress.provinceId"
          emit-value
          map-options
          option-label="name"
          :options="provinceOptions"
          option-value="id"
          :label="`${'จังหวัด'}`"
          @update:model-value="(value) => selectProvince(value, '1')"
        />
      </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="defaultAddress.districtId"
          emit-value
          map-options
          option-label="name"
          :options="districtOptions"
          option-value="id"
          :label="`${'เขต / อำเภอ'}`"
          @update:model-value="(value) => selectDistrict(value, '1')"
        />
      </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="defaultAddress.subdistrictId"
          emit-value
          map-options
          option-label="name"
          :options="subdistrictOptions"
          option-value="id"
          :label="`${'แขวง / ตำบล '}`"
          @update:model-value="(value) => selectSubDistrict(value, '1')"
        />
      </div>
      <div class="col-xs-12 col-sm-3 col-md-3">
        <q-input
          :class="getClass(status == 'checkRegister' || status == 'payment')"
          dense
          lazy-rules
          readonly
          borderless
          v-model="defaultAddress.code"
          :style="
            !(status == 'checkRegister' || status == 'payment')
              ? ''
              : 'padding:0 12px;'
          "
          :label="`${'รหัสไปรษณีย์'}`"
        />
      </div>
      <div class="col-xs-12 q-gutter-sm items-center flex q-mb-sm row">
        <div class="text-bold" v-if="$q.screen.gt.xs">
          ที่อยู่ปัจจุบันตรงกับที่อยู่ตามทะเบียนบ้าน
        </div>
        <div class="text-bold col-12 q-pt-sm" v-else>
          ที่อยู่ปัจจุบันตรงกับที่อยู่ตามทะเบียนบ้าน
        </div>
        <q-radio
          v-model="defaultAddress.same"
          checked-icon="task_alt"
          unchecked-icon="panorama_fish_eye"
          val="1"
          label="ใช่"
          dense
          :disable="!(status == 'checkRegister' || status == 'payment')"
        />
        <q-radio
          v-model="defaultAddress.same"
          checked-icon="task_alt"
          unchecked-icon="panorama_fish_eye"
          val="0"
          label="ไม่"
          dense
          :disable="!(status == 'checkRegister' || status == 'payment')"
        />
      </div>

      <div class="col-xs-12" v-if="defaultAddress.same == '0'">
        <q-input
          :class="getClass(status == 'checkRegister' || status == 'payment')"
          :outlined="status == 'checkRegister' || status == 'payment'"
          dense
          lazy-rules
          type="textarea"
          autogrow
          :readonly="!(status == 'checkRegister' || status == 'payment')"
          :borderless="!(status == 'checkRegister' || status == 'payment')"
          v-model="defaultAddress.addressC"
          :rules="[(val) => !!val || `${'กรุณากรอก ที่อยู่ปัจจุบัน'}`]"
          :label="`${'ที่อยู่ปัจจุบัน'}`"
        />
      </div>
      <div
        class="col-xs-12 col-sm-3 col-md-3"
        v-if="defaultAddress.same == '0'"
      >
        <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="defaultAddress.provinceIdC"
          emit-value
          map-options
          option-label="name"
          :options="provinceOptions"
          option-value="id"
          :label="`${'จังหวัด'}`"
          @update:model-value="(value) => selectProvince(value, '2')"
        />
      </div>
      <div
        class="col-xs-12 col-sm-3 col-md-3"
        v-if="defaultAddress.same == '0'"
      >
        <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="defaultAddress.districtIdC"
          emit-value
          map-options
          option-label="name"
          :options="districtCOptions"
          option-value="id"
          :label="`${'เขต / อำเภอ'}`"
          @update:model-value="(value) => selectDistrict(value, '2')"
        />
      </div>
      <div
        class="col-xs-12 col-sm-3 col-md-3"
        v-if="defaultAddress.same == '0'"
      >
        <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="defaultAddress.subdistrictIdC"
          emit-value
          map-options
          option-label="name"
          :options="subdistrictCOptions"
          option-value="id"
          :label="`${'แขวง / ตำบล '}`"
          @update:model-value="(value) => selectSubDistrict(value, '2')"
        />
      </div>
      <div
        class="col-xs-12 col-sm-3 col-md-3"
        v-if="defaultAddress.same == '0'"
      >
        <q-input
          :class="getClass(status == 'checkRegister' || status == 'payment')"
          dense
          lazy-rules
          readonly
          borderless
          v-model="defaultAddress.codeC"
          :style="
            !(status == 'checkRegister' || status == 'payment')
              ? ''
              : 'padding:0 12px;'
          "
          :label="`${'รหัสไปรษณีย์'}`"
        />
      </div>
    </div>
  </q-form>
</template>
