<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";

import { useRoute } from "vue-router";
import http from "@/plugins/http";
import config from "@/app.config";

import { checkPermission } from "@/utils/permissions";
import { QForm, useQuasar } from "quasar";
import { useCounterMixin } from "@/stores/mixin";

import type { QTableProps } from "quasar";
import type { RequestItemsObject } from "@/modules/04_registryPerson/interface/request/SpecialSkill";
import type { ResponseObject } from "@/modules/04_registryPerson/interface/response/SpecialSkill";

import dialogHeader from "@/components/DialogHeader.vue";

const $q = useQuasar();
const route = useRoute();
const mixin = useCounterMixin();
const {
  dialogConfirm,
  showLoader,
  hideLoader,
  messageError,
  success,
  date2Thai,
  pathRegistryEmp,
} = mixin;

const id = ref<string>(route.params.id.toString()); //id profile
const empType = ref<string>(pathRegistryEmp(route.name?.toString() ?? ""));

const mode = ref<string>("table"); //การแสดงของ Table card
/**
 * props
 */
const isLeave = defineModel<boolean>("isLeave", {
  required: true,
});
//Table
const keyword = ref<string>(""); //คำต้นหา
const rows = ref<ResponseObject[]>([]); //รายการความสามารถ
const columns = ref<QTableProps["columns"]>([
  {
    name: "field",
    align: "left",
    label: "ด้าน",
    sortable: true,
    field: "field",
    headerStyle: "font-size: 14px; width: 50px;",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "detail",
    align: "left",
    label: "รายละเอียด",
    sortable: true,
    field: "detail",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "remark",
    align: "left",
    label: "หมายเหตุ",
    sortable: true,
    field: "remark",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "reference",
    align: "left",
    label: "เอกสารอ้างอิง",
    sortable: true,
    field: "reference",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const visibleColumns = ref<string[]>([
  "field",
  "detail",
  "remark",
  "reference",
]);

const dialog = ref<boolean>(false); //แสดง popup ข้อมูลความสามารถพิเศษ
const dialogStatus = ref<string>("create"); ////สถานะข้อมูลความสามารถพิเศษ
const editId = ref<string>(""); //idที่ต้องการแก้ไข

const historyDialog = ref<boolean>(false); //แสดง popup รายการประวัติ
const historyRows = ref<ResponseObject[]>([]); //รายการประวัติ
const historyKeyword = ref<string>(""); //คำต้นหาประวัติ
const historyColumns = ref<QTableProps["columns"]>([
  {
    name: "field",
    align: "left",
    label: "ด้าน",
    sortable: true,
    field: "field",
    headerStyle: "font-size: 14px; width: 50px;",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "detail",
    align: "left",
    label: "รายละเอียด",
    sortable: true,
    field: "detail",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "remark",
    align: "left",
    label: "หมายเหตุ",
    sortable: true,
    field: "remark",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "reference",
    align: "left",
    label: "เอกสารอ้างอิง",
    sortable: true,
    field: "reference",
    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",
    format: (v) => date2Thai(v, false, true),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const historyVisibleColumns = ref<string[]>([
  "field",
  "detail",
  "remark",
  "reference",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);

//ฟอร์มข้อมูลความสามารถพิเศษ
const specialSkill = reactive<RequestItemsObject>({
  field: "", //ด้าน
  detail: "", //รายละเอียด
  remark: "", //หมายเหตุ
  reference: "", //เอกสารอ้างอิง
  profileId: id.value,
  dateStart: null,
  dateEnd: null,
});

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

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

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

/**
 * function เคลียร์ formData
 */
function clearForm() {
  specialSkill.detail = "";
  specialSkill.field = "";
  specialSkill.reference = "";
  specialSkill.remark = "";
}

/**
 * function
 * @param row ข้อมูลความสามารถพิเศษ
 */
function editForm(row: any) {
  dialogStatus.value = "edit";
  editId.value = row.id;
  specialSkill.detail = row.detail;
  specialSkill.field = row.field;
  specialSkill.reference = row.reference;
  specialSkill.remark = row.remark;
  dialog.value = true;
}

/**
 * function fetch ข้อมูลความสามรรถพิเศษ
 */
async function fetchData(id: string) {
  showLoader();
  await http
    .get(config.API.profileNewAbilityByProfileId(id, empType.value))
    .then(async (res) => {
      rows.value = await res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function fetch ประวัติการแก้ไขความสามรรถพิเศษ
 * @param id  ความสามรรถพิเศษ
 */
async function fetchHistoryData(id: string) {
  showLoader();
  await http
    .get(config.API.profileNewAbilityHisByAbilityId(id, empType.value))
    .then(async (res) => {
      historyRows.value = await res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function เพิ่มข้อมูลความสามรรถพิเศษ
 */
async function addData() {
  showLoader();
  await http
    .post(config.API.profileNewAbility(empType.value), {
      ...specialSkill,
      dateStart: null,
      dateEnd: null,
      profileId: empType.value === "" ? id.value : undefined,
      profileEmployeeId: empType.value !== "" ? id.value : undefined,
    })
    .then(async () => {
      await fetchData(id.value);
      await success($q, "บันทึกข้อมูลสำเร็จ");
      closeDialog();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function บันทึกการแก้ไขข้อมูล
 * @param idData ความสามรรถพิเศษ
 */
async function editData(idData: string) {
  showLoader();
  await http
    .patch(config.API.profileNewAbilityByAbilityId(idData, empType.value), {
      ...specialSkill,
      dateStart: null,
      dateEnd: null,
      profileId: undefined,
    })
    .then(async () => {
      await fetchData(id.value);
      await success($q, "บันทึกข้อมูลสำเร็จ");
      closeDialog();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function ปิด popup  ข้อมูลความสามารถพิเศษ
 */
function closeDialog() {
  dialog.value = false;
}

/**
 * function ปิด popup  รายการประวัติ
 */
function closeHistoryDialog() {
  historyDialog.value = false;
  historyKeyword.value = "";
  historyRows.value = [];
}

/**
 * ทำงานเมื่อ Components ถูกเรียกใช้งาน
 */
onMounted(() => {
  fetchData(id.value);
});
</script>
<template>
  <div class="row items-center q-gutter-x-sm q-pb-sm">
    <q-btn
      v-if="isLeave == false && checkPermission($route)?.attrIsUpdate"
      flat
      round
      color="primary"
      dense
      icon="add"
      @click="() => ((dialogStatus = 'create'), clearForm(), (dialog = true))"
    >
      <q-tooltip>เพิ่มข้อมูล</q-tooltip>
    </q-btn>
    <q-space />
    <q-input dense outlined v-model="keyword" label="ค้นหา">
      <template v-slot:append>
        <q-icon name="search" />
      </template>
    </q-input>

    <q-select
      v-model="visibleColumns"
      multiple
      outlined
      v-if="mode === 'table'"
      dense
      options-dense
      :display-value="$q.lang.table.columns"
      emit-value
      map-options
      :options="columns"
      option-value="name"
      style="min-width: 140px"
    />
    <q-btn-toggle
      v-model="mode"
      dense
      class="no-shadow toggle-borderd"
      toggle-color="grey-4"
      :options="[
        { value: 'table', slot: 'table' },
        { value: 'card', slot: 'card' },
      ]"
    >
      <template v-slot:table>
        <q-icon
          name="format_list_bulleted"
          size="24px"
          :style="{
            color: mode === 'table' ? '#787B7C' : '#C9D3DB',
          }"
        />
      </template>

      <template v-slot:card>
        <q-icon
          name="mdi-view-grid-outline"
          size="24px"
          :style="{
            color: mode === 'card' ? '#787B7C' : '#C9D3DB',
          }"
        />
      </template>
    </q-btn-toggle>
  </div>

  <d-table
    :grid="mode === 'card'"
    ref="table"
    row-key="id"
    flat
    bordered
    dense
    :columns="columns"
    :rows="rows"
    :paging="true"
    :filter="keyword.trim()"
    v-model:pagination="pagination"
    :rows-per-page-options="[20, 50, 100]"
    :visible-columns="visibleColumns"
  >
    <template v-slot:header="props">
      <q-tr :props="props">
        <q-th auto-width />
        <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" v-if="mode === 'table'">
      <q-tr :props="props">
        <q-td auto-width>
          <q-btn
            flat
            dense
            round
            color="deep-purple"
            icon="mdi-history"
            @click="
              fetchHistoryData(props.row.id);
              historyDialog = true;
            "
          >
            <q-tooltip>ประวัติแก้ไขความสามารถพิเศษ</q-tooltip>
          </q-btn>
          <q-btn
            v-if="isLeave == false && checkPermission($route)?.attrIsUpdate"
            flat
            dense
            round
            color="edit"
            icon="edit"
            @click="
              () => {
                editForm(props.row);
              }
            "
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>
        </q-td>
        <q-td v-for="col in props.cols" :key="col.id">
          <div>{{ col.value ? col.value : "-" }}</div>
        </q-td>
      </q-tr>
    </template>
    <template v-slot:item="props" v-else>
      <div
        class="q-pa-xs col-xs-12 col-sm-6 col-md-6 col-lg-6 grid-style-transition"
      >
        <q-card bordered>
          <q-card-actions align="right" class="bg-grey-3">
            <q-btn
              dense
              flat
              round
              color="deep-purple"
              icon="mdi-history"
              @click="
                fetchHistoryData(props.row.id);
                historyDialog = true;
              "
            >
              <q-tooltip>ประวัติแก้ไขความสามารถพิเศษ</q-tooltip>
            </q-btn>
            <q-btn
              v-if="isLeave == false"
              dense
              flat
              round
              color="edit"
              icon="edit"
              size="14px"
              @click="
                () => {
                  editForm(props.row);
                }
              "
            >
              <q-tooltip>แก้ไขข้อมูล</q-tooltip>
            </q-btn>
          </q-card-actions>
          <q-separator />
          <div class="row">
            <div class="col q-pa-sm label-color">ด้าน</div>
            <div class="col q-pa-sm">{{ props.cols[0].value }}</div>
            <div class="col q-pa-sm label-color">รายละเอียด</div>
            <div class="col q-pa-sm">{{ props.cols[1].value }}</div>
          </div>
          <div :class="`row bg-color`">
            <div class="col q-pa-sm label-color">หมายเหตุ</div>
            <div class="col q-pa-sm">{{ props.cols[2].value }}</div>
            <div class="col q-pa-sm label-color">เอกสารอ้างอิง</div>
            <div class="col q-pa-sm">{{ props.cols[3].value }}</div>
          </div>
        </q-card>
      </div>
    </template>
  </d-table>

  <q-dialog v-model="dialog" class="dialog" persistent>
    <q-card>
      <q-form @submit.prevent greedy @validation-success="onSubmit()">
        <dialog-header
          :tittle="
            dialogStatus == 'edit'
              ? 'แก้ไขข้อมูลความสามารถพิเศษ'
              : 'เพิ่มข้อมูลความสามารถพิเศษ'
          "
          :close="closeDialog"
        />
        <q-separator />
        <q-card-section>
          <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
                outlined
                class="inputgreen"
                dense
                bg-color="white"
                v-model="specialSkill.field"
                label="ด้าน"
                hide-bottom-space
                :rules="[(val:string) => !!val || `${'กรุณากรอกด้านความสามารถพิเศษ'}`]"
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-input
                outlined
                dense
                class="inputgreen"
                bg-color="white"
                v-model="specialSkill.detail"
                label="รายละเอียด"
                hide-bottom-space
                :rules="[(val:string) => !!val || `${'กรุณากรอกรายละเอียด'}`]"
              />
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
              <q-input
                class="inputgreen"
                outlined
                dense
                bg-color="white"
                v-model="specialSkill.remark"
                label="หมายเหตุ"
              />
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
              <q-input
                class="inputgreen"
                outlined
                dense
                bg-color="white"
                v-model="specialSkill.reference"
                label="เอกสารอ้างอิง"
              />
            </div>
          </div>
        </q-card-section>

        <q-separator />

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

  <q-dialog v-model="historyDialog" persistent>
    <q-card style="width: 900px; max-width: 80vw">
      <dialog-header
        tittle="ประวัติแก้ไขความสามารถพิเศษ"
        :close="closeHistoryDialog"
      />
      <q-separator />
      <q-card-section>
        <q-toolbar style="padding: 0px" class="text-primary q-mb-sm">
          <q-space />
          <q-input
            dense
            outlined
            bg-color="white"
            v-model="historyKeyword"
            label="ค้นหา"
            class="q-mr-sm"
          >
            <template v-slot:append>
              <q-icon name="search" />
            </template>
          </q-input>

          <q-select
            v-model="historyVisibleColumns"
            multiple
            outlined
            dense
            bg-color="white"
            options-dense
            :display-value="$q.lang.table.columns"
            emit-value
            map-options
            :options="historyColumns"
            option-value="name"
            style="min-width: 140px"
          />
        </q-toolbar>
        <d-table
          ref="table"
          :columns="historyColumns"
          :rows="historyRows"
          row-key="name"
          flat
          bordered
          :paging="true"
          dense
          :filter="historyKeyword.trim()"
          v-model:pagination="historyPagination"
          :rows-per-page-options="[20, 50, 100]"
          class="custom-header-table"
          :visible-columns="historyVisibleColumns"
        >
          <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-th auto-width />
            </q-tr>
          </template>
          <template v-slot:body="props" v-if="mode === 'table'">
            <q-tr :props="props">
              <q-td v-for="col in props.cols" :key="col.id">
                <div>{{ col.value ? col.value : "-" }}</div>
              </q-td>
              <q-td auto-width> </q-td>
            </q-tr>
          </template>
        </d-table>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<style scoped>
.label-color {
  color: #747474cc;
}

.bg-color {
  background-color: #fafafa;
}
</style>
