<script setup lang="ts">
import { useQuasar, type QTableProps } from "quasar";
import { ref, reactive, onMounted } from "vue";

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

/** import type */
import type {
  Address,
  Provinces,
  Districts,
  SubDistricts,
} from "@/modules/10_registry/interface/response/01_Information";

/** import component */
import DialogHistory from "@/modules/10_registry/Dialog/DialogHistory.vue";
import SkeletonAddress from "@/modules/10_registry/components/skeleton/Address.vue";

const $q = useQuasar();
const dataStore = useDataStore();
const { messageError, date2Thai } = useCounterMixin();

const isLoading = ref<boolean>(false); // สถานะการโหลดข้อมูล
const isLoadingHistory = ref<boolean>(false); // สถานะการโหลดประวัติข้อมูลที่อยู่
const link = ref<string>(""); // ลิงก์สำหรับดึงข้อมูลที่อยู่
const rowsHistory = ref<any[]>([]); // ข้อมูลประวัติที่อยู่
const rowsHistoryData = ref<any[]>([]); // ข้อมูลประวัติที่อยู่สำหรับค้นหา
const modalHistory = ref<boolean>(false); // สถานะการแสดงโมดัลประวัติที่อยู่
const formData = reactive({
  registrationAddress: "", //ที่อยู่ตามทะเบียนบ้าน
  registrationProvince: "", //จังหวัด
  registrationDistrict: "", //เขต / อำเภอ
  registrationSubDistrict: "", //แขวง / ตำบล
  registrationZipCode: "", //รหัสไปรษณีย์
  currentAddress: "", //ที่อยู่ปัจจุบัน
  currentProvince: "", //จังหวัด
  currentDistrict: "", //เขต / อำเภอ
  currentSubDistrict: "", //แขวง / ตำบล
  currentZipCode: "", //รหัสไปรษณีย์
});

const provinceData = ref<Provinces[]>([]); // ข้อมูลจังหวัด
const districtRegistration = ref<Districts[]>([]); // เขต / อำเภอตามทะเบียนบ้าน
const districtCurrent = ref<Districts[]>([]); // เขต / อำเภอปัจจุบัน
const subDistrictRegistration = ref<SubDistricts[]>([]); // แขวง / ตำบลตามทะเบียนบ้าน
const subDistrictCurrent = ref<SubDistricts[]>([]); // แขวง / ตำบลปัจจุบัน

