<template>
  <div>
    <!-- การ์ดแก้ไขหน่วยงาน-->
    <q-form ref="myForm">
      <q-card bordered flat>
        <div class="overScroll q-py-sm">
          <div class="col-11 row q-col-gutter-xs">
            <selector
              dense
              outlined
              v-model="organization.organizationOrganizationId"
              :options="organizationOri"
              label="หน่วยงาน"
              class="col-xs-12 col-sm-6 col-md-6"
              use-input
              input-debounce="0"
              @filter="
                  (inputValue:any, doneFn:Function) =>
                    filterSelector(inputValue, doneFn, '1')
                "
              option-label="name"
              option-value="id"
              map-options
              emit-value
              clearable
              :rules="[(val:any) => !!val || `${'กรุณาเลือกหน่วยงาน'}`]"
            />
            <selector
              dense
              outlined
              v-model="organization.organizationAgencyCode"
              :options="organizationAgencyCode"
              label="รหัสหน่วยงาน"
              class="col-xs-12 col-sm-2 col-md-2"
              use-input
              input-debounce="0"
              @filter="
                  (inputValue:any, doneFn:Function) =>
                    filterCodeSelector(inputValue, doneFn, '2',organization)
                "
              @update:model-value="(value:any) => updateGovernmentCode(value, organization)"
              option-label="agencyCode"
              option-value="agencyCode"
              map-options
              emit-value
              clearable
              :rules="[(val:any) => !!val || `${'กรุณาเลือกรหัสหน่วยงาน'}`]"
            />

            <selector
              dense
              outlined
              v-model="organization.organizationGovernmentCode"
              :options="organization.organizationGovernmentCodeOption"
              label="รหัสส่วนราชการ"
              class="col-xs-12 col-sm-2 col-md-2"
              use-input
              input-debounce="0"
              @filter="
                    (inputValue:any, doneFn:Function) =>
                    filterCodeSelector(inputValue, doneFn, '3',organization)
                "
              @update:model-value="(value:any) => updateAgencyCode(value, organization)"
              option-label="governmentCode"
              option-value="governmentCode"
              map-options
              emit-value
              clearable
              :rules="[(val:any) => !!val || `${'กรุณาเลือกรหัสส่วนราชการ'}`]"
            />
            <q-input
              dense
              readonly
              outlined
              :modelValue="organization.organizationShortName.toString() ?? ''"
              label="ชื่อย่อหน่วยงาน"
              class="col-xs-12 col-sm-2 col-md-2"
            />
            <q-input
              dense
              outlined
              v-model="organization.agency"
              class="col-xs-12 col-sm-2 col-md-2"
              label="เลขที่หน่วยงาน"
            />
            <q-input
              dense
              outlined
              v-model="organization.government"
              class="col-xs-12 col-sm-2 col-md-2"
              label="เลขที่ส่วนราชการ"
            />
            <q-input
              dense
              outlined
              v-model="organization.department"
              class="col-xs-12 col-sm-2 col-md-2"
              label="เลขที่ฝ่าย/ส่วน"
            />
            <q-input
              dense
              outlined
              v-model="organization.pile"
              class="col-xs-12 col-sm-2 col-md-2"
              label="เลขที่กอง"
            />
            <selector
              dense
              outlined
              v-model="organization.organizationTypeId"
              :options="organizationType"
              label="ประเภทหน่วยงาน"
              class="col-xs-12 col-sm-2 col-md-2"
              use-input
              input-debounce="0"
              @filter="
                  (inputValue:any, doneFn:Function) =>
                    filterSelector(inputValue, doneFn, '5')
                "
              option-label="name"
              option-value="id"
              map-options
              emit-value
              clearable
            /><!-- :rules="[(val:any) => !!val || `${'กรุณาเลือกประเภทหน่วยงาน'}`]" -->
            <selector
              dense
              outlined
              v-model="organization.organizationLevelId"
              :options="organizationLevel"
              label="ระดับหน่วยงาน"
              class="col-xs-12 col-sm-2 col-md-2"
              use-input
              input-debounce="0"
              @filter="
                  (inputValue:any, doneFn:Function) =>
                    filterSelector(inputValue, doneFn, '6')
                "
              option-label="name"
              option-value="id"
              map-options
              emit-value
              clearable
              :rules="[(val:any) => !!val || `${'กรุณาเลือกระดับหน่วยงาน'}`]"
            />
            <selector
              dense
              disable
              outlined
              v-model="organization.organizationAgencyId"
              :options="organizationAgency"
              label="หน่วยงานต้นสังกัด"
              class="col-xs-12 col-sm-4 col-md-4"
              use-input
              input-debounce="0"
              @filter="
                  (inputValue:any, doneFn:Function) =>
                    filterSelector(inputValue, doneFn, '1')
                "
              option-label="name"
              option-value="id"
              map-options
              emit-value
              clearable
            />
            <!-- :rules="[(val:any) => !!val || `${'กรุณาเลือกหน่วยงานต้นสังกัด'}`]" -->
            <selector
              dense
              disable
              outlined
              v-model="organization.organizationGovernmentAgencyId"
              :options="organizationGovernmentAgency"
              label="ส่วนราชการต้นสังกัด"
              class="col-xs-12 col-sm-6 col-md-6"
              use-input
              input-debounce="0"
              @filter="
                  (inputValue:any, doneFn:Function) =>
                    filterSelector(inputValue, doneFn, '1')
                "
              option-label="name"
              option-value="id"
              map-options
              emit-value
              clearable
            />
            <!-- :rules="[(val:any) => !!val || `${'กรุณาเลือกส่วนราชการต้นสังกัด'}`]" -->
            <q-input
              dense
              outlined
              :modelValue="Number(organization.organizationOrder) ?? 0"
              class="col-xs-12 col-sm-2 col-md-2"
              type="number"
              label="ลำดับ"
              @update:model-value="(value) => updateNumber(organization, value)"
            />
            <selector
              dense
              outlined
              v-model="organization.organizationExternalPhoneId"
              :options="organizationTelExternal"
              label="หมายเลขโทรศัพท์ติดต่อจากภายนอก"
              class="col-xs-12 col-sm-4 col-md-4"
              use-input
              input-debounce="0"
              @filter="
                  (inputValue:any, doneFn:Function) =>
                    filterSelector(inputValue, doneFn, '7')
                "
              option-label="name"
              option-value="id"
              map-options
              emit-value
              clearable
            />
            <selector
              dense
              outlined
              v-model="organization.organizationInternalPhoneId"
              :options="organizationTelInternal"
              label="หมายเลขโทรศัพท์ติดต่อจากภายใน"
              class="col-xs-12 col-sm-4 col-md-4"
              use-input
              input-debounce="0"
              @filter="
                  (inputValue:any, doneFn:Function) =>
                    filterSelector(inputValue, doneFn, '8')
                "
              option-label="name"
              option-value="id"
              map-options
              emit-value
              clearable
            />
            <selector
              dense
              outlined
              v-model="organization.organizationFaxId"
              :options="organizationFax"
              label="หมายเลขโทรสาร"
              class="col-xs-12 col-sm-2 col-md-2"
              use-input
              input-debounce="0"
              @filter="
                  (inputValue:any, doneFn:Function) =>
                    filterSelector(inputValue, doneFn, '9')
                "
              option-label="name"
              option-value="id"
              map-options
              emit-value
              clearable
            />

            <selector
              dense
              outlined
              v-model="organization.organizationStatusId"
              :options="organizationStatus"
              label="สถานะหน่วยงาน"
              class="col-xs-12 col-sm-2 col-md-2"
              use-input
              input-debounce="0"
              @filter="
                  (inputValue:any, doneFn:Function) =>
                    filterSelector(inputValue, doneFn, '10')
                "
              option-label="name"
              option-value="id"
              map-options
              emit-value
            />
            <q-input
              :class="getClass(true)"
              hide-bottom-space
              :outlined="true"
              dense
              lazy-rules
              :readonly="false"
              :borderless="false"
              v-model="organization.organizationUserNote"
              :label="`${'หน้าที่รับผิดชอบ'}`"
              type="textarea"
            />

            <!-- v-model.number="item.organizationOrder" -->
            <!--<q-select
                  dense
                  outlined
                  v-model="item.organizationOrder"
                  :options="orderList"
                  label="ลำดับผังโคงสร้าง"
                  class="col-xs-12 col-sm-4 col-md-3"
                />-->
          </div>
        </div>
      </q-card>
    </q-form>
  </div>
