<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { useCounterMixin } from "@/stores/mixin";
import { useDataStore } from "@/stores/data";
import { useQuasar, type QTableColumn, type QTableProps } from "quasar";

import http from "@/plugins/http";
import config from "@/app.config";

import DialogHistory from "@/modules/10_registry/Dialog/DialogHistory.vue";
import type { InformationData } from "@/interface/Main";

const link = ref<string>("");
const $q = useQuasar();
const dataStore = useDataStore();
const mixin = useCounterMixin();
const {
  showLoader,
  hideLoader,
  messageError,
  date2Thai,
  dialogConfirm,
  success,
} = mixin;

const editPhone = ref<boolean>(false);
const editEmail = ref<boolean>(false);
const rowsHistory = ref<any[]>([]);
const rowsHistoryData = ref<any[]>([]);
const modalHistory = ref<boolean>(false);
const phone = ref<string>("");
const email = ref<string>("");

/** ตัวแปรข้อมูล */
const formDataInformation = reactive<InformationData>({
  rank: "", //ยศ
  citizenId: "", //เลขประจำตัวประชาชน
  prefix: "",
  firstName: "",
  lastName: "",
  birthDate: null, //วันเกิด
  gender: "", //เพศ
  relationship: "", //สถานภาพ
  nationality: "", //สัญชาติ
  ethnicity: "", //เชื้อชาติ
  religion: "", //ศาสนา
  bloodGroup: "", //หมู่เลือด
  phone: "", //เบอร์โทร
  email: "",
});