const visibleColumnsHistory = ref<string[]>([
  "currentAddress",
  "currentDistrict",
  "currentProvince",
  "currentSubDistrict",
  "currentZipCode",
  "registrationAddress",
  "registrationDistrict",
  "registrationProvince",
  "registrationSame",
  "registrationSubDistrict",
  "registrationZipCode",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);
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: (v) =>
      v.registrationAddress === v.currentAddress &&
      v.registrationZipCode === v.currentZipCode
        ? "ใช่"
        : "ไม่",
    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: "lastUpdateFullName",
    align: "left",
    label: "ผู้ดำเนินการ",
    sortable: true,
    field: "lastUpdateFullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastUpdatedAt",
    align: "left",
    label: "วันที่แก้ไข",
    sortable: true,
    field: "lastUpdatedAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => date2Thai(v, false, true),
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

/** ฟังก์ชันดึงข้อมูลที่อยู่ */
async function getData() {
  await http
    .get(config.API.dataUserAddressByType(link.value))
    .then(async (res) => {
      const data: Address = res.data.result;
      await Promise.all([
        fetchDistrict(data.registrationProvinceId, "1"),
        fetchDistrict(data.currentProvinceId, "2"),
        fetchSubDistrict(data.registrationDistrictId, "1"),
        fetchSubDistrict(data.currentDistrictId, "2"),
      ]);

      formData.registrationAddress = data.registrationAddress;
      formData.registrationProvince = data.registrationProvinceId;
      formData.registrationDistrict = data.registrationDistrictId;
      formData.registrationSubDistrict = data.registrationSubDistrictId;
      formData.registrationZipCode = data.registrationZipCode;

      formData.currentAddress = data.currentAddress;
      formData.currentProvince = data.currentProvinceId;
      formData.currentDistrict = data.currentDistrictId;
      formData.currentSubDistrict = data.currentSubDistrictId;
      formData.currentZipCode = data.currentZipCode;
    })
    .catch((e) => {
      messageError($q, e);
    });
}

/** ฟังก์ชันดึงข้อมูลประวัติที่อยู่ */
async function getHistory() {
  isLoadingHistory.value = true;
  rowsHistory.value = [];
  rowsHistoryData.value = [];
  const url =
    dataStore.officerType == "OFFICER"
      ? config.API.dataUserHistory("")
      : config.API.dataUserHistory("-employee");

  await http
    .get(url)
    .then((res) => {
      const data = res.data.result;
      rowsHistory.value = data;
      rowsHistoryData.value = data;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      isLoadingHistory.value = false;
    });
}

function onHistory() {
  modalHistory.value = true;
}

/** ฟังก์ชันดึงข้อมูลจังหวัด */
async function fetchProvince() {
  await http
    .get(config.API.profileNewProvince)
    .then((res) => {
      const data = res.data.result;
      provinceData.value = data;
    })
    .catch((e) => {
      messageError($q, e);
    });
}

/**
 * ฟังก์ชันดึงข้อมูลอำเภอ
 * @param id จังหวัด
 * @param position ที่อยู่ตามทะเบียนบ้าน,ที่อยู่ปัจจุบัน
 */
async function fetchDistrict(id: string | null, position: string) {
  if (!id) return;
  await http
    .get(config.API.profileNewDistrictByPId(id))
    .then((res) => {
      const data = res.data.result.districts;
      if (position === "1") {
        districtRegistration.value = data;
      } else {
        districtCurrent.value = data;
      }
    })
    .catch((e) => {
      messageError($q, e);
    });
}

/**
 * ฟังก์ชันดึงข้อมูลอำเภอ
 * @param id อำเภอ
 * @param position ที่อยู่ตามทะเบียนบ้าน,ที่อยู่ปัจจุบัน
 */
async function fetchSubDistrict(id: string | null, position: string) {
  if (!id) return;
  await http
    .get(config.API.profileNewSubDistrictByDId(id))
    .then((res) => {
      const data = res.data.result.subDistricts;
      if (position === "1") {
        subDistrictRegistration.value = data;
      } else {
        subDistrictCurrent.value = data;
      }
    })
    .catch((e) => {
      messageError($q, e);
    });
}

/**
 * ฟังก์ชันแปลงชื้่อจังหวัด
 * @param id รหัสจังหวัด
 */
function convertProvinceName(id: string) {
  const province = provinceData.value.find((e: Provinces) => e.id === id);
  return province?.name;
}

/**
 * ฟังก์ชันแปลงชื้่ออำเภอ
 * @param id รหัสอำเภอ
 */
function convertDistrictName(id: string, type: string) {
  const data =
    type === "1" ? districtRegistration.value : districtCurrent.value;
  const district = data.find((e: Districts) => e.id === id);
  return district?.name;
}

/**
 * ฟังก์ชัน แปลงชื้่อตำบล
 * @param id รหัสตำบล
 */
function convertSubDistrictName(id: string, type: string) {
  const data =
    type === "1" ? subDistrictRegistration.value : subDistrictCurrent.value;
  const district = data.find((e: SubDistricts) => e.id === id);
  return district?.name;
}

onMounted(async () => {
  isLoading.value = true;
  link.value = await dataStore.getProFileType();
  try {
    await fetchProvince();
    await getData();
  } finally {
    isLoading.value = false;
  }
});
</script>
<template>
  <div class="col-12">
    <q-toolbar class="q-px-none">
      <span class="text-blue-6 text-weight-bold text-body1">ข้อมูลที่อยู่</span>
      <q-space />
      <q-btn
        icon="mdi-history"
        color="info"
        flat
        dense
        round
        size="14px"
        :loading="isLoading"
        @click="onHistory"
      >
        <q-tooltip>ประวัติข้อมูลที่อยู่</q-tooltip>
      </q-btn>
    </q-toolbar>

    <div class="row q-col-gutter-sm">
      <div class="col-md-6 col-sm-12 col-xs-12">
        <q-card class="bg-grey-1" bordered>
          <q-item>
            <q-item-section>
              <q-item-label>ที่อยู่ตามทะเบียนบ้าน</q-item-label>
            </q-item-section>
          </q-item>
          <q-separator />
          <q-card-section>
            <SkeletonAddress v-if="isLoading" />
            <div v-else class="col-12 col-sm-12 col-md-6 q-gutter-y-sm">
              <div class="row">
                <div class="col-5 text-grey-6 text-weight-medium">
                  ที่อยู่ตามทะเบียนบ้าน
                </div>
                <div class="col-7">
                  {{
                    formData.registrationAddress
                      ? formData.registrationAddress
                      : "-"
                  }}
                </div>
              </div>

              <div class="row">
                <div class="col-5 text-grey-6 text-weight-medium">จังหวัด</div>
                <div class="col-7">
                  {{
                    formData.registrationProvince
                      ? convertProvinceName(formData.registrationProvince)
                      : "-"
                  }}
                </div>
              </div>

              <div class="row">
                <div class="col-5 text-grey-6 text-weight-medium">
                  เขต / อำเภอ
                </div>
                <div class="col-7">
                  {{
                    formData.registrationDistrict
                      ? convertDistrictName(formData.registrationDistrict, "1")
                      : "-"
                  }}
                </div>
              </div>

              <div class="row">
                <div class="col-5 text-grey-6 text-weight-medium">
                  แขวง / ตำบล
                </div>
                <div class="col-7">
                  {{
                    formData.registrationSubDistrict
                      ? convertSubDistrictName(
                          formData.registrationSubDistrict,
                          "1"
                        )
                      : "-"
                  }}
                </div>
              </div>

              <div class="row">
                <div class="col-5 text-grey-6 text-weight-medium">
                  รหัสไปรษณีย์
                </div>
                <div class="col-7">
                  {{
                    formData.registrationZipCode
                      ? formData.registrationZipCode
                      : "-"
                  }}
                </div>
              </div>
            </div>
          </q-card-section>
        </q-card>
      </div>
      <div class="col-md-6 col-sm-12 col-xs-12">
        <q-card class="bg-grey-1" bordered>
          <q-item>
            <q-item-section>
              <q-item-label>ที่อยู่ปัจจุบัน</q-item-label>
            </q-item-section>
          </q-item>
          <q-separator />
          <q-card-section>
            <SkeletonAddress v-if="isLoading" />
            <div v-else class="col-12 col-sm-12 col-md-6 q-gutter-y-sm">
              <div class="row">
                <div class="col-5 text-grey-6 text-weight-medium">
                  ที่อยู่ปัจจุบัน
                </div>
                <div class="col-7">
                  {{ formData.currentAddress ? formData.currentAddress : "-" }}
                </div>
              </div>
              <div class="row">
                <div class="col-5 text-grey-6 text-weight-medium">จังหวัด</div>
                <div class="col-7">
                  {{
                    formData.currentProvince
                      ? convertProvinceName(formData.currentProvince)
                      : "-"
                  }}
                </div>
              </div>
              <div class="row">
                <div class="col-5 text-grey-6 text-weight-medium">
                  เขต / อำเภอ
                </div>
                <div class="col-7">
                  {{
                    formData.currentDistrict
                      ? convertDistrictName(formData.currentDistrict, "2")
                      : "-"
                  }}
                </div>
              </div>
              <div class="row">
                <div class="col-5 text-grey-6 text-weight-medium">
                  แขวง / ตำบล
                </div>
                <div class="col-7">
                  {{
                    formData.currentSubDistrict
                      ? convertSubDistrictName(formData.currentSubDistrict, "2")
                      : "-"
                  }}
                </div>
              </div>
              <div class="row">
                <div class="col-5 text-grey-6 text-weight-medium">
                  รหัสไปรษณีย์
                </div>
                <div class="col-7">
                  {{ formData.currentZipCode ? formData.currentZipCode : "-" }}
                </div>
              </div>
            </div>
          </q-card-section>
        </q-card>
      </div>
    </div>
  </div>

  <DialogHistory
    v-model:modal="modalHistory"
    :title="'ประวัติแก้ไขข้อมูลที่อยู่'"
    :getData="getHistory"
    :rows="rowsHistory"
    :rows-data="rowsHistoryData"
    :visibleColumns="visibleColumnsHistory"
    :columns="columnsHistory"
    :is-loading="isLoadingHistory"
  />
</template>
