<template>
  <q-card flat bordered class="col-12 q-px-lg q-py-md q-mt-md">
    <HeaderTop
      v-model:edit="edit"
      header="ข้อมูลที่อยู่"
      icon="mdi-map-marker"
      :save="saveData"
      :history="!statusAdd()"
      :changeBtn="changeBtn"
      :disable="statusEdit"
      :cancel="refreshData"
      :historyClick="clickHistory"
      :addEmployee="statusAdd()"
    />
    <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.address"
            :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.provinceId"
            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.districtId"
            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.subdistrictId"
            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.same"
            checked-icon="task_alt"
            unchecked-icon="panorama_fish_eye"
            val="1"
            label="ใช่"
            dense
            :disable="!edit"
          />
          <q-radio
            v-model="addressData.same"
            checked-icon="task_alt"
            unchecked-icon="panorama_fish_eye"
            val="0"
            label="ไม่"
            dense
            :disable="!edit"
          />
        </div>

        <div class="col-xs-12" v-if="addressData.same == '0'">
          <q-input
            :class="getClass(edit)"
            hide-bottom-space
            :outlined="edit"
            dense
            lazy-rules
            type="textarea"
            autogrow
            :readonly="!edit"
            :borderless="!edit"
            v-model="addressData.addressC"
            :rules="[(val:string) => !!val || `${'กรุณากรอก ที่อยู่ปัจจุบัน'}`]"
            :label="`${'ที่อยู่ปัจจุบัน'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3" v-if="addressData.same == '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.provinceIdC"
            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.same == '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.districtIdC"
            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.same == '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.subdistrictIdC"
            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.same == '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>
  <HistoryTable
    :rows="rowsHistory"
    :columns="columnsHistory"
    :filter="filterHistory"
    :visible-columns="visibleColumnsHistory"
    v-model:modal="modalHistory"
    v-model:inputfilter="filterHistory"
    v-model:inputvisible="visibleColumnsHistory"
    v-model:tittle="tittleHistory"
  >
    <template #columns="props">
      <q-tr :props="props">
        <q-td v-for="col in props.cols" :key="col.name" :props="props">
          <div v-if="col.name == 'createdAt'" class="table_ellipsis">
            {{ date2Thai(col.value) }}
          </div>
          <div
            v-else-if="col.name == 'registrationSame'"
            class="table_ellipsis"
          >
            {{ col.value ? "ใช่" : "ไม่" }}
          </div>
          <div v-else class="table_ellipsis">
            {{ col.value }}
          </div>
        </q-td>
      </q-tr>
    </template>
  </HistoryTable>
</template>
<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 {
  Address,
  DataOption,
  zipCodeOption,
} from "@/components/information/interface/profileType";
import { defaultAddress } from "@/components/information/interface/profileType";
import HeaderTop from "@/components/information/top.vue";
import type { RequestItemsHistoryObject } from "@/components/information/interface/request/Address";
import type { ResponseObject } from "@/components/information/interface/response/Address";
import HistoryTable from "@/components/TableHistory.vue";
import { useRoute } from "vue-router";
import type { AddressOps } from "@/components/information/interface/index/Main";
import type { QTableProps } from "quasar";

const props = defineProps({
  statusEdit: {
    type: Boolean,
    required: true,
  },
  statusAdd: {
    type: Boolean,
    default: false,
  },
});
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<Address>(defaultAddress);
const myform = ref<any>();
const codep = ref<string>("");
const codec = ref<string>("");
const rowsHistory = ref<RequestItemsHistoryObject[]>([]); //select data history
const tittleHistory = ref<string>("ประวัติแก้ไขข้อมูลที่อยู่"); //
const filterHistory = ref<string>(""); //search data table history
const modalHistory = ref<boolean>(false); //modal ประวัติการแก้ไขข้อมูล
const Ops = ref<AddressOps>({
  provinceOps: [],
  districtOps: [],
  districtCOps: [],
  subdistrictOps: [],
  subdistrictCOps: [],
});
const OpsFilter = ref<AddressOps>({
  provinceOps: [],
  districtOps: [],
  districtCOps: [],
  subdistrictOps: [],
  subdistrictCOps: [],
});
const columnsHistory = ref<QTableProps["columns"]>([
  {
    name: "registrationAddress",
    align: "left",
    label: "ที่อยู่ตามทะเบียนบ้าน",
    sortable: true,
    field: "registrationAddress",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "registrationProvince",
    align: "left",
    label: "จังหวัดตามทะเบียนบ้าน",
    sortable: true,
    field: "registrationProvince",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "registrationDistrict",
    align: "left",
    label: "เขต/อำเภอตามทะเบียนบ้าน",
    sortable: true,
    field: "registrationDistrict",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "registrationSubDistrict",
    align: "left",
    label: "แขวง/ตำบลตามทะเบียนบ้าน",
    sortable: true,
    field: "registrationSubDistrict",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "registrationZipCode",
    align: "left",
    label: "รหัสไปรษณีย์ตามทะเบียนบ้าน",
    sortable: true,
    field: "registrationZipCode",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "registrationSame",
    align: "left",
    label: "ที่อยู่ปัจจุบันตรงกับที่อยู่ตามทะเบียนบ้าน",
    sortable: true,
    field: "registrationSame",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "currentAddress",
    align: "left",
    label: "ที่อยู่ปัจจุบัน",
    sortable: true,
    field: "currentAddress",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "currentProvince",
    align: "left",
    label: "จังหวัดปัจจุบัน",
    sortable: true,
    field: "currentProvince",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "currentDistrict",
    align: "left",
    label: "เขต/อำเภอปัจจุบัน",
    sortable: true,
    field: "currentDistrict",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "currentSubDistrict",
    align: "left",
    label: "แขวง/ตำบลปัจจุบัน",
    sortable: true,
    field: "currentSubDistrict",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "currentZipCode",
    align: "left",
    label: "รหัสไปรษณีย์ปัจจุบัน",
    sortable: true,
    field: "currentZipCode",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "createdFullName",
    align: "left",
    label: "ผู้ดำเนินการ",
    sortable: true,
    field: "createdFullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "createdAt",
    align: "left",
    label: "วันที่แก้ไข",
    sortable: true,
    field: "createdAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const visibleColumnsHistory = ref<String[]>([
  "currentAddress",
  "currentDistrict",
  "currentProvince",
  "currentSubDistrict",
  "currentZipCode",
  "registrationAddress",
  "registrationDistrict",
  "registrationProvince",
  "registrationSame",
  "registrationSubDistrict",
  "registrationZipCode",
  "createdFullName",
  "createdAt",
]);

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

const statusAdd = () => props.statusAdd;

const defaultAdd = () => {
  if (props.statusAdd) {
    edit.value = props.statusAdd;
    addressData.value = {
      address: null,
      provinceId: null,
      districtId: null,
      subdistrictId: null,
      addressC: null,
      provinceIdC: null,
      districtIdC: null,
      subdistrictIdC: null,
      same: "0",
    };
  }
};

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

    default:
      break;
  }
};

