import { ref } from "vue";
import { defineStore } from "pinia";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";

import type { RequestObject } from "@/modules/04_registryPerson/interface/request/Address";
import type { ResponseObject } from "@/modules/04_registryPerson/interface/response/Address";
import type {
  DataOption,
  AddressOps,
  zipCodeOption,
} from "@/modules/04_registryPerson/interface/index/Main";

const $q = useQuasar();
const mixin = useCounterMixin();
const {
  showLoader,
  hideLoader,

  messageError,
} = mixin;

export const useAddressDataStore = defineStore("addess", () => {
  const profileIdBefore = ref<string>("");

  const Ops = ref<AddressOps>({
    provinceOps: [],
    districtOps: [],
    districtCOps: [],
    subdistrictOps: [],
    subdistrictCOps: [],
  });
  const OpsFilter = ref<AddressOps>({
    provinceOps: [],
    districtOps: [],
    districtCOps: [],
    subdistrictOps: [],
    subdistrictCOps: [],
  });

  const defaultAddress: ResponseObject = {
    id: "",
    currentZipCode: "",
    currentSubDistrictId: "",
    currentDistrictId: "",
    currentProvinceId: "",
    currentAddress: "",
    registrationZipCode: "",
    registrationSubDistrictId: "",
    registrationDistrictId: "",
    registrationProvinceId: "",
    registrationAddress: "",
  };

  const defaultAddressForm: RequestObject = {
    currentZipCode: "",
    currentSubDistrictId: "",
    currentDistrictId: "",
    currentProvinceId: "",
    currentAddress: "",
    registrationZipCode: "",
    registrationSubDistrictId: "",
    registrationDistrictId: "",
    registrationProvinceId: "",
    registrationAddress: "",
  };

  function findData(ops: any, id: string | null) {
    if (id === null) return "";
    return ops.find((r: { id: string }) => r.id === id) || {};
  }

  /**
   * ฟังก์ชันดึงข้อมูลจังหวัด
   */
  async function fetchProvince() {
    showLoader();
    await http
      .get(config.API.profileNewProvince)
      .then(async (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();
      });
  }

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

  /**
   * ฟังก์ชันดึงข้อมูล  แขวง/ตำบล
   * @param id  เขต / อำเภอ
   * @param position   ที่อยู่ตามทะเบียนบ้าน, ที่อยู่ปัจจุบัน
   */
  async function fetchSubDistrict(id: string | null, position: string) {
    if (!id) return;
    showLoader();
    await http
      .get(config.API.profileNewSubDistrictByDId(id))
      .then(async (res) => {
        const data = res.data.result;
        let option: zipCodeOption[] = [];
        data.subDistricts.map((r: any) => {
          option.push({
            id: r.id,
            name: r.name,
            zipCode: r.zipCode,
          });
        });
        if (position == "1") {
          OpsFilter.value.subdistrictOps = option;
          Ops.value.subdistrictOps = option;
        } else {
          OpsFilter.value.subdistrictCOps = option;
          Ops.value.subdistrictCOps = option;
        }
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  }

  /**
   * ฟังกชันค้นหาข้อมูลใน select
   * @param val  คำที่ต้องการค้นหา
   * @param update function
   * @param refData ประเภทตัวเลือก
   */
  function 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;
    }
  }

  return {
    profileIdBefore,
    defaultAddress,
    defaultAddressForm,
    Ops,
    OpsFilter,

    findData,
    fetchProvince,
    fetchDistrict,
    fetchSubDistrict,
    filterSelector,
  };
});
