<script setup lang="ts">
import { onMounted, watch, ref, reactive } from "vue";
import { useRoute } from "vue-router";
import { useQuasar } from "quasar";
import type { QTableColumn, QForm } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";

import { useCounterMixin } from "@/stores/mixin";
import { useProfileDataStore } from "@/modules/04_registryNew/stores/profile";
import DialogHeader from "@/components/DialogHeader.vue";
import type { RequestObject } from "@/modules/04_registryNew/interface/request/Profile";
import type { ResponseObject } from "@/modules/04_registryNew/interface/response/Profile";

const $q = useQuasar();
const route = useRoute();
const mixin = useCounterMixin();
const store = useProfileDataStore();
const {
  success,
  showLoader,
  hideLoader,
  date2Thai,
  messageError,
  dialogConfirm,
} = mixin;
const { calculateAge, fetchPerson, filterSelector } = store;
const profileId = ref<string>(
  route.params.id ? route.params.id.toString() : ""
);

const currentPage = ref<number>(1);
const maxPage = ref<number>(1);
const modal = ref<boolean>(false);
const informaData = ref<ResponseObject>();
const rowsHistory = ref<ResponseObject[]>([]);
const filterHistory = ref<string>("");
const modalHistory = ref<boolean>(false);

const id = ref<string>("");
const age = ref<string | null>("");
const formData = reactive<RequestObject>(store.defaultProfile);

const pagination = ref({
  page: 1,
  rowsPerPage: 10,
});

const dataLabel = {
  citizenId: "เลขบัตรประจำตัวประชาชน",
  name: "ชื่อ - สกุล",
  birthDate: "วัน/เดือน/ปีเกิด",
  age: "อายุ",
  gender: "เพศ",
  relationship: "สถานภาพ",
  nationality: "สัญชาติ",
  ethnicity: "เชื้อชาติ",
  religion: "ศาสนา",
  bloodGroup: "หมู่เลือด",
  phone: "เบอร์โทร",

  prefix: "คำนำหน้าชื่อ",
  rank: "ยศ",
  firstName: "ชื่อ",
  lastName: "นามสกุล",
};