</template>
<script setup lang="ts">
import { ref, defineAsyncComponent, watch, onMounted } from "vue";
import type { PropType } from "vue";
import { useQuasar, QForm } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";
import type {
  DataOption,
  OrganizaOption,
  GovermentOption,
} from "../../interface/index/Main";
import { log } from "console";

import type { EnumStringMember } from "@babel/types";
// import { organizationSet } from "../interface/index/Main";
import { useCounterMixin } from "@/stores/mixin";

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

const props = defineProps({
  organizprops: Object as PropType<OrganizaOption>,
  formprops: QForm as PropType<QForm | null>,
  org: {
    type: Object, //FE ส่งมาทั้งก้อน rowClickTree
    required: true,
  },
});

const emit = defineEmits(["update:organizprops", "update:formprops"]);

const $q = useQuasar(); // show dialog
const myForm = ref<QForm | null>(null);

// const organizations = ref<OrganizaOption[]>([]);
// emit("update:organizprops", organizations.value);
// emit("update:formprops", myForm.value);

watch(myForm, (form: QForm | null, prevForm: QForm | null) => {
  emit("update:formprops", form);
});

const organizationFax = ref<DataOption[]>([]);
const organizationTelInternal = ref<DataOption[]>([]);
const organizationTelExternal = ref<DataOption[]>([]);
const organizationFaxFilter = ref<DataOption[]>([]);
const organizationTelInternalFilter = ref<DataOption[]>([]);
const organizationTelExternalFilter = ref<DataOption[]>([]);

