<!-- card ข้อมูลที่อยู่ -->
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";
import type { zipCodeOption } from "@/modules/05_placement/components/PersonalDetail/profileType";

import HeaderTop from "@/modules/05_placement/components/PersonalDetail/Information/top.vue";

import { useRoute } from "vue-router";
import { AddressDataDefualt } from "@/modules//05_placement/interface/index/Main";

import type {
  AddressOps,
  Address as AddressType,
  optionData,
} from "@/modules//05_placement/interface/index/Main";
import type { PropType } from "vue";

const props = defineProps({
  statusEdit: {
    type: Boolean,
    required: true,
  },
  notiNoEdit: {
    type: Function,
    default: () => console.log("not function"),
  },
  fetch: {
    type: Function,
    default: () => console.log("not function"),
  },
  data: {
    type: Object as PropType<AddressType>,
    default: AddressDataDefualt,
  },
});
const emit = defineEmits(["update:statusEdit"]);

const route = useRoute();
const $q = useQuasar();
const mixin = useCounterMixin();
const { date2Thai, success, messageError, showLoader, hideLoader } = mixin;
const edit = ref<boolean>(false);
const addressData = ref<AddressType>(props.data);
const myform = ref<any>();
const codep = ref<string>("");
const codec = ref<string>("");
const Ops = ref<AddressOps>({
  provinceOps: [],
  districtOps: [],
  districtCOps: [],
  subdistrictOps: [],
  subdistrictCOps: [],
});
const OpsFilter = ref<AddressOps>({
  provinceOps: [],
  districtOps: [],
  districtCOps: [],
  subdistrictOps: [],
  subdistrictCOps: [],
});

onMounted(async () => {
  await getNewData();
  emit("update:statusEdit", false);
});

