<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 $q = useQuasar();
const mixin = useCounterMixin();
const {
  messageError,
  showLoader,
  dialogMessageNotify,
  dialogConfirm,
  success,
  hideLoader,
} = mixin;
/**
 * รับ props มาจาก page หลัก
 */
const props = defineProps({
  data: {
    type: Object,
    default: null,
  },
  onSubmit: {
    type: Function,
    default: () => "",
  },
});
const isReadonly = ref<boolean>(false); // อ่านได้อย่างเดียว
const emit = defineEmits(["formDataReturn"]);
/**
 * ข้อมูลเลขประจำตัวประชาชน
 */
//
const idCard = ref<string>("");
const idCardRef = ref<any>(null);
const type = ref<string>("idcard");
const search = ref<string>("");
const typeOps = ref<typeOp[]>([
  { id: "idcard", name: "เลขประจำตัวประชาชน" },
  { id: "firstname", name: "ชื่อ" },
  { id: "lastname", name: "นามสกุล" },
]);

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

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

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",
  },
]);

/**
 * เช็คข้อมูลจาก props
 * เมื่อมีข้อมูล
 * เก็บข้อมูลลง formData
 */
watch(props.data, async () => {
  // console.log("data==>", props.data)
  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;
});

/**
 * เพิ่มบุคลากร
 */
function addEmployee() {
  showLoader();
  const idCardNew = idCard.value.replace(/-/g, "");
  if (idCardNew.length === 13) {
    http
      .post(config.API.profileSearchPersonal(), {
        fieldName: "idcard",
        keyword: idCardNew,
      })
      .then((res) => {
        console.log(res);
        const dataApi = res.data.result;
        if (dataApi.length > 0) {
          const dataList = dataApi[0];
          formData.personalId = dataList.personId;
          formData.prefix = dataList.prefix;
          formData.firstname = dataList.firstName;
          formData.lastname = dataList.lastName;
          formData.position = dataList.position;
          formData.phone = dataList.phone;
          formData.email = dataList.email;
        } else {
          dialogMessageNotify($q, "ไม่มีข้อมูลบุคคลากรที่ต้องการค้นหา");
          formData.personalId = "";
          formData.prefix = "";
          formData.firstname = "";
          formData.lastname = "";
          formData.position = "";
          formData.phone = "";
          formData.email = "";
        }
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(async () => {
        hideLoader();
      });
  } else {
    dialogMessageNotify($q, "กรุณากรอกเลขประจำตัวประชาชนให้ครบ 13 หลัก");
    hideLoader();
  }
}

/**
 * ตรวจสอบข้อมูลก่อนส่งไปยัง api
 */
const rows = ref<tableType[]>([]);
const searchRef = ref<any>(null);
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,
  phone: phoneRef,
  email: emailRef,
};

/** ฟังชั่นตรวจสอบความถูกต้องก่อน บันทึก */
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.searchPersonal(), 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 updatemodalPersonal(modal: boolean) {
  modalPersonal.value = modal;
}
</script>
<template>
  <form @submit.prevent.stop="onValidate">
    <q-card bordered>
      <div class="col-12 row q-pa-md">
        <div class="row q-col-gutter-md">
          <div class="col-12 q-gutter-y-sm" v-if="data === null">
            <div class="row q-col-gutter-md items-start">
              <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-6">
                <q-input
                  ref="searchRef"
                  v-model="search"
                  outlined
                  clearable
                  hide-bottom-space
                  dense
                  label="คำค้น"
                  :rules="[(val) => !!val || `กรุณากรอกคำค้น`]"
                />
              </div>

              <div class="col-12 col-sm-6 col-md-3">
                <q-btn
                  color="primary"
                  icon="search"
                  label="ค้นหา"
                  class="full-width q-pa-sm"
                  @click="searchInput()"
                >
                </q-btn>
              </div>
            </div>

            <div class="col-12">
              <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-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 !== '' || `${'กรุณากรอกคำนำหน้า'}`]"
              lazy-rules
            />
          </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 !== '' || `${'กรุณากรอกชื่อ'}`]"
              lazy-rules
            />
          </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 || `${'กรุณากรอกนามสกุล'}`]"
              lazy-rules
            />
          </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 || `${'กรุณากรอกตำแหน่ง'}`]"
              lazy-rules
            />
          </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>
      </div>
      <q-separator />
      <div class="row col-12 q-pa-sm">
        <q-space />
        <q-btn
          for="ButtonOnSubmit"
          id="formSubmit"
          color="secondary"
          label="บันทึก"
          @click.stop="onValidate"
          ><q-tooltip>บับทึกข้อมูล</q-tooltip></q-btn
        >
      </div>
    </q-card>
  </form>

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