const organizationGovernmentAgency = ref<DataOption[]>([]);
const organizationGovernmentAgencyFilter = ref<DataOption[]>([]);
const organizationAgency = ref<DataOption[]>([]);
const organizationAgencyFilter = ref<DataOption[]>([]);
const organizationType = ref<DataOption[]>([]);
const organizationTypeFilter = ref<DataOption[]>([]);

const organizationLevel = ref<DataOption[]>([]);
const organizationLevelFilter = ref<DataOption[]>([]);
const organizationOri = ref<DataOption[]>([]);
const organizationOriFilter = ref<DataOption[]>([]);

const organizationGovernmentCode = ref<GovermentOption[]>([]);
const organizationGovernmentCodeFilter = ref<GovermentOption[]>([]);
const organizationAgencyCode = ref<GovermentOption[]>([]);
const organizationAgencyCodeFilter = ref<GovermentOption[]>([]);

const organizationStatus = ref<DataOption[]>([]);
const organizationStatusFilter = ref<DataOption[]>([]);

const organization = ref<OrganizaOption>({
  organizationOrganizationId: "", // หน่วยงาน
  organizationShortNameId: "", // รหัสส่วนราชการ
  organizationShortName: "", // ชื่อย่อหน่วยงาน
  organizationAgencyCode: "", // รหัสหน่วยงาน
  organizationGovernmentCode: "", // รหัสส่วนราชการ
  organizationAgencyId: "", // หน่วยงานต้นสังกัด
  organizationGovernmentAgencyId: "", // ส่วนราชการต้นสังกัด
  organizationTypeId: "", // ประเภทหน่วยงาน
  organizationLevelId: "", //ระดับหน่วยงาน
  organizationInternalPhoneId: "", //เบอร์ติดต่อภายใน
  organizationExternalPhoneId: "", //เบอร์ติดต่อภายนอก
  organizationFaxId: "", //เบอร์โทรสาร
  organizationOrder: 0, // ลำดับผังโครงสร้าง
  organizationUserNote: "", // User Note});
  organizationStatusId: "",
  agency: "", // หน่วยงาน
  government: "", // ส่วนราชการ
  department: "", // ฝ่าย/ส่วน
  pile: "", // กอง
  organizationGovernmentCodeOption: organizationGovernmentCode.value,
  organizationGovernmentCodeOptionFilter:
    organizationGovernmentCodeFilter.value,
  isActive: true,
});
emit("update:organizprops", organization.value);

onMounted(async () => {
  hideLoader();
  //   await fillOrgEdit(); //มาแค่ตรง selector(q-select)
  await fetchOrganizationOri();
  //   await fetchOrganizationShortName();
  await fetchOrganizationAgencyCode();
  await fetchOrganizationGovernmentCode();

  await fetchOrganizationAgency();
  await fetchOrganizationGovernmentAgency();
  await fetchOrganizationType();
  await fetchOrganizationLevel();

  await fetchOrganizationFax();
  await fetchOrganizationTelExternal();
  await fetchOrganizationTelInternal();
  await fetchOrganizationStatus();
  //   console.log("Edit:organization.value", organization.value);
  console.log("props.orgId", props.org);
  console.log("props.orgId.organizationId", props.org.organizationId);
  await fillOrgEdit(); // ต้องอยู่ตรงนี้ ไม่งั้น input shortName & shortCode ไม่มา
});