/**
 * ฟังชั้นดูข้อมูลประวัติแก้ไขข้อมูลที่เลือก
 */
const clickHistory = async () => {
  modalHistory.value = true;
  showLoader();
  await http
    .get(config.API.profileAdrsHisId(route.params.id.toString()))
    .then((res) => {
      let data = res.data.result;
      rowsHistory.value = [];
      data.map((e: RequestItemsHistoryObject) => {
        rowsHistory.value.push({
          currentAddress: e.currentAddress,
          currentDistrict: e.currentDistrict,
          currentProvince: e.currentProvince,
          currentSubDistrict: e.currentSubDistrict,
          currentZipCode: e.currentZipCode,
          registrationSame: e.registrationSame,
          registrationAddress: e.registrationAddress,
          registrationDistrict: e.registrationDistrict,
          registrationProvince: e.registrationProvince,
          registrationSubDistrict: e.registrationSubDistrict,
          registrationZipCode: e.registrationZipCode,
          createdFullName: e.createdFullName,
          createdAt: new Date(e.createdAt),
        });
      });
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

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

const getNewData = async () => {
  await fetchData();
  await fetchProvince();
  await fetchDistrict(addressData.value.provinceId, "1");
  await fetchDistrict(addressData.value.provinceIdC, "2");
  await fetchSubDistrict(addressData.value.districtId, "1");
  await fetchSubDistrict(addressData.value.districtIdC, "2");
};

const fetchData = async () => {
  if (route.params.id) {
    showLoader();
    await http
      .get(config.API.profileAdrsId(route.params.id.toString()))
      .then((res) => {
        const data: ResponseObject = res.data.result;
        addressData.value.address = data.registrationAddress;
        addressData.value.addressC = data.currentAddress;
        addressData.value.districtId = data.registrationDistrictId;
        addressData.value.districtIdC = data.currentDistrictId;
        addressData.value.provinceId = data.registrationProvinceId;
        addressData.value.provinceIdC = data.currentProvinceId;
        addressData.value.subdistrictId = data.registrationSubDistrictId;
        addressData.value.subdistrictIdC = data.currentSubDistrictId;
        addressData.value.same = data.registrationSame ? "1" : "0";
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  }
};

const editData = async () => {
  const body: ResponseObject = {
    registrationSame: addressData.value.same == "1",
    registrationAddress: addressData.value.address,
    registrationSubDistrictId: addressData.value.subdistrictId,
    registrationDistrictId: addressData.value.districtId,
    registrationProvinceId: addressData.value.provinceId,
    registrationZipCode: codep.value,
    currentAddress:
      addressData.value.same == "1"
        ? addressData.value.address
        : addressData.value.addressC,
    currentSubDistrictId:
      addressData.value.same == "1"
        ? addressData.value.subdistrictId
        : addressData.value.subdistrictIdC,
    currentDistrictId:
      addressData.value.same == "1"
        ? addressData.value.districtId
        : addressData.value.districtIdC,
    currentProvinceId:
      addressData.value.same == "1"
        ? addressData.value.provinceId
        : addressData.value.provinceIdC,
    currentZipCode: addressData.value.same == "1" ? codep.value : codec.value,
    createdAt: new Date(),
    createdFullName: "-",
  };
  showLoader();
  await http
    .put(config.API.profileAdrsId(route.params.id.toString()), body)
    .then((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      edit.value = false;
      emit("update:statusEdit", false);
      await getNewData();
    });
};

const addData = async () => {
  //     showLoader();
  //   await http
  //     .put(config.API.profileInforId(route.params.id.toString()), body)
  //     .then((res) => {
  //       success($q, "บันทึกข้อมูลสำเร็จ");
  //     })
  //     .catch((e) => {
  //       messageError($q, e);
  //     })
  //     .finally(async () => {
  //       edit.value = false;
  //       emit("update:statusEdit", false);
  //       await fetchData();
  //       await changeBirth(informaData.value.birthDate ?? new Date());
  //     });
};

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

const selectProvince = async (e: string | null, name: string) => {
  if (e != null) {
    if (name == "1") {
      addressData.value.districtId = "";
      addressData.value.subdistrictId = "";
      codep.value = "";
    } else {
      addressData.value.districtIdC = "";
      addressData.value.subdistrictIdC = "";
      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.subdistrictId = "";
      codep.value = "";
    } else {
      addressData.value.subdistrictIdC = "";
      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: DataOption[] = [];
      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: DataOption[] = [];
        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;
    } 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>
