import { ref } from "vue";
import { defineStore } from "pinia";
import { useCounterMixin } from "@/stores/mixin";

import http from "@/plugins/http";
import config from "@/app.config";

import type {
  DataOption,
  AddressOps,
  InformationOps,
  zipCodeOption,
} from "@/modules/04_registryPerson/interface/index/Main";

const mixin = useCounterMixin();
const { showLoader, hideLoader } = mixin;

export const useDataLinkCenter = defineStore("DataLinkCenter", () => {
  const optionRelationshipMain = ref<DataOption[]>([]);
  const optionRelationship = ref<DataOption[]>([]);
  //รายการตัวเลือก
  const OpsPerson = ref<InformationOps>({
    prefixOps: [],
    rankOps: [],
    genderOps: [],
    bloodOps: [],
    statusOps: [],
    religionOps: [],
    employeeClassOps: [
      { id: "perm", name: "ลูกจ้างประจำ" },
      { id: "temp", name: "ลูกจ้างชั่วคราว" },
    ],
    employeeTypeOps: [
      { id: "gov", name: "งบประมาณเงินอุดหนุนรัฐบาล" },
      { id: "bkk", name: "งบประมาณกรุงเทพมหานคร" },
    ],
  });

  //ข้อมูลตัวเลือก
  const OpsPersonFilter = ref<InformationOps>({
    prefixOps: [],
    rankOps: [],
    genderOps: [],
    bloodOps: [],
    statusOps: [],
    religionOps: [],
    employeeClassOps: [
      { id: "perm", name: "ลูกจ้างประจำ" },
      { id: "temp", name: "ลูกจ้างชั่วคราว" },
    ],
    employeeTypeOps: [
      { id: "gov", name: "งบประมาณเงินอุดหนุนรัฐบาล" },
      { id: "bkk", name: "งบประมาณกรุงเทพมหานคร" },
    ],
  });

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

  /**
   * ฟังก์ชันดึงข้อมูลตัวเลือกข้อมูลหลัก
   */
  async function fetchPerson() {
    await http
      .get(config.API.profileNewMetaMain)
      .then((res) => {
        const data = res.data.result;
        let optionbloodGroups: DataOption[] = [];
        data.bloodGroups.map((r: any) => {
          optionbloodGroups.push({
            id: r.id.toString(),
            name: r.name.toString(),
          });
        });
        OpsPerson.value.bloodOps = optionbloodGroups;
        OpsPersonFilter.value.bloodOps = optionbloodGroups;

        let optiongenders: DataOption[] = [];
        data.genders.map((r: any) => {
          optiongenders.push({
            id: r.id.toString(),
            name: r.name.toString(),
          });
        });
        OpsPerson.value.genderOps = optiongenders;
        OpsPersonFilter.value.genderOps = optiongenders;

        let optionprefixs: DataOption[] = [];
        data.prefixs.map((r: any) => {
          optionprefixs.push({
            id: r.id.toString(),
            name: r.name.toString(),
          });
        });
        OpsPerson.value.prefixOps = optionprefixs;
        OpsPersonFilter.value.prefixOps = optionprefixs;

        let optionrank: DataOption[] = [];
        data.rank.map((r: any) => {
          optionrank.push({
            id: r.id.toString(),
            name: r.name.toString(),
          });
        });
        OpsPerson.value.rankOps = optionrank;
        OpsPersonFilter.value.rankOps = optionrank;

        let optionrelationships: DataOption[] = [];
        data.relationships.map((r: any) => {
          optionrelationships.push({
            id: r.id.toString(),
            name: r.name.toString(),
          });
        });
        OpsPerson.value.statusOps = optionrelationships;
        OpsPersonFilter.value.statusOps = optionrelationships;

        let optionreligions: DataOption[] = [];
        data.religions.map((r: any) => {
          optionreligions.push({
            id: r.id.toString(),
            name: r.name.toString(),
          });
        });
        OpsPerson.value.religionOps = optionreligions;
        OpsPersonFilter.value.religionOps = optionreligions;
      })
      .catch((e) => {
        console.log(e);
      })
      .finally(() => {
        hideLoader();
      });
  }

  /** -----(จังหวัด-อำเภอ-ตำบล)----- */
  /**
   * ฟังก์ชันดึงข้อมูลจังหวัด
   */
  async function fetchProvince(isLoad?: boolean) {
    isLoad && 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() });
        });
        OpsAddress.value.provinceOps = option;
        OpsAddressFilter.value.provinceOps = option;
      })
      .catch((e) => {
        console.log(e);
      })
      .finally(() => {
        isLoad && hideLoader();
      });
  }

  /**
   * ฟังก์ชันดึงข้อมูล เขต / อำเภอ
   * @param id  จังหวัด
   * @param position   ที่อยู่ตามทะเบียนบ้าน, ที่อยู่ปัจจุบัน
   */
  async function fetchDistrict(
    id: string | null,
    position: string,
    isLoad?: boolean
  ) {
    if (!id) return;
    isLoad && 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") {
          OpsAddress.value.districtOps = option;
          OpsAddressFilter.value.districtOps = option;
        } else {
          OpsAddress.value.districtCOps = option;
          OpsAddressFilter.value.districtCOps = option;
        }
        return option;
      })
      .catch((e) => {
        console.log(e);
      })
      .finally(() => {
        isLoad && hideLoader();
      });
  }

  /**
   * ฟังก์ชันดึงข้อมูล  แขวง/ตำบล
   * @param id  เขต / อำเภอ
   * @param position   ที่อยู่ตามทะเบียนบ้าน, ที่อยู่ปัจจุบัน
   */
  async function fetchSubDistrict(
    id: string | null,
    position: string,
    isLoad: boolean
  ) {
    if (!id) return;
    isLoad && 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") {
          OpsAddressFilter.value.subdistrictOps = option;
          OpsAddress.value.subdistrictOps = option;
        } else {
          OpsAddressFilter.value.subdistrictCOps = option;
          OpsAddress.value.subdistrictCOps = option;
        }
      })
      .catch((e) => {
        console.log(e);
      })
      .finally(() => {
        isLoad && hideLoader();
      });
  }

  /**
   * ฟังกชันค้นหาข้อมูลใน select
   * @param val  คำที่ต้องการค้นหา
   * @param update function
   * @param refData ประเภทตัวเลือก
   */
  function filterSelector(val: any, update: Function, refData: string) {
    switch (refData) {
      case "provinceOps":
        update(() => {
          OpsAddress.value.provinceOps =
            OpsAddressFilter.value.provinceOps.filter(
              (v: DataOption) => v.name.indexOf(val) > -1
            );
        });
        break;
      case "districtOps":
        update(() => {
          OpsAddress.value.districtOps =
            OpsAddressFilter.value.districtOps.filter(
              (v: DataOption) => v.name.indexOf(val) > -1
            );
        });
        break;
      case "districtCOps":
        update(() => {
          OpsAddress.value.districtCOps =
            OpsAddressFilter.value.districtCOps.filter(
              (v: DataOption) => v.name.indexOf(val) > -1
            );
        });
        break;
      case "subdistrictOps":
        update(() => {
          OpsAddress.value.subdistrictOps =
            OpsAddressFilter.value.subdistrictOps.filter(
              (v: DataOption) => v.name.indexOf(val) > -1
            );
        });
        break;
      case "subdistrictCOps":
        update(() => {
          OpsAddress.value.subdistrictCOps =
            OpsAddressFilter.value.subdistrictCOps.filter(
              (v: DataOption) => v.name.indexOf(val) > -1
            );
        });
        break;

      default:
        break;
    }
  }

  /**
   * function fetch ข้อมูลความสัมพันธ์
   */
  function fetchDataRelationship() {
    http
      .get(config.API.orgRelationship)
      .then((res) => {
        const list = res.data.result.map((e: any) => ({
          id: e.id,
          name: e.name,
        }));
        optionRelationshipMain.value = list;
      })
      .catch((e) => {
        console.log(e);
      });
  }
  return {
    fetchPerson,
    OpsPersonFilter,
    OpsPerson,
    OpsAddress,
    OpsAddressFilter,

    fetchProvince,
    filterSelector,
    fetchDistrict,
    fetchSubDistrict,
    optionRelationshipMain,
    optionRelationship,
    fetchDataRelationship,
  };
});