const getClass = (val: boolean) => {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
};

/**Get ข้อมูลหน่วยงานเพื่อมาใส่ dropdown Edit ในโครงสร้าง
 * API16
 * @param node node that you want to edit data
 */
const fillOrgEdit = async () => {
  showLoader();
  await http
    .get(config.API.getOrgDraft(props.org.organizationId))
    .then((res) => {
      //ใส่ข้อมูลลงใน objOrg ที่ได้จาก OrganizationDialogAddEdit.vue
      console.log("ข้อมูลเดิม", res.data.result);
      organization.value.organizationOrganizationId =
        res.data.result.organizationOrganizationId;
      organization.value.organizationShortNameId =
        res.data.result.organizationShortNameId;
      organization.value.organizationAgencyId =
        res.data.result.organizationAgencyId;
      organization.value.organizationGovernmentAgencyId =
        res.data.result.organizationGovernmentAgencyId;
      organization.value.organizationTypeId =
        res.data.result.organizationTypeId;
      organization.value.organizationLevelId =
        res.data.result.organizationLevelId;
      organization.value.organizationExternalPhoneId =
        res.data.result.organizationTelExternalId;
      organization.value.organizationInternalPhoneId =
        res.data.result.organizationTelInternalId;
      organization.value.organizationFaxId = res.data.result.organizationFaxId;
      organization.value.organizationOrder = res.data.result.organizationOrder;
      organization.value.organizationUserNote =
        res.data.result.organizationUserNote;
      organization.value.agency = res.data.result.agency;
      organization.value.government = res.data.result.government;
      organization.value.department = res.data.result.department;
      organization.value.pile = res.data.result.pile;
      organization.value.agency = res.data.result.agency;
      organization.value.government = res.data.result.government;
      organization.value.department = res.data.result.department;
      organization.value.pile = res.data.result.pile;
      organization.value.organizationAgencyCode = res.data.result.agencyCode;
      organization.value.organizationGovernmentCode =
        res.data.result.governmentCode;
      organization.value.organizationStatusId =
        res.data.result.organizationStatusId;
      //ได้จาก updateShortName
      // organization.value.organizationShortName =
      //     res.data.result.organizationShortName.toString;
      //   organization.value.organizationShortCode =
      //     res.data.result.organizationShortCode.toString;
      //   updateShortName(
      //     res.data.result.organizationShortNameId,
      //     organization.value
      //   );
      fetchGovernmentCode(
        organization.value.organizationAgencyCode,
        organization.value
      );
      if (
        organization.value.organizationGovernmentCode == null ||
        organization.value.organizationGovernmentCode == ""
      ) {
        updateAgencyCode(
          organization.value.organizationAgencyCode,
          organization.value
        );
      } else {
        updateAgencyCode(
          organization.value.organizationGovernmentCode,
          organization.value
        );
      }
      emit("update:organizprops", organization.value);
    })
    .catch((e) => {
      console.log(e);
    })
    .finally(async () => {
      hideLoader();
    });
  console.log("success");
};

/**
 *  หน่วยงาน
 */
const fetchOrganizationOri = async () => {
  showLoader();
  await http
    .get(config.API.organization)
    .then((res) => {
      const data = res.data.result;
      let option: DataOption[] = [];
      data.map((r: any) => {
        option.push({ id: r.id.toString(), name: r.name.toString() });
      });
      organizationOri.value = option;
      organizationOriFilter.value = option;
    })
    .catch((e) => {
      console.log(e);
    })
    .finally(() => {
      hideLoader();
    });
};
/**
 *  รหัสหน่วยงาน
 */
const fetchOrganizationAgencyCode = async () => {
  showLoader();
  await http
    .get(config.API.organizationCode)
    .then((res) => {
      const data = res.data.result;
      //   console.log(data);
      let option: GovermentOption[] = [];
      data.map((r: any) => {
        option.push({
          id: r.id.toString(),
          governmentCode: r.governmentCode.toString(),
          agencyCode: r.agencyCode.toString(),
          shortName: r.name.toString(),
        });
      });
      organizationAgencyCode.value = option;
      organizationAgencyCodeFilter.value = option;
    })
    .catch((e) => {
      console.log(e);
    })
    .finally(() => {
      hideLoader();
    });
};
/**
 *  รหัสส่วนราชการ
 */
