<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";
import type { QTableProps } from "quasar";
import type {
  FormData,
  FormRef,
  typeOp,
  ResponsePreson,
  tableType,
} from "@/modules/11_discipline/interface/request/director";
import http from "@/plugins/http";
import config from "@/app.config";

import PopupPersonal from "@/components/Dialogs/PopupPersonal.vue";

const modalPersonal = ref<boolean>(false);
const personId = ref<string>("");
const searchRef = ref<any>(null);
const rows = ref<tableType[]>([]);
const search = ref<string>("");
const $q = useQuasar();
const mixin = useCounterMixin();
const { messageError, showLoader, dialogMessageNotify, hideLoader } = mixin;

/** รับ props มาจาก page หลัก */
const props = defineProps({
  data: {
    type: Object,
    default: null,
  },
  onSubmit: {
    type: Function,
    default: () => "",
  },
});

const type = ref<string>("idcard");
const typeOps = ref<typeOp[]>([
  { id: "idcard", name: "เลขประจำตัวประชาชน" },
  { id: "firstname", name: "ชื่อ" },
  { id: "lastname", name: "นามสกุล" },
]);
const isReadonly = ref<boolean>(false); // อ่านได้อย่างเดียว
const emit = defineEmits(["formDataReturn"]);
/**
 * ข้อมูลเลขประจำตัวประชาชน
 */
//
const idCard = ref<string>("");
const idCardRef = ref<any>(null);

/**
 * ข้อมูลทั้งก้อน form
 */
const formData = reactive<FormData>({
  personalId: "",
  prefix: "",
  firstname: "",
  lastname: "",
  position: "",
  phone: "",
  email: "",
  qualification: "",
});

/**
 * ตรวจสอบข้อมูลก่อนส่งไปยัง api
 */
const prefixRef = ref<object | null>(null);
const firstnameRef = ref<object | null>(null);
const lastnameRef = ref<object | null>(null);
const positionRef = ref<object | null>(null);
const phoneRef = ref<object | null>(null);
const emailRef = ref<object | null>(null);
const formRef: FormRef = {
  prefix: prefixRef,
  firstname: firstnameRef,
  lastname: lastnameRef,
  position: positionRef,
};

