<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import { useQuasar, type QTableProps } from "quasar";

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useIndividualDevelopmentPlan } from "@/modules/14_IDP/store"; // ดึง store IDP

import type { DataOption, RowsListMain } from "@/modules/14_IDP/interface/Main";

import DialogDevelop from "@/modules/14_IDP/component/DialogDevelop.vue";

const $q = useQuasar();
const router = useRouter();
const mixin = useCounterMixin();
const store = useIndividualDevelopmentPlan();
const { showLoader, hideLoader, messageError, success, dialogRemove } = mixin;

const idRow = ref<string>("");
const isEdit = ref<boolean>(false);
const modalAdd = ref<boolean>(false); //ตัวแปร dialog #Add
const filterKeyword = ref<string>("");
const status = ref<string>("ALL"); // สถานะคำร้อง
const statusOptions = ref<DataOption[]>(store.optionStatus);

/** pagination */
const rows = ref<RowsListMain[]>([]);
const total = ref<number>(0);
const totalList = ref<number>(1);
const pagination = ref({
  sortBy: "createdAt",
  descending: true,
  page: 1,
  rowsPerPage: 10,
});

const visibleColumns = ref<string[]>([
  "no",
  "name",
  "developmentProjects",
  "developmentTarget",
  "developmentResults",
  "developmentReport",
  "topic",
  "detail",
  "document",
  "status",
  "remark",
]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: (row) => rows.value.indexOf(row) + 1,
    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",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "developmentProjects",
    align: "left",
    label: "วิธีการพัฒนา",
    sortable: true,
    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: true,
    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: true,
    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: true,
    field: "developmentReport",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "document",
    align: "left",
    label: "หลักฐานอ้างอิง",
    sortable: true,
    field: "document",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "status",
    align: "left",
    label: "สถานะคำร้อง",
    sortable: true,
    field: "status",
    format: (v) => store.convertStatus(v),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "remark",
    align: "left",
    label: "หมายเหตุ ",
    sortable: true,
    field: "remark",
    format: (v) => (v ? v : "-"),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

/**
 * function ค้นหาข้อมูลใน select
 * @param val คำค้นหา
 * @param update Function
 */
function filterOption(val: string, update: Function) {
  update(() => {
    status.value = val ? "" : status.value;
    statusOptions.value = store.optionStatus.filter(
      (v: DataOption) => v.name.indexOf(val) > -1
    );
  });
}

/**
 * function เคลียร์ข้อมูลสถานะคำร้อง
 */
function clearStatus() {
  status.value = "ALL";
  statusOptions.value = store.optionStatus;
}

/** ฟังชั่น เปิด popup */
function openAdd() {
  modalAdd.value = true;
}

function onDelete(id: string) {
  dialogRemove($q, async () => {
    await http
      .delete(config.API.developmentRequest + `/${id}`)
      .then(async (res) => {
        success($q, "ลบข้อมูลสำเร็จ");
        await getListData();
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {});
  });
}
/** list รายการ */
async function getListData() {
  showLoader();
  await http
    .get(
      config.API.developmentRequest +
        `/user?status=${status.value}&keyword=${filterKeyword.value}&page=${pagination.value.page}&pageSize=${pagination.value.rowsPerPage}
  `
    )
    .then(async (res) => {
      const data = await res.data.result.data;
      const dataTotal = await res.data.result.total;
      totalList.value = Math.ceil(dataTotal / pagination.value.rowsPerPage);
      total.value = dataTotal;
      rows.value = data;
      hideLoader();
    })
    .catch((e) => {
      hideLoader();
    })
    .finally(() => {});
}

/**
 * function หาชื่อไฟล์
 * @param id รายการยื่นคำร้องขอแก้ไขข้อมูล
 */
function onDownloadFile(id: string) {
  showLoader();
  http
    .get(config.API.file("IDP", "ยื่นคำร้องขอเพิ่มข้อมูลการพัฒนารายบุคคล", id))
    .then((res) => {
      if (res.data.length !== 0) {
        downloadUrl(id, res.data[0].fileName);
      } else {
        hideLoader();
      }
    })
    .catch((e) => {
      messageError($q, e);
      hideLoader();
    });
}

/**
 * function  โหลดไฟล์
 * @param id  รายการยื่นคำร้องขอแก้ไขข้อมูล
 * @param fileName  ชื่อไฟล์
 */
function downloadUrl(id: string, fileName: string) {
  http
    .get(
      config.API.fileByFile(
        "IDP",
        "ยื่นคำร้องขอเพิ่มข้อมูลการพัฒนารายบุคคล",
        id,
        fileName
      )
    )
    .then((res) => {
      window.open(res.data.downloadUrl, "_blank");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/** เมื่อมีการเปลี่ยน แถว ดึงข้อมูลใหม่ */
function updatePagination(newPagination: any) {
  pagination.value.page = 1;
  pagination.value.rowsPerPage = newPagination.rowsPerPage;
}

/**
 * ฟังชั่น เปิดรายละเอียด
 * @param id id row
 */
function onDetail(id: string) {
  modalAdd.value = true;
  isEdit.value = true;
  idRow.value = id;
}

watch(
  () => pagination.value.rowsPerPage,
  async () => {
    await getListData();
  }
);

onMounted(async () => {
  await getListData();
});
</script>

<template>
  <div class="col-12 row justify-center">
    <div class="col-xs-12 col-sm-12 col-md-11">
      <div class="toptitle text-white col-12 row items-center">
        <q-btn
          icon="mdi-arrow-left"
          unelevated
          round
          dense
          flat
          color="primary"
          class="q-mr-sm"
          @click="router.push(`/`)"
        />
        รายการคำร้องขอเพิ่มข้อมูลการพัฒนารายบุคคล (Individual Development Plan)
      </div>
      <div class="col-12">
        <q-card bordered class="q-pa-md">
          <div class="items-center col-12 row q-gutter-sm q-mb-sm">
            <q-select
              dense
              outlined
              label="สถานะคำร้อง"
              v-model="status"
              emit-value
              map-options
              use-input
              option-label="name"
              option-value="id"
              :options="statusOptions"
              style="width: 250px"
              @update:model-value="getListData()"
              @filter="(inputValue:string,
              doneFn:Function) => filterOption(inputValue, doneFn
              ) "
            >
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-grey">
                    ไม่มีข้อมูล
                  </q-item-section>
                </q-item>
              </template>
              <template v-if="status !== 'ALL'" v-slot:append>
                <q-icon
                  name="cancel"
                  @click.stop.prevent="(status = 'ALL'), getListData()"
                  class="cursor-pointer"
                />
              </template>
            </q-select>
            <q-btn dense round flat icon="add" color="primary" @click="openAdd">
              <q-tooltip>เพิ่มข้อมูล</q-tooltip>
            </q-btn>

            <q-space />
            <q-input
              v-model="filterKeyword"
              outlined
              dense
              label="ค้นหา"
              @keydown.enter="getListData()"
              style="width: 200px"
            >
              <template v-slot:append>
                <q-icon v-if="filterKeyword == ''" name="search" />
                <q-icon
                  v-if="filterKeyword !== ''"
                  name="clear"
                  class="cursor-pointer"
                  @click="(filterKeyword = ''), getListData()"
                />
              </template>
            </q-input>
            <q-select
              v-model="visibleColumns"
              multiple
              outlined
              dense
              options-dense
              :display-value="$q.lang.table.columns"
              emit-value
              map-options
              :options="columns"
              option-value="name"
              options-cover
              style="width: 200px"
            />
          </div>

          <div>
            <d-table
              :columns="columns"
              :rows="rows"
              row-key="id"
              :paging="true"
              :visible-columns="visibleColumns"
              :rows-per-page-options="[1, 25, 50, 100]"
              @update:pagination="updatePagination"
            >
              <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">
                <q-tr :props="props">
                  <q-td
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                    class="vertical-top cursor-pointer"
                    @click="
                      col.name === 'document' ? '' : onDetail(props.row.id)
                    "
                  >
                    <div v-if="col.name == 'no'">
                      {{
                        (pagination.page - 1) * pagination.rowsPerPage +
                        props.rowIndex +
                        1
                      }}
                    </div>
                    <div v-else-if="col.name === 'document'">
                      <q-btn
                        icon="mdi-download"
                        round
                        dense
                        flat
                        color="primary"
                        size="12px"
                        @click.pervent="onDownloadFile(props.row.id)"
                      >
                        <q-tooltip>หลักฐานอ้างอิง</q-tooltip>
                      </q-btn>
                    </div>
                    <div v-else-if="col.name == 'developmentProjects'">
                      <div class="column no-pointer-events">
                        <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>
                    <div v-else class="table_ellipsis2">
                      {{ col.value ? col.value : "-" }}
                    </div>
                  </q-td>
                  <q-td class="vertical-top">
                    <q-btn
                      v-if="props.row.status === 'PENDING'"
                      flat
                      round
                      color="red"
                      icon="mdi-delete"
                      size="12px"
                      @click="onDelete(props.row.id)"
                    >
                      <q-tooltip>ลบข้อมูล</q-tooltip>
                    </q-btn>
                  </q-td>
                </q-tr>
              </template>
              <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="getListData()"
                ></q-pagination>
              </template>
            </d-table>
          </div>
        </q-card>
      </div>
    </div>
  </div>

  <DialogDevelop
    v-model:modal="modalAdd"
    :get-data="getListData"
    v-model:is-edit="isEdit"
    v-model:id-row="idRow"
  />
</template>
<style scoped lang="scss"></style>