const columnsHistory = ref<QTableColumn[]>([
  {
    name: "citizenId",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    sortable: true,
    field: "citizenId",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "prefix",
    align: "left",
    label: "คำนำหน้าชื่อ",
    sortable: true,
    field: "prefix",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "rank",
    align: "left",
    label: "ยศ",
    sortable: true,
    field: "rank",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "firstName",
    align: "left",
    label: "ชื่อ",
    sortable: true,
    field: "firstName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastName",
    align: "left",
    label: "นามสกุล",
    sortable: true,
    field: "lastName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "birthDate",
    align: "left",
    label: "วัน/เดือน/ปี เกิด",
    sortable: true,
    field: "birthDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => date2Thai(v),
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "gender",
    align: "left",
    label: "เพศ",
    sortable: true,
    field: "gender",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "relationship",
    align: "left",
    label: "สถานภาพ",
    sortable: true,
    field: "relationship",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "bloodGroup",
    align: "left",
    label: "หมู่เลือด",
    sortable: true,
    field: "bloodGroup",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "nationality",
    align: "left",
    label: "สัญชาติ",
    sortable: true,
    field: "nationality",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "ethnicity",
    align: "left",
    label: "เชื้อชาติ",
    sortable: true,
    field: "ethnicity",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "religion",
    align: "left",
    label: "ศาสนา",
    sortable: true,
    field: "religion",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "phone",
    align: "left",
    label: "เบอร์โทร",
    sortable: true,
    field: "phone",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "createdFullName",
    align: "left",
    label: "ผู้ดำเนินการ",
    sortable: true,
    field: "createdFullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "createdAt",
    align: "left",
    label: "วันที่แก้ไข",
    sortable: true,
    field: "lastUpdatedAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => date2Thai(v),
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

const visibleColumnsHistory = ref<String[]>([
  "citizenId",
  "prefix",
  "rank",
  "firstName",
  "lastName",
  "birthDate",
  "gender",
  "relationship",
  "bloodGroup",
  "nationality",
  "ethnicity",
  "religion",
  "phone",
  "createdFullName",
  "createdAt",
]);

async function getData() {
  showLoader();
  await http
    .get(config.API.profileNewProfileByProfileId(profileId.value))
    .then((res) => {
      informaData.value = res.data.result;
      if (informaData.value) {
        id.value = informaData.value.id;
        age.value = calculateAge(informaData.value.birthDate);
      }
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

const calculateMaxDate = () => {
  const today = new Date();
  today.setFullYear(today.getFullYear() - 18);
  return today;
};

async function editData() {
  showLoader();
  await http
    .put(config.API.profileNewProfileById(id.value), {
      ...formData,
    })
    .then((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
      getData(), (modal.value = false);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

function onClickOpenDialog() {
  if (!informaData.value) return;
  modal.value = true;

  id.value = informaData.value.id;
  age.value = calculateAge(informaData.value.birthDate);
  formData.citizenId = informaData.value.citizenId;
  formData.prefix = informaData.value.prefix;
  formData.rank = informaData.value.rank;
  formData.firstName = informaData.value.firstName;
  formData.lastName = informaData.value.lastName;
  formData.birthDate = informaData.value.birthDate;
  formData.gender = informaData.value.gender;
  formData.relationship = informaData.value.relationship;
  formData.nationality = informaData.value.nationality;
  formData.ethnicity = informaData.value.ethnicity;
  formData.religion = informaData.value.religion;
  formData.bloodGroup = informaData.value.bloodGroup;
  formData.phone = informaData.value.phone;
}

function onSubmit() {
  dialogConfirm(
    $q,
    async () => {
      editData();
      modal.value = false;
    },
    "ยืนยันการบันทึกข้อมูล",
    "ต้องการยืนยันการบันทึกข้อมูลนี้หรือไม่ ?"
  );
}

async function clickHistory() {
  modalHistory.value = true;
  await http
    .get(config.API.profileNewProfileHisById(id.value))
    .then((res) => {
      rowsHistory.value = res.data.result;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

watch(
  () => formData.birthDate,
  (v) => {
    if (v) {
      age.value = calculateAge(v);
    }
  }
);

onMounted(async () => {
  await getData();
  if (
    store.Ops.prefixOps.length === 0 ||
    store.Ops.genderOps.length === 0 ||
    store.Ops.bloodOps.length === 0 ||
    store.Ops.statusOps.length === 0 ||
    store.Ops.religionOps.length === 0
  ) {
    await fetchPerson();
  }
  // store.genderOp.length === 0 ? await getGender() : "";
  // store.relationshipOp.length === 0 ? await getRelationship() : "";
  // store.religionOp.length === 0 ? await getReligion() : "";
  // store.bloodGroupOp.length === 0 ? await getBloodGroup() : "";
});
</script>
<template>
  <div class="row q-gutter-sm items-center">
    <div class="toptitle col text-right q-gutter-x-sm">
      <q-btn
        flat
        round
        dense
        icon="mdi-pencil-outline"
        color="primary"
        @click="onClickOpenDialog"
      >
        <q-tooltip>แก้ไขข้อมูล</q-tooltip>
      </q-btn>
      <q-btn dense flat round icon="mdi-history" color="info" @click="clickHistory">
        <q-tooltip>ประวัติแก้ไขข้อมูลส่วนตัว</q-tooltip>
      </q-btn>
    </div>
  </div>

  <q-card bordered class="my-card bg-grey-1 q-pa-md">
    <div v-if="informaData" :class="$q.screen.gt.xs ? 'row' : 'column'">
      <!-- column 1 -->
      <div class="col-md-7 col-12 row">
        <div class="col-5 text-grey-6 text-weight-medium">
          <div
            v-for="label in Object.keys(dataLabel).slice(0, 6)"
            class="q-py-xs"
          >
            {{ dataLabel[label as keyof typeof dataLabel] }}
          </div>
        </div>
        <!-- data -->
        <div class="col-7">
          <div class="q-py-xs">
            {{ informaData.citizenId }}
          </div>
          <div class="q-py-xs">
            {{
              `${informaData.rank ? informaData.rank : informaData.prefix} ${
                informaData.firstName
              } ${informaData.lastName}`
            }}
          </div>
          <div class="q-py-xs">
            {{ date2Thai(informaData.birthDate) }}
          </div>
          <div class="q-py-xs">
            {{ age ? age : "-" }}
          </div>
          <div class="q-py-xs">
            {{ informaData.gender ? informaData.gender : "-" }}
          </div>
          <div class="q-py-xs">
            {{ informaData.relationship ? informaData.relationship : "-" }}
          </div>
        </div>
      </div>

      <!-- column 2 -->
      <div class="col-md-5 col-12 row">
        <div class="col-5 col text-grey-6 text-weight-medium">
          <div
            v-for="label in Object.keys(dataLabel).slice(6, 11)"
            class="q-py-xs"
          >
            {{ dataLabel[label as keyof typeof dataLabel] }}
          </div>
        </div>
        <!-- data -->
        <div class="col-7">
          <div class="q-py-xs">
            {{ informaData.nationality ? informaData.nationality : "-" }}
          </div>
          <div class="q-py-xs">
            {{ informaData.ethnicity ? informaData.ethnicity : "-" }}
          </div>
          <div class="q-py-xs">
            {{ informaData.religion ? informaData.religion : "-" }}
          </div>
          <div class="q-py-xs">
            {{ informaData.bloodGroup ? informaData.bloodGroup : "-" }}
          </div>
          <div class="q-py-xs">
            {{ informaData.phone ? informaData.phone : "-" }}
          </div>
        </div>
      </div>
    </div>
  </q-card>

  <!-- Edit Dialog -->
  <q-dialog v-model="modal" persistent>
    <q-card>
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader
            tittle="แก้ไขประวัติส่วนตัว"
            :close="() => (modal = false)"
          />

        <q-separator />
        <q-card-section style="max-height: 50vh" class="scroll">
          <div class="row col-12 q-col-gutter-x-xs q-col-gutter-y-xs">
              <div class="col-xs-6 col-sm-6 col-md-6">
                <q-input
                  dense
                  outlined
                  lazy-rules
                  hide-bottom-space
                  maxlength="13"
                  mask="#############"
                  v-model="formData.citizenId"
                  class="inputgreen"
                  :label="dataLabel.citizenId"
                  :rules="[
                (val: string) => !!val || `${'กรุณากรอก เลขประจำตัวประชาชน'}`,
                (val: string) =>
                  val.length >= 13 ||
                  `${'กรุณากรอกเลขประจำตัวประชาชนให้ครบ'}`,
              ]"
                />
              </div>
              <div class="col-xs-6 col-sm-6 col-md-6">
                <q-select
                  dense
                  outlined
                  use-input
                  lazy-rules
                  emit-value
                  map-options
                  hide-bottom-space
                  input-debounce="0"
                  option-label="name"
                  option-value="name"
                  v-model="formData.prefix"
                  class="inputgreen"
                  :options="store.Ops.prefixOps"
                  :label="dataLabel.prefix"
                  :rules="[(val: string) => !!val || `${'กรุณาเลือก คำนำหน้าชื่อ'}`]"
                  @filter="(inputValue: any,
              doneFn: Function) => filterSelector(inputValue, doneFn, 'prefixOps'
              )"
                />
              </div>
              <div class="col-xs-6 col-sm-6 col-md-6">
                <q-select
                  dense
                  outlined
                  clearable
                  use-input
                  lazy-rules
                  emit-value
                  map-options
                  hide-bottom-space
                  input-debounce="0"
                  option-label="name"
                  option-value="name"
                  v-model="formData.rank"
                  class="inputgreen"
                  :options="store.Ops.rankOps"
                  :label="dataLabel.rank"
                  @filter="(inputValue: any,
              doneFn: Function) => filterSelector(inputValue, doneFn, 'rankOps'
              )"
                />
              </div>
              <div class="col-xs-6 col-sm-6 col-md-6">
                <q-input
                  dense
                  outlined
                  lazy-rules
                  hide-bottom-space
                  v-model="formData.firstName"
                  class="inputgreen"
                  :label="dataLabel.firstName"
                  :rules="[(val: string) => !!val || `${'กรุณากรอก ชื่อ'}`]"
                />
              </div>
              <div class="col-xs-6 col-sm-6 col-md-6">
                <q-input
                  dense
                  outlined
                  lazy-rules
                  hide-bottom-space
                  v-model="formData.lastName"
                  class="inputgreen"
                  :label="dataLabel.lastName"
                  :rules="[(val: string) => !!val || `${'กรุณากรอก นามสกุล'}`]"
                />
              </div>
              <div class="col-xs-6 col-sm-6 col-md-6">
                <datepicker
                  autoApply
                  :max-date="calculateMaxDate()"
                  borderless
                  :enableTimePicker="false"
                  week-start="0"
                  menu-class-name="modalfix"
                  v-model="formData.birthDate"
                  :locale="'th'"
                >
                  <template #year="{ year }">
                    {{ year + 543 }}
                  </template>
                  <template #year-overlay-value="{ value }">
                    {{ parseInt(value + 543) }}
                  </template>
                  <template #trigger>
                    <q-input
                      for="inputDatereceive"
                      ref="dateReceivedRef"
                      outlined
                      dense
                      hide-bottom-space
                      class="inputgreen"
                      :model-value="
                        formData.birthDate != null
                          ? date2Thai(formData.birthDate)
                          : null
                      "
                      :label="dataLabel.birthDate"
                      :rules="[
                        (val) => !!val || `${'กรุณาเลือก วัน/เดือน/ปี เกิด'}`,
                      ]"
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          color="primary"
                        >
                        </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>
              <div class="col-xs-6 col-sm-6 col-md-6">
                <q-input
                  dense
                  outlined
                  lazy-rules
                  hide-bottom-space
                  readonly
                  v-model="age"
                  :label="dataLabel.age"
                />
              </div>
              <div class="col-xs-6 col-sm-6 col-md-6">
                <q-select
                  dense
                  outlined
                  use-input
                  clearable
                  lazy-rules
                  emit-value
                  map-options
                  hide-bottom-space
                  input-debounce="0"
                  option-label="name"
                  option-value="name"
                  v-model="formData.gender"
                  class="inputgreen"
                  :options="store.Ops.genderOps"
                  :label="dataLabel.gender"
                  @filter="(inputValue: any,
              doneFn: Function) => filterSelector(inputValue, doneFn, 'genderOps'
              )"
                />
              </div>
              <div class="col-xs-6 col-sm-6 col-md-6">
                <q-select
                  dense
                  outlined
                  use-input
                  clearable
                  lazy-rules
                  emit-value
                  map-options
                  hide-bottom-space
                  option-value="name"
                  option-label="name"
                  input-debounce="0"
                  class="inputgreen"
                  v-model="formData.relationship"
                  :options="store.Ops.statusOps"
                  :label="dataLabel.relationship"
                  @filter="(inputValue: any,
              doneFn: Function) => filterSelector(inputValue, doneFn, 'statusOps'
              )"
                />
              </div>
              <div class="col-xs-6 col-sm-6 col-md-6">
                <q-input
                  dense
                  outlined
                  lazy-rules
                  hide-bottom-space
                  class="inputgreen"
                  v-model="formData.nationality"
                  :label="dataLabel.nationality"
                />
              </div>
              <div class="col-xs-6 col-sm-6 col-md-6">
                <q-input
                  dense
                  outlined
                  lazy-rules
                  hide-bottom-space
                  class="inputgreen"
                  v-model="formData.ethnicity"
                  :label="dataLabel.ethnicity"
                />
              </div>
              <div class="col-xs-6 col-sm-6 col-md-6">
                <q-select
                  dense
                  outlined
                  use-input
                  clearable
                  lazy-rules
                  emit-value
                  map-options
                  hide-bottom-space
                  option-value="name"
                  option-label="name"
                  input-debounce="0"
                  v-model="formData.religion"
                  class="inputgreen"
                  :options="store.Ops.religionOps"
                  :label="dataLabel.religion"
                  @filter="(inputValue: any,
              doneFn: Function) => filterSelector(inputValue, doneFn, 'religionOps'
              )"
                />
              </div>
              <div class="col-xs-6 col-sm-6 col-md-6">
                <q-select
                  dense
                  outlined
                  use-input
                  clearable
                  lazy-rules
                  emit-value
                  map-options
                  hide-bottom-space
                  option-value="name"
                  option-label="name"
                  input-debounce="0"
                  v-model="formData.bloodGroup"
                  class="inputgreen"
                  :options="store.Ops.bloodOps"
                  :label="dataLabel.bloodGroup"
                  @filter="(inputValue: any,
              doneFn: Function) => filterSelector(inputValue, doneFn, 'bloodOps'
              )"
                />
              </div>
              <div class="col-xs-6 col-sm-6 col-md-6">
                <q-input
                  dense
                  outlined
                  lazy-rules
                  hide-bottom-space
                  mask="##########"
                  class="inputgreen"
                  v-model="formData.phone"
                  :label="dataLabel.phone"
                />
              </div>
            </div>
        </q-card-section>

        <q-separator />

        <q-card-actions align="right">
          <q-btn
              dense
              unelevated
              label="บันทึก"
              id="onSubmit"
              type="submit"
              color="public"
              class="q-px-md"
            >
              <q-tooltip>บันทึกข้อมูล</q-tooltip>
            </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>

  <q-dialog v-model="modalHistory" persistent>
    <q-card style="min-width: 80%">
      <DialogHeader
            tittle="ประวัติแก้ไขข้อมูลส่วนตัว"
            :close="() => (modalHistory = false)"
          />
      <q-separator />

      <q-card-section style="max-height: 50vh" class="scroll">
         <div class="row q-gutter-sm q-mb-sm">
            <q-space />
            <q-input
              standout
              dense
              v-model="filterHistory"
              ref="filterRef"
              outlined
              placeholder="ค้นหา"
              debounce="300"
            >
              <template v-slot:append>
                <q-icon
                  v-if="filterHistory == ''"
                  name="search"
                  @click.stop.prevent="filterHistory = ''"
                  class="cursor-pointer"
                />
                <q-icon
                  v-if="filterHistory"
                  name="cancel"
                  @click.stop.prevent="filterHistory = ''"
                  class="cursor-pointer"
                />
              </template>
            </q-input>
            <q-select
              v-model="visibleColumnsHistory"
              multiple
              outlined
              dense
              options-dense
              :display-value="$q.lang.table.columns"
              emit-value
              map-options
              :options="columnsHistory"
              option-value="name"
              options-cover
              style="min-width: 150px"
            />
          </div>

          <d-table
            ref="table"
            flat
            bordered
            dense
            :columns="columnsHistory"
            :rows="rowsHistory"
            class="custom-header-table"
            v-model:pagination="pagination"
            :rows-per-page-options="[10, 25, 50, 100]"
            :visible-columns="visibleColumnsHistory"
            :filter="filterHistory"
          >
            >
            <template v-slot:header="props">
              <q-tr :props="props">
                <q-th v-for="col in props.cols" :key="col.name" :props="props">
                  <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.id">
                  <div>
                    {{ col.value ? col.value : "-" }}
                  </div>
                </q-td>
              </q-tr>
            </template>
          </d-table>
      </q-card-section>

      <q-separator />

      <q-card-actions align="right">
        
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<style lang="scss">
.modalfix {
  position: fixed !important;
}
</style>