const filterSelector = (val: any, update: Function, refData: string) => {
  switch (refData) {
    case "provinceOps":
      update(() => {
        Ops.value.provinceOps = OpsFilter.value.provinceOps.filter(
          (v: optionData) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "districtOps":
      update(() => {
        Ops.value.districtOps = OpsFilter.value.districtOps.filter(
          (v: optionData) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "districtCOps":
      update(() => {
        Ops.value.districtCOps = OpsFilter.value.districtCOps.filter(
          (v: optionData) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "subdistrictOps":
      update(() => {
        Ops.value.subdistrictOps = OpsFilter.value.subdistrictOps.filter(
          (v: optionData) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "subdistrictCOps":
      update(() => {
        Ops.value.subdistrictCOps = OpsFilter.value.subdistrictCOps.filter(
          (v: optionData) => v.name.indexOf(val) > -1
        );
      });
      break;

    default:
      break;
  }
};

const refreshData = async () => {
  myform.value.reset();
  await getNewData();
};

const getNewData = async () => {
  await props.fetch();
  await fetchProvince();
  await fetchDistrict(addressData.value.registProvinceId, "1");
  await fetchDistrict(addressData.value.currentProvinceId, "2");
  await fetchSubDistrict(addressData.value.registDistrictId, "1");
  await fetchSubDistrict(addressData.value.currentDistrictId, "2");
};

const editData = async () => {
  const body = {
    registrationSame: addressData.value.registSame == "1",
    registrationAddress: addressData.value.registAddress,
    registrationSubDistrictId: addressData.value.registSubDistrictId,
    registrationDistrictId: addressData.value.registDistrictId,
    registrationProvinceId: addressData.value.registProvinceId,
    registrationZipCode: codep.value,
    currentAddress:
      addressData.value.registSame == "1"
        ? addressData.value.registAddress
        : addressData.value.currentAddress,
    currentSubDistrictId:
      addressData.value.registSame == "1"
        ? addressData.value.registSubDistrictId
        : addressData.value.currentSubDistrictId,
    currentDistrictId:
      addressData.value.registSame == "1"
        ? addressData.value.registDistrict
        : addressData.value.currentDistrictId,
    currentProvinceId:
      addressData.value.registSame == "1"
        ? addressData.value.registProvinceId
        : addressData.value.currentProvinceId,
    currentZipCode:
      addressData.value.registSame == "1" ? codep.value : codec.value,
  };
  showLoader();
  await http
    .put(
      config.API.placementAddressId(route.params.personalId.toString()),
      body
    )
    .then((res) => {
      success($q, "แก้ไขข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      edit.value = false;
      emit("update:statusEdit", false);
      await getNewData();
    });
};

const saveData = async () => {
  await myform.value.validate().then(async (success: boolean) => {
    if (success) {
      await editData();
    }
  });
};

const selectProvince = async (e: string | null, name: string) => {
  if (e != null) {
    if (name == "1") {
      addressData.value.registDistrictId = "";
      addressData.value.registSubDistrictId = "";
      codep.value = "";
    } else {
      addressData.value.currentDistrictId = "";
      addressData.value.currentSubDistrictId = "";
      codec.value = "";
    }
    myform.value.resetValidation();
    await fetchDistrict(e, name);
  }
};

const selectDistrict = async (e: string | null, name: string) => {
  if (e != null) {
    if (name == "1") {
      addressData.value.registSubDistrictId = "";
      codep.value = "";
    } else {
      addressData.value.currentSubDistrictId = "";
      codec.value = "";
    }
    myform.value.resetValidation();
    await fetchSubDistrict(e, name);
  }
};

const selectSubDistrict = (e: string | null, name: string) => {
  if (e != null) {
    if (name == "1") {
      const findcode = Ops.value.subdistrictOps.filter((r) => r.id == e);
      const namecode = findcode.length > 0 ? findcode[0].zipCode : "";
      codep.value = namecode;
    } else {
      const findcode = Ops.value.subdistrictCOps.filter((r) => r.id == e);
      const namecode = findcode.length > 0 ? findcode[0].zipCode : "";
      codec.value = namecode;
    }
  }
};

const fetchProvince = async () => {
  showLoader();
  await http
    .get(config.API.province)
    .then((res) => {
      const data = res.data.result;
      let option: optionData[] = [];
      data.map((r: any) => {
        option.push({ id: r.id.toString(), name: r.name.toString() });
      });
      Ops.value.provinceOps = option;
      OpsFilter.value.provinceOps = option;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const fetchDistrict = async (id: string | null, position: string) => {
  if (id != null && id != "") {
    showLoader();
    await http
      .get(config.API.listDistrict(id))
      .then((res) => {
        const data = res.data.result;
        let option: optionData[] = [];
        data.map((r: any) => {
          option.push({ id: r.id.toString(), name: r.name.toString() });
        });
        if (position == "1") {
          Ops.value.districtOps = option;
          OpsFilter.value.districtOps = option;
        } else {
          Ops.value.districtCOps = option;
          OpsFilter.value.districtCOps = option;
        }
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  }
};

const fetchSubDistrict = async (id: string | null, position: string) => {
  if (id != null && id != "") {
    showLoader();
    await http
      .get(config.API.listSubDistrict(id))
      .then((res) => {
        const data = res.data.result;
        let option: zipCodeOption[] = [];
        data.map((r: any) => {
          option.push({
            id: r.id.toString(),
            name: r.name.toString(),
            zipCode: r.zipCode.toString(),
          });
        });
        if (position == "1") {
          Ops.value.subdistrictOps = option;
          OpsFilter.value.subdistrictOps = option;
        } else {
          Ops.value.subdistrictCOps = option;
          OpsFilter.value.subdistrictCOps = option;
        }
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  }
};

const changeBtn = async () => {
  if (edit.value == true) {
    if (props.statusEdit === true) {
      edit.value = false;
      props.notiNoEdit();
    } else {
      emit("update:statusEdit", true);
    }
  } else {
    emit("update:statusEdit", false);
  }
};

const getClass = (val: boolean) => {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
};
</script>
<template>
  <q-card class="col-12 q-px-lg q-py-md q-mt-md no-border">
    <HeaderTop
      v-model:edit="edit"
      header="ข้อมูลที่อยู่"
      icon="mdi-map-marker"
      :save="saveData"
      :history="false"
      :changeBtn="changeBtn"
      :disable="statusEdit"
      :cancel="refreshData"
    />
    <q-form ref="myform">
      <div class="row col-12 items-center q-col-gutter-x-xs q-col-gutter-y-xs">
        <div class="col-xs-12">
          <q-input
            :class="getClass(edit)"
            hide-bottom-space
            :outlined="edit"
            dense
            lazy-rules
            type="textarea"
            autogrow
            :readonly="!edit"
            :borderless="!edit"
            v-model="addressData.registAddress"
            :rules="[(val:string) => !!val || `${'กรุณากรอก ที่อยู่ตามทะเบียนบ้าน'}`]"
            :label="`${'ที่อยู่ตามทะเบียนบ้าน'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <selector
            :hide-dropdown-icon="!edit"
            hide-bottom-space
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :rules="[(val:string) => !!val || `${'กรุณาเลือก จังหวัด'}`]"
            :outlined="edit"
            dense
            lazy-rules
            v-model="addressData.registProvinceId"
            emit-value
            map-options
            option-label="name"
            :options="Ops.provinceOps"
            option-value="id"
            :label="`${'จังหวัด'}`"
            @update:model-value="(value:string) => selectProvince(value, '1')"
            use-input
            input-debounce="0"
            @filter="(inputValue:string,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'provinceOps'
                      ) "
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <selector
            :hide-dropdown-icon="!edit"
            hide-bottom-space
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :rules="[(val:string) => !!val || `${'กรุณาเลือก เขต / อำเภอ'}`]"
            :outlined="edit"
            dense
            lazy-rules
            v-model="addressData.registDistrictId"
            emit-value
            map-options
            option-label="name"
            :options="Ops.districtOps"
            option-value="id"
            :label="`${'เขต / อำเภอ'}`"
            @update:model-value="(value:string) => selectDistrict(value, '1')"
            use-input
            input-debounce="0"
            @filter="(inputValue:string,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'districtOps'
                      ) "
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <selector
            :hide-dropdown-icon="!edit"
            hide-bottom-space
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :rules="[(val:string) => !!val || `${'กรุณาเลือก ตำบล / แขวง'}`]"
            :outlined="edit"
            dense
            lazy-rules
            v-model="addressData.registSubDistrictId"
            emit-value
            map-options
            option-label="name"
            :options="Ops.subdistrictOps"
            option-value="id"
            :label="`${'ตำบล / แขวง'}`"
            @update:model-value="(value:string) => selectSubDistrict(value, '1')"
            use-input
            input-debounce="0"
            @filter="(inputValue:string,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'subdistrictOps'
                      ) "
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-input
            :class="getClass(edit)"
            hide-bottom-space
            dense
            lazy-rules
            readonly
            borderless
            v-model="codep"
            :style="!edit ? '' : 'padding:0 12px;'"
            :label="`${'รหัสไปรษณีย์'}`"
          />
        </div>
        <div class="col-12 q-pt-lg"><q-separator /></div>
        <div class="col-xs-12 q-gutter-sm items-center flex q-my-sm">
          <label class="text-bold"
            >ที่อยู่ปัจจุบันตรงกับที่อยู่ตามทะเบียนบ้าน</label
          >
          <q-radio
            v-model="addressData.registSame"
            checked-icon="task_alt"
            unchecked-icon="panorama_fish_eye"
            val="1"
            label="ใช่"
            dense
            :disable="!edit"
          />
          <q-radio
            v-model="addressData.registSame"
            checked-icon="task_alt"
            unchecked-icon="panorama_fish_eye"
            val="0"
            label="ไม่"
            dense
            :disable="!edit"
          />
        </div>

        <div class="col-xs-12" v-if="addressData.registSame == '0'">
          <q-input
            :class="getClass(edit)"
            hide-bottom-space
            :outlined="edit"
            dense
            lazy-rules
            type="textarea"
            autogrow
            :readonly="!edit"
            :borderless="!edit"
            v-model="addressData.currentAddress"
            :rules="[(val:string) => !!val || `${'กรุณากรอก ที่อยู่ปัจจุบัน'}`]"
            :label="`${'ที่อยู่ปัจจุบัน'}`"
          />
        </div>
        <div
          class="col-xs-6 col-sm-3 col-md-3"
          v-if="addressData.registSame == '0'"
        >
          <selector
            :hide-dropdown-icon="!edit"
            hide-bottom-space
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :rules="[(val:string) => !!val || `${'กรุณาเลือก จังหวัด'}`]"
            :outlined="edit"
            dense
            lazy-rules
            v-model="addressData.currentProvinceId"
            emit-value
            map-options
            option-label="name"
            :options="Ops.provinceOps"
            option-value="id"
            :label="`${'จังหวัด'}`"
            @update:model-value="(value:string) => selectProvince(value, '2')"
            use-input
            input-debounce="0"
            @filter="(inputValue:string,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'provinceOps'
                      ) "
          />
        </div>
        <div
          class="col-xs-6 col-sm-3 col-md-3"
          v-if="addressData.registSame == '0'"
        >
          <selector
            :hide-dropdown-icon="!edit"
            hide-bottom-space
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :rules="[(val:string) => !!val || `${'กรุณาเลือก เขต / อำเภอ'}`]"
            :outlined="edit"
            dense
            lazy-rules
            v-model="addressData.currentDistrictId"
            emit-value
            map-options
            option-label="name"
            :options="Ops.districtCOps"
            option-value="id"
            :label="`${'เขต / อำเภอ'}`"
            @update:model-value="(value:string) => selectDistrict(value, '2')"
            use-input
            input-debounce="0"
            @filter="(inputValue:string,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'districtCOps'
                      ) "
          />
        </div>
        <div
          class="col-xs-6 col-sm-3 col-md-3"
          v-if="addressData.registSame == '0'"
        >
          <selector
            :hide-dropdown-icon="!edit"
            hide-bottom-space
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :rules="[(val:string) => !!val || `${'กรุณาเลือก ตำบล / แขวง'}`]"
            :outlined="edit"
            dense
            lazy-rules
            v-model="addressData.currentSubDistrictId"
            emit-value
            map-options
            option-label="name"
            :options="Ops.subdistrictCOps"
            option-value="id"
            :label="`${'ตำบล / แขวง'}`"
            @update:model-value="(value:string) => selectSubDistrict(value, '2')"
            use-input
            input-debounce="0"
            @filter="(inputValue:string,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'subdistrictCOps'
                      ) "
          />
        </div>
        <div
          class="col-xs-6 col-sm-3 col-md-3"
          v-if="addressData.registSame == '0'"
        >
          <q-input
            :class="getClass(edit)"
            hide-bottom-space
            dense
            lazy-rules
            readonly
            borderless
            v-model="codec"
            :style="!edit ? '' : 'padding:0 12px;'"
            :label="`${'รหัสไปรษณีย์'}`"
          />
        </div>
      </div>
    </q-form>
  </q-card>
</template>