const emailVerify = ref<string | null>(null);
const visibleColumnsHistory = ref<string[]>([
  "citizenId",
  "prefix",
  "rank",
  "firstName",
  "lastName",
  "birthDate",
  "gender",
  "relationship",
  "bloodGroup",
  "nationality",
  "ethnicity",
  "religion",
  "phone",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);
const columnsHistory = ref<QTableProps["columns"]>([
  {
    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: "lastUpdateFullName",
    align: "left",
    label: "ผู้ดำเนินการ",
    sortable: true,
    field: "lastUpdateFullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastUpdatedAt",
    align: "left",
    label: "วันที่แก้ไข",
    sortable: true,
    field: "lastUpdatedAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => date2Thai(v, false, true),
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

function onHistory() {
  modalHistory.value = true;
}

const mainEmail = ref<string>("");
const mainPhone = ref<string>("");

const isCheckEmail = computed(() => {
  return mainEmail.value === formDataInformation.email ? true : false;
});

const isCheckPhone = computed(() => {
  console.log("mainPhone", mainPhone.value);
  console.log("formDataInformation", formDataInformation.phone);

  return mainPhone.value === formDataInformation.phone ? true : false;
});

/** get data */
async function getData() {
  showLoader();
  await http
    .get(config.API.dataUserInformationByType(link.value))
    .then(async (res) => {
      const data = await res.data.result;
      formDataInformation.rank = data.rank;
      formDataInformation.citizenId = data.citizenId;
      formDataInformation.prefix = data.prefix;
      formDataInformation.firstName = data.firstName;
      formDataInformation.lastName = data.lastName;
      formDataInformation.birthDate = data.birthDate;
      formDataInformation.gender = data.gender;
      formDataInformation.relationship = data.relationship;

      formDataInformation.nationality = data.nationality;
      formDataInformation.ethnicity = data.ethnicity;
      formDataInformation.religion = data.religion;
      formDataInformation.bloodGroup = data.bloodGroup;
      formDataInformation.phone = data.phone;
      formDataInformation.email = data.email ? data.email.split("@")[0] : "";

      mainEmail.value = data.email ? data.email.split("@")[0] : "";
      mainPhone.value = data.phone ? data.phone : "";

      email.value = data.email ? data.email.split("@")[0] : "";
      phone.value = data.phone;

      emailVerify.value = data.statusEmail;
      hideLoader();
    })

    .catch((e) => {
      messageError($q, e);
      hideLoader();
    })
    .finally(() => {});
}

/** get history */
function getHistory() {
  const url =
    dataStore.officerType == "OFFICER"
      ? config.API.dataUserInformatioHistory("")
      : config.API.dataUserInformatioHistory("-employee");
  showLoader();
  http
    .get(url)
    .then((res) => {
      const data = res.data.result;
      rowsHistory.value = data;
      rowsHistoryData.value = data;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

const isValidPhone = ref<boolean>(true); // validate เบอร์โทร
const isValidEmail = ref<boolean>(true); // validate อีเมล

/** บันทึกเบอร์โทร */
async function onSavePhone() {
  if (!formDataInformation.phone || formDataInformation.phone.length != 10) {
    isValidPhone.value = false;
    return;
  } else {
    isValidPhone.value = true;

    dialogConfirm(
      $q,
      async () => {
        showLoader();
        await http
          .put(config.API.upDateNumberByType(link.value), {
            phone: formDataInformation.phone,
          })
          .then(async (res) => {
            editPhone.value = false;
            success($q, "บันทึกข้อมูลสำเร็จ");
            hideLoader();
          })
          .catch((e) => {
            messageError($q, e);
          })
          .finally(() => {
            getData();
          });
      },
      "ยืนยันการแก้ไขเบอร์โทร"
    );
  }
}

/** บันทึก email */
async function onSaveEmail() {
  if (!formDataInformation.email) {
    isValidEmail.value = false;
    return;
  } else {
    isValidEmail.value = true;

    dialogConfirm(
      $q,
      async () => {
        await http
          .put(config.API.updateEmailByType(link.value), {
            email: formDataInformation.email + `@bangkok.go.th`,
          })
          .then(async (res) => {
            await getData();
            editEmail.value = false;
            success($q, "บันทึกข้อมูลสำเร็จ");
          })
          .catch((e) => {
            messageError($q, e);
          })
          .finally(() => {});
      },
      "ยืนยันการแก้ไขอีเมล"
    );
  }
}

onMounted(async () => {
  link.value = await dataStore.getProFileType();
  await getData();
});
</script>
<template>
  <div class="col-12">
    <q-toolbar class="q-px-none">
      <span class="text-blue-6 text-weight-bold text-body1"
        >ประวัติส่วนตัว</span
      >
      <q-space />
      <q-btn
        icon="mdi-history"
        color="info"
        flat
        dense
        round
        size="14px"
        @click="onHistory"
      >
        <q-tooltip>ประวัติแก้ไขข้อมูลส่วนตัว</q-tooltip>
      </q-btn>
    </q-toolbar>
    <q-card bordered class="bg-grey-1 q-pa-md">
      <div class="row">
        <div class="col-12 col-sm-12 col-md-6 q-gutter-y-sm">
          <div class="row">
            <div class="col-4 text-grey-6 text-weight-medium">
              เลขประจำตัวประชาชน
            </div>
            <div class="col-8">
              {{
                formDataInformation.citizenId
                  ? formDataInformation.citizenId
                  : "-"
              }}
            </div>
          </div>

          <div class="row">
            <div class="col-4 text-grey-6 text-weight-medium">ชื่อ - สกุล</div>
            <div class="col-8">
              {{
                formDataInformation.firstName
                  ? `${
                      formDataInformation.rank
                        ? formDataInformation.rank
                        : formDataInformation.prefix
                    }${formDataInformation.firstName} ${
                      formDataInformation.lastName
                    }`
                  : "-"
              }}
            </div>
          </div>

          <div class="row">
            <div class="col-4 text-grey-6 text-weight-medium">
              วัน/เดือน/ปีเกิด
            </div>
            <div class="col-8">
              {{
                formDataInformation.birthDate
                  ? date2Thai(formDataInformation.birthDate)
                  : "-"
              }}
            </div>
          </div>

          <div class="row">
            <div class="col-4 text-grey-6 text-weight-medium">เพศ</div>
            <div class="col-8">
              {{
                formDataInformation.gender ? formDataInformation.gender : "-"
              }}
            </div>
          </div>

          <div class="row">
            <div class="col-4 text-grey-6 text-weight-medium">สถานภาพ</div>
            <div class="col-8">
              {{
                formDataInformation.relationship
                  ? formDataInformation.relationship
                  : "-"
              }}
            </div>
          </div>
        </div>

        <div class="col-12 col-sm-12 col-md-6 q-gutter-y-sm">
          <div class="row">
            <div class="col-4 text-grey-6 text-weight-medium">สัญชาติ</div>
            <div class="col-8">
              {{
                formDataInformation.nationality
                  ? formDataInformation.nationality
                  : "-"
              }}
            </div>
          </div>
          <div class="row">
            <div class="col-4 text-grey-6 text-weight-medium">เชื้อชาติ</div>
            <div class="col-8">
              {{
                formDataInformation.ethnicity
                  ? formDataInformation.ethnicity
                  : "-"
              }}
            </div>
          </div>
          <div class="row">
            <div class="col-4 text-grey-6 text-weight-medium">ศาสนา</div>
            <div class="col-8">
              {{
                formDataInformation.religion
                  ? formDataInformation.religion
                  : "-"
              }}
            </div>
          </div>
          <div class="row">
            <div class="col-4 text-grey-6 text-weight-medium">หมู่เลือด</div>
            <div class="col-8">
              {{
                formDataInformation.bloodGroup
                  ? formDataInformation.bloodGroup
                  : "-"
              }}
            </div>
          </div>
          <div class="row">
            <div class="col-4 text-grey-6 text-weight-medium">เบอร์โทร</div>
            <div class="col-8">
              <div class="row q-col-gutter-sm">
                <div class="col-9">
                  <q-input
                    dense
                    outlined
                    v-model="formDataInformation.phone"
                    :readonly="!editPhone"
                    mask="##########"
                    :class="editPhone ? 'inputgreen' : ''"
                    hide-bottom-space
                    error-message="กรุณากรอกเบอร์โทร"
                    :error="!isValidPhone"
                    @change="() => (isValidPhone = true)"
                  />
                </div>

                <div v-if="editPhone == false" class="self-center col-3">
                  <q-btn
                    dense
                    flat
                    round
                    icon="edit"
                    color="edit"
                    @click="() => (editPhone = true)"
                  >
                    <q-tooltip>แก้ไขข้อมูล</q-tooltip>
                  </q-btn>
                </div>

                <div v-else class="self-center col-3">
                  <q-btn
                    :disable="isCheckPhone"
                    dense
                    flat
                    round
                    icon="save"
                    :color="isCheckPhone ? 'grey-6' : 'primary'"
                    @click="onSavePhone"
                  >
                    <q-tooltip>บันทึก</q-tooltip>
                  </q-btn>
                  <q-btn
                    dense
                    flat
                    round
                    icon="undo"
                    color="red"
                    @click="
                      () => {
                        editPhone = false;
                        formDataInformation.phone = phone;
                        isValidPhone = true;
                      }
                    "
                  >
                    <q-tooltip>ยกเลิก</q-tooltip>
                  </q-btn>
                </div>
              </div>
            </div>
          </div>
          <div class="row">
            <div class="col-4 text-grey-6 text-weight-medium">อีเมล</div>
            <div class="col-8">
              <div class="row q-col-gutter-sm">
                <div class="col-9">
                  <q-input
                    dense
                    outlined
                    v-model="formDataInformation.email"
                    :readonly="!editEmail"
                    type="email"
                    suffix="@bangkok.go.th"
                    :class="editEmail ? 'inputgreen' : ''"
                    hide-bottom-space
                    error-message="กรุณากรอกอีเมล"
                    :error="!isValidEmail"
                    @change="isValidEmail = true"
                  />
                </div>
                <div v-if="emailVerify == null" class="self-center col-3">
                  <div v-if="editEmail == false">
                    <q-btn
                      dense
                      flat
                      round
                      icon="edit"
                      color="edit"
                      @click="() => (editEmail = true)"
                    >
                      <q-tooltip>แก้ไขข้อมูล</q-tooltip>
                    </q-btn>
                  </div>
                  <div v-else class="self-center">
                    <q-btn
                      :disable="isCheckEmail"
                      :color="isCheckEmail ? 'grey-6' : 'primary'"
                      dense
                      flat
                      round
                      icon="save"
                      @click="onSaveEmail"
                    >
                      <q-tooltip>บันทึก</q-tooltip>
                    </q-btn>
                    <q-btn
                      dense
                      flat
                      round
                      icon="undo"
                      color="red"
                      @click="
                        () => {
                          editEmail = false;
                          formDataInformation.email = email;
                          isValidEmail = true;
                        }
                      "
                    >
                      <q-tooltip>ยกเลิก</q-tooltip>
                    </q-btn>
                  </div>
                </div>
                <div
                  v-else-if="emailVerify == 'NOT_VERIFIED'"
                  class="self-center col-3"
                >
                  <q-icon
                    name="mdi-alert-box"
                    color="warning"
                    size="sm"
                    class="selft-center"
                  >
                    <q-tooltip>รอยืนยันอีเมล</q-tooltip>
                  </q-icon>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </q-card>
  </div>

  <DialogHistory
    v-model:modal="modalHistory"
    :title="'ประวัติแก้ไขข้อมูลส่วนตัว'"
    :getData="getHistory"
    :rows="rowsHistory"
    :rows-data="rowsHistoryData"
    :visibleColumns="visibleColumnsHistory"
    :columns="columnsHistory"
  />
</template>
