<script setup lang="ts">
import { ref, reactive, watch, onMounted, computed, type PropType } from "vue";
import { useQuasar } from "quasar";

import http from "@/plugins/http";
import config from "@/app.config";
import { useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import { usePagination } from "@/composables/usePagination";

/** importType*/
import type { QTableProps } from "quasar";
import type {
  FormData,
  typeOp,
  ResponsePreson,
  tableType,
} from "@/modules/11_discipline/interface/request/director";
import type { Pagination } from "@/modules/12_evaluatePersonal/interface/index/Main";

/** importComponenst*/
import PopupPersonal from "@/components/Dialogs/PopupPersonalNew.vue";

/** use*/
const $q = useQuasar();
const { showLoader, hideLoader, messageError } = useCounterMixin();
const { pagination, params, onRequest } = usePagination("", searchInput);

/**
 * รับ props มาจาก page หลัก
 */
const actionType = defineModel<string>("actionType", { default: "" });
const props = defineProps({
  data: {
    type: Object as PropType<FormData>,
    default: null,
  },
  onSubmit: {
    type: Function,
    default: () => "",
  },
});
const emit = defineEmits(["formDataReturn"]);

const route = useRoute();
const isReadonly = computed(() => (actionType.value === "VIEW" ? true : false)); //อ่านอย่างเดียว
const modalPersonal = ref<boolean>(false);
const personId = ref<string>("");
const type = ref<string>("citizenId");
const search = ref<string>("");
const typeOps = ref<typeOp[]>([
  { id: "citizenId", name: "เลขประจำตัวประชาชน" },
  { id: "fullName", name: "ชื่อ - นามสกุล" },
]);

/**
 * ข้อมูลทั้งก้อน form
 */
const formData = reactive<FormData>({
  personalId: "",
  prefix: "", //คำนำหน้า
  firstname: "", //ชื่อ
  lastname: "", //นามสกุล
  position: "", //ตำแหน่ง
  phone: "", //เบอร์โทร
  email: "", //อีเมล
});

/**
 * ตารางผู้ถูกร้องเรียน
 */
const searchRef = ref<any>(null);
const rows = ref<tableType[]>([]);
const visibleColumnsRespondent = ref<string[]>([
  "info",
  "no",
  "citizenId",
  "name",
  "position",
  "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: "citizenId",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    sortable: true,
    field: "citizenId",
    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",
  },
]);

/** บันทึกข้อมูล*/
function onSubmit() {
  props.onSubmit(formData);
}

/** 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 ? search.value.trim() : "",
      system: (route.meta?.Key as string) || undefined,
    };
    await http
      .post(config.API.orgSearchPersonal(), body, {
        params: {
          ...params.value,
        },
      })
      .then((res) => {
        const result = res.data.result;
        pagination.value.rowsNumber = result.total;
        const list = result.data.map((e: ResponsePreson) => ({
          personId: e.id,
          idcard: e.citizenId,
          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 ?? "-",
          citizenId: e.citizenId ?? "-",
        }));

        rows.value = list;
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  }
}

/**
 * เลือกชื่อกรรมการ
 * @param data เลือกชื่อกรรมการ
 */
function returnDetail(data: ResponsePreson) {
  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;
}

/**
 * ฟังก์ชันอัพเดท modal
 * @param modal เปิด,ปิด  popup ทะเบียนประวัติ
 */
function updatemodalPersonal(modal: boolean) {
  modalPersonal.value = modal;
}

/**
 * ฟังก์ชันโหลดข้อมูล
 * @param data ข้อมูลที่ส่งมา edit,view
 */
