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

import http from "@/plugins/http";
import config from "@/app.config";
import { useDataStore } from "@/stores/data";

import DialogDevelop from "@/modules/10_registry/Dialog/DialogDevelopmant.vue";

const typeIDP = ref<string>("");
const link = ref<string>("");
const dataPerson = useDataStore();
const idByRow = ref<string>("");
const rows = ref<any[]>([]);
const rowsData = ref<any[]>([]);
const filter = ref<string>("");
const rowsHistory = ref<any[]>([]);
const rowsHistoryData = ref<any[]>([]);
const $q = useQuasar();
const mode = ref<boolean>($q.screen.gt.xs);
const mixin = useCounterMixin();
const { showLoader, hideLoader, messageError, date2Thai, onSearchDataTable } =
  mixin;
const modalDevelop = ref<boolean>(false);
const kpiDevelopmentId = ref<string>("");

const modalHistory = ref<boolean>(false);
/** ตัวแปรข้อมูล */

const visibleColumns = ref<string[]>([
  "no",
  "name",
  "developmentProjects",
  "developmentTarget",
  "developmentResults",
  "developmentReport",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);

const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => date2Thai(v),
  },
  {
    name: "name",
    align: "left",
    label: "ความรู้ / ทักษะ / สมรรถนะที่ต้องได้รับการพัฒนา",
    sortable: false,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "developmentProjects",
    align: "left",
    label: "วิธีการพัฒนา",
    sortable: false,
    field: "developmentProjects",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "developmentTarget",
    align: "left",
    label: "เป้าหมายการพัฒนา",
    sortable: false,
    field: "developmentTarget",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "developmentResults",
    align: "left",
    label: "วิธีการวัดผลการพัฒนา",
    sortable: false,
    field: "developmentResults",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "developmentReport",
    align: "left",
    label: "รายงานผลการพัฒนา",
    sortable: false,
    field: "developmentReport",
    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: false,
    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: false,
    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" }),
  },
]);

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

function onHistory(id: string) {
  modalHistory.value = true;
  idByRow.value = id;
}