const fetchOrganizationGovernmentCode = async () => {
  showLoader();
  await http
    .get(config.API.organizationShortName)
    .then((res) => {
      const data = res.data.result;
      //   console.log(data);
      let option: GovermentOption[] = [];
      data.map((r: any) => {
        option.push({
          id: r.id.toString(),
          governmentCode: r.governmentCode.toString(),
          agencyCode: r.agencyCode.toString(),
          shortName: r.name.toString(),
        });
      });
      organizationGovernmentCode.value = option;
      organizationGovernmentCodeFilter.value = option;
      organization.value.organizationGovernmentCodeOption = option;
      organization.value.organizationGovernmentCodeOptionFilter = option;
      emit("update:organizprops", organization.value);
    })
    .catch((e) => {
      console.log(e);
    })
    .finally(() => {
      hideLoader();
    });
};
// /**
//  *  ชื่อย่อหน่วยงาน
//  */
// const fetchOrganizationShortName = async () => {
//   showLoader();
//   await http
//     .get(config.API.organizationShortName)
//     .then((res) => {
//       const data = res.data.result;
//       //   console.log(data);
//       let option: GovermentOption[] = [];
//       data.map((r: any) => {
//         option.push({
//           id: r.id.toString(),
//           name: r.governmentCode.toString(),
//           agencyCode: r.agencyCode.toString(),
//           shortName: r.name.toString(),
//         });
//       });
//       organizationShortName.value = option;
//       organizationShortNameFilter.value = option;
//     })
//     .catch((e) => {
//       console.log(e);
//     })
//     .finally(() => {
//       hideLoader();
//     });
// };
/**
 *  หน่วยงานต้นสังกัด
 */
const fetchOrganizationAgency = async () => {
  showLoader();
  await http
    // .get(config.API.organizationAgency)
    .get(config.API.listOrganizationHistoryAgency("หน่วยงาน"))
    .then((res) => {
      const data = res.data.result;
      let option: DataOption[] = [];
      data.map((r: any) => {
        option.push({
          id: r.organizationId.toString(),
          name: r.organizationName.toString(),
        });
      });
      organizationAgency.value = option;
      organizationAgencyFilter.value = option;
    })
    .catch((e) => {
      console.log(e);
    })
    .finally(() => {
      hideLoader();
    });
};
/**
 *  ส่วนราชการต้นสังกัด
 */
const fetchOrganizationGovernmentAgency = async () => {
  showLoader();
  await http
    // .get(config.API.organizationGovernmentAgency)
    .get(config.API.listOrganizationHistoryAgency("ส่วนราชการ"))
    .then((res) => {
      const data = res.data.result;
      let option: DataOption[] = [];
      //   console.log(data);
      data.map((r: any) => {
        option.push({
          id: r.organizationId.toString(),
          name: r.organizationName.toString(),
        });
      });
      organizationGovernmentAgency.value = option;
      organizationGovernmentAgencyFilter.value = option;
    })
    .catch((e) => {
      console.log(e);
    })
    .finally(() => {
      hideLoader();
    });
};
/**
 *   ประเภทหน่วยงาน
 */
const fetchOrganizationType = async () => {
  showLoader();
  await http
    .get(config.API.organizationType)
    .then((res) => {
      const data = res.data.result;
      let option: DataOption[] = [];
      data.map((r: any) => {
        option.push({ id: r.id.toString(), name: r.name.toString() });
      });
      organizationType.value = option;
      organizationTypeFilter.value = option;
    })
    .catch((e) => {
      console.log(e);
    })
    .finally(() => {
      hideLoader();
    });
};

/**
 *   สถานะหน่วยงาน
 */
const fetchOrganizationStatus = async () => {
  showLoader();
  await http
    .get(config.API.organizationStatus)
    .then((res) => {
      const data = res.data.result;
      let option: DataOption[] = [];
      data.map((r: any) => {
        option.push({ id: r.id.toString(), name: r.name.toString() });
      });
      organizationStatus.value = option;
      organizationStatusFilter.value = option;
    })
    .catch((e) => {
      console.log(e);
    })
    .finally(() => {
      hideLoader();
    });
};

/**
 *  ระดับหน่วยงาน
 */