async function fetchForm(data: FormData) {
  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 inputEdit(val: boolean) {
  return {
    "full-width cursor-pointer ": val,
    "full-width cursor-pointer inputgreen": !val,
  };
}

onMounted(async () => {
  if (props.data) {
    await fetchForm(props.data);
  }
});
</script>
<template>
  <q-form greedy @submit.prevent @validation-success="onSubmit">
    <q-card bordered>
      <q-card-section>
        <div class="row col-12 q-col-gutter-md">
          <div class="col-12 q-col-gutter-y-sm" v-if="data === null">
            <div class="row q-col-gutter-sm 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-9">
                <q-input
                  ref="searchRef"
                  v-model="search"
                  outlined
                  clearable
                  hide-bottom-space
                  dense
                  label="คำค้น"
                >
                  <template v-slot:after>
                    <q-btn
                      color="primary"
                      icon="search"
                      outline
                      label="ค้นหา"
                      class="full-width q-py-sm q-px-md"
                      @click="(pagination.page = 1), searchInput()"
                    >
                    </q-btn>
                  </template>
                </q-input>
              </div>
            </div>

            <div class="col-12">
              <p-table
                ref="table"
                :columns="columnsRespondent"
                :rows="rows"
                row-key="personId"
                flat
                bordered
                :paging="true"
                dense
                class="custom-header-table"
                :visible-columns="visibleColumnsRespondent"
                :rows-per-page-options="[10, 25, 50, 100]"
                v-model:pagination="pagination"
                @request="onRequest"
              >
                <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.stop.prevent="returnDetail(props.row)"
                    >
                      <div v-if="col.name == 'no'">
                        {{ props.rowIndex + 1 }}
                      </div>
                      <div v-else-if="col.name == 'info'">
                        <q-btn
                          dense
                          flat
                          round
                          color="info"
                          icon="info"
                          @click.stop.prevent="
                            onclickViewinfo(props.row.personId)
                          "
                        >
                          <q-tooltip>ดูข้อมูลในทะเบียนประวัติ</q-tooltip>
                        </q-btn>
                      </div>

                      <div v-else>
                        {{ col.value ?? "-" }}
                      </div>
                    </q-td>
                  </q-tr>
                </template>
              </p-table>
            </div>
          </div>

          <div :class="actionType !== '' ? 'col-12' : 'col-3'">
            <q-input
              :class="inputEdit(isReadonly)"
              :readonly="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="actionType !== '' ? 'col-12' : 'col-3'">
            <q-input
              :class="inputEdit(isReadonly)"
              :readonly="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="actionType !== '' ? 'col-12' : 'col-3'">
            <q-input
              :class="inputEdit(isReadonly)"
              :readonly="isReadonly"
              dense
              outlined
              v-model="formData.lastname"
              label="นามสกุล"
              ref="lastnameRef"
              for="lastnameRef"
              hide-bottom-space
              :rules="[(val: string) => !!val || `${'กรุณากรอกนามสกุล'}`]"
              lazy-rules
            />
          </div>

          <div :class="actionType !== '' ? 'col-12' : 'col-3'">
            <q-input
              :class="inputEdit(isReadonly)"
              :readonly="isReadonly"
              dense
              outlined
              v-model="formData.position"
              label="ตำแหน่ง"
              ref="positionRef"
              for="positionRef"
              hide-bottom-space
              :rules="[(val: string) => !!val || `${'กรุณากรอกตำแหน่ง'}`]"
              lazy-rules
            />
          </div>

          <div :class="actionType !== '' ? 'col-12' : 'col-3'">
            <q-input
              :class="inputEdit(isReadonly)"
              :readonly="isReadonly"
              dense
              outlined
              v-model="formData.phone"
              label="เบอร์โทร"
              ref="phoneRef"
              for="phoneRef"
              type="tel"
              mask="##########"
              hide-bottom-space
            />
          </div>

          <div :class="actionType !== '' ? 'col-12' : 'col-3'">
            <q-input
              :class="inputEdit(isReadonly)"
              :readonly="isReadonly"
              dense
              outlined
              v-model="formData.email"
              label="อีเมล"
              ref="emailRef"
              hide-bottom-space
              for="emailRef"
            />
          </div>
        </div>
      </q-card-section>

      <q-separator v-if="!isReadonly" />

      <q-card-actions align="right" v-if="!isReadonly">
        <q-btn
          for="ButtonOnSubmit"
          id="formSubmit"
          color="secondary"
          label="บันทึก"
          type="onSubmit"
          ><q-tooltip>บับทึกข้อมูล</q-tooltip></q-btn
        >
      </q-card-actions>
    </q-card>
  </q-form>

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