/** get data */
function getData() {
  showLoader();
  http
    .get(config.API.developmentUserByType(link.value))
    .then((res) => {
      const data = res.data.result;
      rows.value = data;
      rowsData.value = data;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/** get history */
function getHistory() {
  showLoader();
  http
    .get(
      config.API.dataUserCertificateHistoryByType(
        link.value,
        "assessments",
        idByRow.value
      )
    )
    .then((res) => {
      const data = res.data.result;
      rowsHistory.value = data;
      rowsHistoryData.value = data;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * เปิด Dialog การพัฒนารายบุคคล
 * @param data ข้อมูลตาม row
 */
function openDialogDevelop(data: any) {
  modalDevelop.value = true;
  kpiDevelopmentId.value = data.kpiDevelopmentId;
  typeIDP.value = data.type;
}

function onSearch() {
  rows.value = onSearchDataTable(
    filter.value,
    rowsData.value,
    columns.value ? columns.value : []
  );
}

onMounted(async () => {
  link.value = await dataPerson.getProFileType();
  getData();
});
</script>
<template>
  <!-- v-if="mode" -->
  <div class="col-12" v-if="dataPerson.officerType == 'OFFICER'">
    <q-toolbar class="q-px-none q-mt-md">
      <span class="text-blue-6 text-weight-bold text-body1"
        >การพัฒนารายบุคคล (Individual Development Plan)</span
      >
      <q-space />
      <q-input
        v-if="mode"
        class="inputgreen"
        outlined
        dense
        v-model="filter"
        label="ค้นหา"
        style="max-width: 200px"
        @keydown.enter.prevent="onSearch"
      >
        <template v-slot:append>
          <q-icon name="search" />
        </template>
      </q-input>
      <q-select
        v-if="mode"
        class="q-ml-sm"
        dense
        multiple
        outlined
        emit-value
        map-options
        options-dense
        option-value="name"
        style="min-width: 140px"
        v-model="visibleColumns"
        :options="columns"
        :display-value="$q.lang.table.columns"
      />
    </q-toolbar>
    <d-table
      flat
      dense
      bordered
      virtual-scroll
      :rows="rows.length !== 0 ? rows : []"
      :columns="columns"
      :grid="!mode"
      :rows-per-page-options="[10, 25, 50, 100]"
      :visible-columns="visibleColumns"
      :virtual-scroll-sticky-size-start="48"
    >
      <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-if="mode" v-slot:body="props">
        <q-tr :props="props" class="vertical-top">
          <q-td v-for="col in props.cols" :key="col.name" :props="props">
            <div v-if="col.name == 'no'">
              {{
                (paginationPlan.page - 1) * paginationPlan.rowsPerPage +
                props.rowIndex +
                1
              }}
            </div>
            <div v-else-if="col.name == 'developmentProjects'">
              <div class="column">
                <q-checkbox
                  size="xs"
                  :model-value="props.row.isDevelopment70"
                  label="70 การลงมือปฏิบัติ (โดยผู้บังคับบัญชามอบหมาย)"
                />
                <q-checkbox
                  size="xs"
                  :model-value="props.row.isDevelopment20"
                  label="20 การเรียนรู้จากผู้อื่น (Coach/Mentor/Consulting)"
                />
                <q-checkbox
                  size="xs"
                  :model-value="props.row.isDevelopment10"
                  label="10 การฝึกอบรมอื่นๆ"
                />
              </div>
            </div>
            <div v-else class="table_ellipsis">
              {{ col.value ? col.value : "-" }}
            </div>
          </q-td>
          <q-td auto-width>
            <q-btn
              flat
              round
              dense
              color="info"
              icon="mdi-eye"
              @click="openDialogDevelop(props.row)"
            >
              <q-tooltip>รายละเอียด</q-tooltip>
            </q-btn></q-td
          >
        </q-tr>
      </template>
      <template v-else v-slot:item="props">
        <div class="q-mb-xs col-xs-12 col-sm-6 col-md-4 col-lg-3">
          <q-card bordered flat>
            <q-list dense class="q-mt-lg relative-position">
              <q-btn
                flat
                round
                dense
                color="info"
                icon="mdi-eye"
                size="14px"
                class="absolute_button"
                @click="openDialogDevelop(props.row)"
              >
                <q-tooltip>รายละเอียด</q-tooltip>
              </q-btn>
              <q-item v-for="col in props.cols" :key="col.name">
                <q-item-section class="fix_top">
                  <q-item-label class="text-grey-6 text-weight-medium">{{
                    col.label
                  }}</q-item-label>
                </q-item-section>

                <q-item-section
                  v-if="col.name == 'developmentProjects'"
                  class="fix_top"
                >
                  <div class="column">
                    <q-checkbox
                      class="check_box"
                      size="xs"
                      :model-value="props.row.isDevelopment70"
                      label="70 การลงมือปฏิบัติ (โดยผู้บังคับบัญชามอบหมาย)"
                    />
                    <q-checkbox
                      class="check_box"
                      size="xs"
                      :model-value="props.row.isDevelopment20"
                      label="20 การเรียนรู้จากผู้อื่น (Coach/Mentor/Consulting)"
                    />
                    <q-checkbox
                      class="check_box"
                      size="xs"
                      :model-value="props.row.isDevelopment10"
                      label="10 การฝึกอบรมอื่นๆ"
                    />
                  </div>
                </q-item-section>

                <q-item-section v-else class="fix_top">
                  <q-item-label class="text-dark text-weight-medium">{{
                    col.value ? col.value : "-"
                  }}</q-item-label>
                </q-item-section>
              </q-item>
            </q-list>
          </q-card>
        </div>
      </template>
    </d-table>
  </div>

  <DialogDevelop
    v-model:modal="modalDevelop"
    v-model:id="kpiDevelopmentId"
    :type="typeIDP"
  />
</template>
<style scoped>
.absolute_button {
  position: absolute;
  right: 5px;
  top: -20px;
}

.fix_top {
  justify-content: start !important;
}

.check_box {
  align-items: start;
  text-wrap: wrap;
}
</style>
