<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";
import axios from "axios";
import type { QTableProps } from "quasar";
import { useQuasar } from "quasar";
import type { ResRecord } from "@/modules/15_development/interface/response/Main";
const mixin = useCounterMixin();
const route = useRoute();
const $q = useQuasar();
const id = ref<string>(route.params.id.toString());
const {
  success,
  messageError,
  showLoader,
  hideLoader,
  dialogConfirm,
  date2Thai,
} = mixin;
const columns = ref<QTableProps["columns"]>([
  {
    name: "type",
    align: "left",
    label: "ประเภท",
    sortable: true,
    field: "type",
    headerStyle: "font-size: 14px; width: 50px;",
    style: "font-size: 14px",
    format: (v) => formBmaofficer(v),
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "idcard",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    sortable: true,
    field: "idcard",
    headerStyle: "font-size: 14px; width: 50px;",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "fullName",
    align: "left",
    label: "ชื่อ - นามสกุล",
    sortable: true,
    field: "fullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "position",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "posTypeName",
    align: "left",
    label: "ประเภทตำแหน่ง",
    sortable: true,
    field: "posTypeName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "posLevelName",
    align: "left",
    label: "ระดับตำแหน่ง",
    sortable: true,
    field: "posLevelName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "posExecutive",
    align: "left",
    label: "ตำแหน่งทางการบริหาร",
    sortable: true,
    field: "posExecutive",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "org",
    align: "left",
    label: "หน่วยงานที่สังกัด",
    sortable: true,
    field: "org",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "dateStart",
    align: "left",
    label: "วันที่เริ่มต้น",
    sortable: true,
    field: "dateStart",
    format: (v) => date2Thai(v),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "dateEnd",
    align: "left",
    label: "วันที่สิ้นสุด",
    sortable: true,
    field: "dateEnd",
    format: (v) => date2Thai(v),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "trainingDays",
    align: "left",
    label: "จำนวนวันที่อบรม",
    sortable: true,
    field: "trainingDays",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "commandNumber",
    align: "left",
    label: "เลขที่คำสั่ง/เลขที่หนังสืออนุมัติ",
    sortable: true,
    field: "commandNumber",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "commandDate",
    align: "left",
    label: "คำสั่งลงวันที่/หนังสืออนุมัติลงวันที่",
    sortable: true,
    field: "commandDate",
    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 visibleColumns = ref<string[]>([
  "type",
  "idcard",
  "fullName",
  "position",
  "posTypeName",
  "posLevelName",
  "posExecutive",
  "startDate",
  "endDate",
  "trainingDays",
  "org",
  "commandNumber",
  "commandDate",
]);
const files = ref<any>([]);
const pagination = ref({
  page: 1,
  rowsPerPage: 10,
});
const keyword = ref<string>("");
const rows = ref<ResRecord[]>([]);

async function clickUpload(file: any) {
  dialogConfirm(
    $q,
    async () => {
      const selectedFile = file;
      const formData = new FormData();
      formData.append("file", selectedFile);
      await http
        .post(config.API.developmentMainTab("tab6", id.value), formData)
        .then((res) => {
          success($q, "อัปโหลดไฟล์สำเร็จ");
          getData();
        })
        .catch((err) => {
          messageError($q, err);
        });
    },
    "ยืนยันการอัปโหลดไฟล์",
    "ต้องการยืนยันการอัปโหลดไฟล์นี้หรือไม่ ?"
  );
}

function formBmaofficer(val: string) {
  switch (val) {
    case "OFFICER":
      return "ขรก.กทม. สามัญ";
    case "EMPLOYEE_PERM":
      return "ลูกจ้างประจำ";
    case "EMPLOYEE_TEMP":
      return "ลูกจ้างชั่วคราว";
    default:
      return "";
  }
}

async function getData() {
  showLoader();
  await http
    .get(config.API.developmentMainTab("tab6", id.value))
    .then((res) => {
      rows.value = res.data.result;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

function sendRecordRegistry() {
  // ส่งไปบันทึกที่ทะเบียนประวัติ
  dialogConfirm(
    $q,
    async () => {
      showLoader();
      // post
      await http
        .get(config.API.developmentMainTab("tab6/done", id.value))
        .then((res) => {
          success($q, "ส่งข้อมูลสำเร็จ");
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(() => {
          hideLoader();
        });
    },
    "ยืนยันการส่งข้อมูลไปบันทึกยังทะเบียนประวัติ",
    "ต้องการยืนยันการส่งข้อมูลไปบันทึกยังทะเบียนประวัติหรือไม่"
  );
}

onMounted(() => {
  getData();
});
</script>

<template>
  <q-toolbar style="padding: 0px" class="text-primary q-mb-xs">
    <q-file
      v-model="files"
      dense
      label="อัปโหลดไฟล์"
      outlined
      accept=".xlsx"
      hide-bottom-space
      clearable
      class="col-xs-12 col-sm-4"
    >
      <template v-slot:prepend>
        <q-icon name="attach_file" color="blue" />
      </template>
    </q-file>
    <q-btn
      v-if="files"
      size="md"
      icon="mdi-upload"
      round
      flat
      color="blue"
      @click="clickUpload(files)"
    >
      <q-tooltip>อัปโหลดไฟล์</q-tooltip>
    </q-btn>
    <q-btn
      v-if="rows.length > 0"
      size="md"
      icon="mdi-clipboard-account-outline"
      round
      flat
      color="public"
      @click="sendRecordRegistry()"
    >
      <q-tooltip>ส่งไปบันทึกที่ทะเบียนประวัติ</q-tooltip>
    </q-btn>

    <q-space />
    <q-input dense outlined v-model="keyword" label="ค้นหา" class="q-mr-sm">
      <template v-slot:append>
        <q-icon name="search" />
      </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="min-width: 150px"
      class="q-mr-sm"
    />
  </q-toolbar>
  <d-table
    ref="table"
    row-key="id"
    flat
    bordered
    dense
    :columns="columns"
    :rows="rows"
    :paging="true"
    :filter="keyword"
    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>
        <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-if="props.row.isDone">
          <q-icon name="mdi-check" color="green" size="xs">
            <q-tooltip>ส่งไปบันทึกที่ทะเบียนประวัติแล้ว</q-tooltip>
          </q-icon>
        </q-td>
        <q-td v-for="col in props.cols" :key="col.id">
          <div>{{ col.value ? col.value : "-" }}</div>
        </q-td>
      </q-tr>
    </template>
  </d-table>
</template>

<style scoped></style>