const fetchOrganizationLevel = async () => {
  showLoader();
  await http
    .get(config.API.organizationLevel)
    .then((res) => {
      const data = res.data.result;
      let option: DataOption[] = [];
      data.map((r: any) => {
        option.push({ id: r.id.toString(), name: r.name.toString() });
      });
      organizationLevel.value = option;
      organizationLevelFilter.value = option;
    })
    .catch((e) => {
      console.log(e);
    })
    .finally(() => {
      hideLoader();
    });
};
/**
 *  เบอร์ติดต่อภายใน
 */
const fetchOrganizationTelInternal = async () => {
  showLoader();
  await http
    .get(config.API.organizationTelInternal)
    .then((res) => {
      const data = res.data.result;
      let option: DataOption[] = [];
      data.map((r: any) => {
        option.push({ id: r.id.toString(), name: r.name.toString() });
      });
      organizationTelInternal.value = option;
      organizationTelInternalFilter.value = option;
    })
    .catch((e) => {
      console.log(e);
    })
    .finally(() => {
      hideLoader();
    });
};
/**
 *  เบอร์ติดต่อภายนอก
 */
const fetchOrganizationTelExternal = async () => {
  showLoader();
  await http
    .get(config.API.organizationTelExternal)
    .then((res) => {
      const data = res.data.result;
      let option: DataOption[] = [];
      data.map((r: any) => {
        option.push({ id: r.id.toString(), name: r.name.toString() });
      });
      organizationTelExternal.value = option;
      organizationTelExternalFilter.value = option;
    })
    .catch((e) => {
      console.log(e);
    })
    .finally(() => {
      hideLoader();
    });
};
/**
 *  เบอร์โทรสาร
 */
const fetchOrganizationFax = async () => {
  showLoader();
  await http
    .get(config.API.organizationFax)
    .then((res) => {
      const data = res.data.result;
      let option: DataOption[] = [];
      data.map((r: any) => {
        option.push({ id: r.id.toString(), name: r.name.toString() });
      });
      organizationFax.value = option;
      organizationFaxFilter.value = option;
    })
    .catch((e) => {
      console.log(e);
    })
    .finally(() => {
      hideLoader();
    });
};

const fetchAgencyCode = async (val: string, item: OrganizaOption) => {
  let option: GovermentOption[] = [];
  showLoader();
  await http
    .get(config.API.organizationGovernmentCode(val))
    .then((res) => {
      const data = res.data.result;
      data.map((r: any) => {
        option.push({
          id: r.id.toString(),
          governmentCode: r.governmentCode.toString(),
          agencyCode: r.agencyCode.toString(),
          shortName: r.name.toString(),
        });
      });
      // organizationAgencyCode.value = option;
      // organizationAgencyCodeFilter.value = option;
    })
    .catch((e) => {
      console.log(e);
    })
    .finally(() => {
      hideLoader();
    });
  return option;
};

const fetchGovernmentCode = async (val: string, item: OrganizaOption) => {
  let option: GovermentOption[] = [];
  showLoader();
  await http
    .get(config.API.organizationAgencyCode(val))
    .then((res) => {
      const data = res.data.result;
      data.map((r: any) => {
        option.push({
          id: r.id.toString(),
          governmentCode: r.governmentCode.toString(),
          agencyCode: r.agencyCode.toString(),
          shortName: r.name.toString(),
        });
      });
      item.organizationGovernmentCodeOption = option;
      item.organizationGovernmentCodeOptionFilter = option;
    })
    .catch((e) => {
      console.log(e);
    })
    .finally(() => {
      hideLoader();
    });
  return option;
};

/**เมื่อเลือกใหม่
 * q-select ส่งค่ามาให้เองจาก @update:model-value="updateShortName"
 * @param val ค่าตัวที่เลือก
 */
const updateAgencyCode = async (val: string, item: OrganizaOption) => {
  let option = await fetchAgencyCode(val, item);
  // organizationAgencyCode.value = option;
  // organizationAgencyCodeFilter.value = option;
  //   const find = option.filter((r) => r.governmentCode === val);
  //   if (find.length == 1) {
  item.organizationShortName = option[0].shortName.toString();
  item.organizationAgencyCode = option[0].agencyCode.toString();
  item.organizationGovernmentCode = option[0].governmentCode.toString();
  item.organizationShortNameId = option[0].id;
  //   } else {
  //     item.organizationShortName = "";
  //     item.organizationAgencyCode = "";
  //     //   item.organizationGovernmentCode = "";
  //   }
  await fetchGovernmentCode(item.organizationAgencyCode, item);
};

