<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";

/**
 * importTypr
 */
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";

/**
 * importStore
 */
import { useCounterMixin } from "@/stores/mixin";

/**
 * use
 */
const $q = useQuasar();
const { showLoader, hideLoader, messageError } = useCounterMixin();

/**
 * รับ 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 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",
  "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: "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 total = ref<number>(0);
const totalList = ref<number>(1);
const pagination = ref({
  sortBy: "createdAt",
  descending: true,
  page: 1,
  rowsPerPage: 10,
});

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

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

/**
 * ค้นหารายชื่อ
 */
function searchInput() {
  searchRef.value.validate();
  if (!searchRef.value.hasError) {
    showLoader();
    const body = {
      fieldName: type.value,
      keyword: search.value,
    };
    http
      .post(
        config.API.orgSearchPersonal() +
          `?page=${pagination.value.page}&pageSize=${pagination.value.rowsPerPage}`,
        body
      )
      .then((res) => {
        const data = res.data.result.data;
        totalList.value = Math.ceil(
          res.data.result.total / pagination.value.rowsPerPage
        );
        total.value = res.data.result.total;
        const list = 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 ?? "-",
        }));

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

/**
 * เลืือกชื่อกรรมการ
 */
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;
}

/**
 * เปิด,ปิด  popup ทะเบียนประวัติ
 */
function updatemodalPersonal(modal: boolean) {
  modalPersonal.value = modal;
}

function updatePagination(newPagination: Pagination) {
  pagination.value.page = 1;
  pagination.value.rowsPerPage = newPagination.rowsPerPage;
}

watch(
  () => pagination.value.rowsPerPage,
  () => {
    searchInput();
  }
);

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="คำค้น"
                  :rules="[(val:string) => !!val || `กรุณากรอกคำค้น`]"
                >
                  <template v-slot:after>
                    <q-btn
                      color="primary"
                      icon="search"
                      outline
                      label="ค้นหา"
                      class="full-width q-py-sm q-px-md"
                      @click="searchInput()"
                    >
                    </q-btn>
                  </template>
                </q-input>
              </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"
                :rows-per-page-options="[10, 25, 50, 100]"
                @update:pagination="updatePagination"
              >
                <template v-slot:pagination="scope">
                  ทั้งหมด {{ total }} รายการ
                  <q-pagination
                    v-model="pagination.page"
                    active-color="primary"
                    color="dark"
                    :max="Number(totalList)"
                    size="sm"
                    boundary-links
                    direction-links
                    :max-pages="5"
                    @update:model-value="searchInput"
                  ></q-pagination>
                </template>

                <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.pervent="returnDetail(props.row)"
                    >
                      <div v-if="col.name == 'no'">
                        {{
                          (pagination.page - 1) * pagination.rowsPerPage +
                          props.rowIndex +
                          1
                        }}
                      </div>
                      <div v-else-if="col.name == 'info'">
                        <q-btn
                          dense
                          flat
                          round
                          color="info"
                          icon="info"
                          @click.stop.pervent="
                            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="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>