const columnsRespondent = ref<QTableProps["columns"]>([
  {
    name: "info",
    align: "center",
    label: "",
    sortable: false,
    field: "info",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "name",
    align: "left",
    label: "ชื่อ - นามสกุล",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "position",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "organization",
    align: "left",
    label: "หน่วยงาน",
    sortable: true,
    field: "organization",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

/** หัวข้อที่เเสดงในตารางผู้ถูกร้องเรียน */
const visibleColumnsRespondent = ref<string[]>([
  "info",
  "no",
  // "idcard",
  "name",
  // "posNo",
  "position",
  // "positionLevel",
  // "salary",
  "organization",
]);

/** ฟังชั่นตรวจสอบความถูกต้องก่อน บันทึก */
function onValidate() {
  const hasError = [];
  for (const key in formRef) {
    if (Object.prototype.hasOwnProperty.call(formRef, key)) {
      const property = formRef[key];
      if (property.value && typeof property.value.validate === "function") {
        const isValid = property.value.validate();
        hasError.push(isValid);
      }
    }
  }
  if (hasError.every((result) => result === true)) {
    props.onSubmit(formData);
  }
}

function inputEdit(val: boolean) {
  return {
    "full-width cursor-pointer ": val,
    "full-width cursor-pointer inputgreen": !val,
  };
}

/** update เมื่อเปลี่ยน option */
function updateSelect() {
  search.value = "";
}

async function searchInput() {
  searchRef.value.validate();
  if (!searchRef.value.hasError) {
    showLoader();
    const body = {
      fieldName: type.value,
      keyword: search.value,
    };
    await http
      .post(config.API.orgSearchPersonal(), body)
      .then((res) => {
        const data = res.data.result;
        const list = data.map((e: ResponsePreson) => ({
          personId: e.personId,
          idcard: e.idcard,
          prefix: e.prefix,
          firstName: e.firstName,
          lastName: e.lastName,
          name: `${e.prefix}${e.firstName}  ${e.lastName}`,
          posNo: e.posNo ?? "-",
          position: e.position ?? "-",
          positionLevel: e.positionLevel ?? "-",
          salary: e.salaries ?? "-",
          organization: e.organization ?? "-",
          phone: e.phone ?? "-",
          email: e.email ?? "-",
        }));

        rows.value = list;
      })
      .catch((err) => {
      })
      .finally(() => {
        hideLoader();
      });
  }
}

function returnDetail(data: any) {
  formData.prefix = data.prefix;
  formData.firstname = data.firstName;
  formData.lastname = data.lastName;
  formData.position = data.position;
  formData.phone = data.phone;
  formData.email = data.email;
}

/**
 * function ดูประวัติแบบย่อย
 * @param id  personId
 */
function onclickViewinfo(id: string) {
  modalPersonal.value = true;
  personId.value = id;
}

/**
 * function อัปเดท modal
 * @param modal ค่า modal
 */
function updatemodalPersonal(modal: boolean) {
  modalPersonal.value = modal;
}

/**
 * เช็คข้อมูลจาก props
 * เมื่อมีข้อมูล
 * เก็บข้อมูลลง formData
 */
 watch(props.data, async () => {
  formData.prefix = props.data.prefix;
  formData.firstname = props.data.firstname;
  formData.lastname = props.data.lastname;
  formData.position = props.data.position;
  formData.phone = props.data.phone;
  formData.email = props.data.email;
  formData.qualification = props.data.qualification;
});
</script>
<template>
  <form @submit.prevent.stop="onValidate">
    <q-card bordered>
      <div class="col-12 row q-pa-md">
        <div class="row col-12 q-col-gutter-md">
          <div class="col-12" v-if="data === null">
            <div class="row q-col-gutter-sm">
              <div class="col-12 col-sm-6 col-md-3">
                <q-select
                  label="ค้นหาจาก"
                  v-model="type"
                  :options="typeOps"
                  emit-value
                  dense
                  @update:model-value="updateSelect"
                  map-options
                  outlined
                  option-label="name"
                  option-value="id"
                />
              </div>

              <div class="col-12 col-sm-6 col-md-9">
                <q-input
                  ref="searchRef"
                  v-model="search"
                  outlined
                  clearable
                  hide-bottom-space
                  dense
                  label="คำค้น"
                  :rules="[(val) => !!val || `กรุณากรอกคำค้น`]"
                >
                <template v-slot:after>
                  <q-btn
                    color="primary"
                    icon="search"
                    label="ค้นหา"
                    class="full-width q-py-sm q-px-md"
                    @click="searchInput()"
                  >
                  </q-btn>
                </template>
                </q-input>
              </div>
            </div>

            <div class="col-12 q-pt-sm">
              <d-table
                ref="table"
                :columns="columnsRespondent"
                :rows="rows"
                row-key="personId"
                flat
                bordered
                :paging="true"
                dense
                class="custom-header-table"
                :visible-columns="visibleColumnsRespondent"
              >
                <template v-slot:header="props">
                  <q-tr :props="props">
                    <q-th
                      v-for="col in props.cols"
                      :key="col.name"
                      :props="props"
                      style="color: #000000; font-weight: 500"
                    >
                      <span class="text-weight-medium">{{ col.label }}</span>
                    </q-th>
                  </q-tr>
                </template>
                <template v-slot:body="props">
                  <q-tr :props="props" class="cursor-pointer">
                    <q-td
                      v-for="col in props.cols"
                      :key="col.name"
                      :props="props"
                      @click="returnDetail(props.row)"
                    >
                      <div v-if="col.name == 'no'">
                        {{ props.rowIndex + 1 }}
                      </div>
                      <div v-else-if="col.name == 'info'">
                        <!-- <router-link
                          target="_blank"
                          :to="`/registry/${props.row.personId}`"
                          > -->
                        <q-btn
                          dense
                          flat
                          round
                          color="info"
                          icon="info"
                          @click="onclickViewinfo(props.row.personId)"
                        >
                          <q-tooltip>ดูข้อมูลในทะเบียนประวัติ</q-tooltip>
                        </q-btn>
                      </div>

                      <div v-else>
                        {{ col.value }}
                      </div>
                    </q-td>
                  </q-tr>
                </template>
              </d-table>
            </div>
          </div>
          <!-- <div class="col-12"><q-separator /></div> -->

          <div class="col-3">
            <q-input
              :class="inputEdit(isReadonly)"
              dense
              outlined
              v-model="formData.prefix"
              label="คำนำหน้า"
              ref="prefixRef"
              for="prefixRef"
              hide-bottom-space
              :rules="[(val: string) => val !== null && val !== '' || `${'กรุณากรอกคำนำหน้า'}`]"
            />
          </div>
          <div class="col-3">
            <q-input
              :class="inputEdit(isReadonly)"
              dense
              outlined
              v-model="formData.firstname"
              label="ชื่อ"
              ref="firstnameRef"
              for="firstnameRef"
              hide-bottom-space
              :rules="[(val: string) => val !== null && val !== '' || `${'กรุณากรอกชื่อ'}`]"
            />
          </div>
          <div class="col-3">
            <q-input
              :class="inputEdit(isReadonly)"
              dense
              outlined
              v-model="formData.lastname"
              label="นามสกุล"
              ref="lastnameRef"
              for="lastnameRef"
              hide-bottom-space
              :rules="[(val: string) => !!val || `${'กรุณากรอกนามสกุล'}`]"
            />
          </div>
          <div class="col-3">
            <q-input
              :class="inputEdit(isReadonly)"
              dense
              outlined
              v-model="formData.position"
              label="ตำแหน่ง"
              ref="positionRef"
              for="positionRef"
              hide-bottom-space
              :rules="[(val: string) => !!val || `${'กรุณากรอกตำแหน่ง'}`]"
            />
          </div>
          <div class="col-3">
            <q-input
              :class="inputEdit(isReadonly)"
              dense
              outlined
              v-model="formData.phone"
              label="เบอร์โทร"
              ref="phoneRef"
              for="phoneRef"
              type="tel"
              mask="##########"
              hide-bottom-space
            />
          </div>
          <div class="col-3">
            <q-input
              :class="inputEdit(isReadonly)"
              dense
              outlined
              v-model="formData.email"
              label="อีเมล"
              ref="emailRef"
              hide-bottom-space
              for="emailRef"
            />
          </div>
          <div class="col-12">
            <q-input
              :class="inputEdit(isReadonly)"
              label="คุณวุฒิ"
              type="textarea"
              dense
              outlined
              v-model="formData.qualification"
            />
          </div>
        </div>
      </div>
      <q-separator />
      <div class="row col-12 q-pa-sm">
        <q-space />
        <q-btn
          for="ButtonOnSubmit"
          id="formSubmit"
          color="secondary"
          label="บันทึก"
          type="submit"
          ><q-tooltip>บับทึกข้อมูล</q-tooltip></q-btn
        >
      </div>
    </q-card>
  </form>

  <PopupPersonal
    :modal="modalPersonal"
    :id="personId"
    @update:modal="updatemodalPersonal"
  />
</template>