/**เมื่อเลือกใหม่
 * q-select ส่งค่ามาให้เองจาก @update:model-value="updateShortName"
 * @param val ค่าตัวที่เลือก
 */
const updateGovernmentCode = async (val: string, item: OrganizaOption) => {
  let option = await fetchGovernmentCode(val, item);
  const find = option.filter((r) => r.agencyCode === val);
  if (find.length == 1) {
    item.organizationShortName = find[0].shortName.toString();
    item.organizationAgencyCode = find[0].agencyCode.toString();
    item.organizationGovernmentCode = find[0].governmentCode.toString();
    item.organizationShortNameId = find[0].id.toString();
  } else {
    item.organizationShortName = "";
    // item.organizationAgencyCode = "";
    item.organizationGovernmentCode = "";
  }
};

const updateNumber = (item: OrganizaOption, newValue: any) => {
  item.organizationOrder = newValue;
};

/**Fuction Filter DropDown
 * q-select ส่งค่ามาให้เองจาก @filter="filterSelector"
 * @param val ค่าตัวพิมพ์ค้นหา
 * @param update ทุกครั้งที่พิมพ์ค่า
 */
const filterSelector = (val: any, update: Function, filtername: string) => {
  switch (filtername) {
    case "1":
      update(() => {
        organizationOri.value = organizationOriFilter.value.filter(
          (v: DataOption) =>
            v.name.toLowerCase().indexOf(val.toLowerCase()) > -1
        );
      });
      break;

    // case "2":
    //   update(() => {
    //     organizationShortName.value = organizationShortNameFilter.value.filter(
    //       (v: DataOption) =>
    //         v.name.toLowerCase().indexOf(val.toLowerCase()) > -1
    //     );
    //   });
    //   break;
    // case "3":
    //   update(() => {
    //     organizationAgency.value = organizationAgencyFilter.value.filter(
    //       (v: DataOption) =>
    //         v.name.toLowerCase().indexOf(val.toLowerCase()) > -1
    //     );
    //   });
    //   break;
    case "4":
      update(() => {
        organizationGovernmentAgency.value =
          organizationGovernmentAgencyFilter.value.filter(
            (v: DataOption) =>
              v.name.toLowerCase().indexOf(val.toLowerCase()) > -1
          );
      });
      break;
    case "5":
      update(() => {
        organizationType.value = organizationTypeFilter.value.filter(
          (v: DataOption) =>
            v.name.toLowerCase().indexOf(val.toLowerCase()) > -1
        );
      });
      break;
    case "6":
      update(() => {
        organizationLevel.value = organizationLevelFilter.value.filter(
          (v: DataOption) =>
            v.name.toLowerCase().indexOf(val.toLowerCase()) > -1
        );
      });
      break;
    case "7":
      update(() => {
        organizationTelExternal.value =
          organizationTelExternalFilter.value.filter(
            (v: DataOption) =>
              v.name.toLowerCase().indexOf(val.toLowerCase()) > -1
          );
      });
      break;
    case "8":
      update(() => {
        organizationTelInternal.value =
          organizationTelInternalFilter.value.filter(
            (v: DataOption) =>
              v.name.toLowerCase().indexOf(val.toLowerCase()) > -1
          );
      });
      break;
    case "9":
      update(() => {
        organizationFax.value = organizationFaxFilter.value.filter(
          (v: DataOption) =>
            v.name.toLowerCase().indexOf(val.toLowerCase()) > -1
        );
      });
      break;
    case "10":
      update(() => {
        organizationStatus.value = organizationStatusFilter.value.filter(
          (v: DataOption) =>
            v.name.toLowerCase().indexOf(val.toLowerCase()) > -1
        );
      });
      break;

    default:
      break;
  }
};
const filterCodeSelector = (
  val: any,
  update: Function,
  filtername: string,
  item: OrganizaOption
) => {
  switch (filtername) {
    case "2":
      update(() => {
        organizationAgencyCode.value =
          organizationAgencyCodeFilter.value.filter(
            (v: GovermentOption) => v.agencyCode.indexOf(val) > -1
          );
      });
      break;
    case "3":
      update(() => {
        item.organizationGovernmentCodeOption =
          item.organizationGovernmentCodeOptionFilter.filter(
            (v: GovermentOption) => v.governmentCode.indexOf(val) > -1
          );
      });
      break;
  }
};
</script>
