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

import { useRoute } from "vue-router";
import { checkPermission } from "@/utils/permissions";
import { useCounterMixin } from "@/stores/mixin";
import { useRegistryNewDataStore } from "@/modules/04_registryPerson/store";
import http from "@/plugins/http";
import config from "@/app.config";

import type { QTableColumn } from "quasar";
import type { ResFileData } from "@/modules/04_registryPerson/interface/index/Main";
import type { RowList } from "@/modules/04_registryPerson/interface/index/salary";
import type { RequestNoPaidObject } from "@/modules/04_registryPerson/interface/request/Salary";

import DialogHeader from "@/components/DialogHeader.vue";
import DialogHistory from "@/modules/04_registryPerson/components/detail/DialogHistory.vue";

const $q = useQuasar();
const route = useRoute();
const {
  date2Thai,
  dialogConfirm,
  showLoader,
  hideLoader,
  messageError,
  success,
  pathRegistryEmp,
  onSearchDataTable,
  convertDateToAPI,
  dialogRemove,
} = useCounterMixin();
const { createPathUploadFlie, getPathUploadFlie, uploadFile } =
  useRegistryNewDataStore();
const salaryText = ref<string>(
  route.name === "registryNewByid" ? "เงินเดือน" : "ค่าจ้าง"
);

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

/** props*/
const isLeave = defineModel<boolean>("isLeave", {
  required: true,
});

const modelView = ref<string>("table"); //การแสดงผล Table,Card
const modalDialog = ref<boolean>(false); //แสดง popup บันทึกวันที่ไม่ได้รับเงินเดือนฯ
const modalHistory = ref<boolean>(false); //แสดง popup ประวัติแก้ไขบันทึกวันที่ไม่ได้รับเงินเดือนฯ
const isStatusEdit = ref<boolean>(false); //สถานะการแก้ไจข้อมูล

const formData = reactive<RequestNoPaidObject>({
  date: null, //วัน/เดือน/ปี
  reference: "", //เอกสารอ้างอิง
  detail: "", //รายละเอียด
  refCommandNo: "", //เลขที่คำสั่ง
  refCommandDate: null, //'เอกสารอ้างอิง (ลงวันที่)'
});

const baseColumns = ref<QTableColumn[]>([
  {
    name: "date",
    align: "left",
    label: "วัน เดือน ปี",
    sortable: true,
    field: "date",
    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: "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: "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: "refCommandNo",
    align: "left",
    label: "เลขที่คำสั่ง",
    sortable: true,
    field: "refCommandNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "refCommandDate",
    align: "left",
    label: "เอกสารอ้างอิง (ลงวันที่)",
    sortable: true,
    field: "refCommandDate",
    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: "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" }),
  },
]);
const baseVisibleColumns = ref<string[]>([
  "date",
  "reference",
  "detail",
  "refCommandNo",
  "refCommandDate",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);

//Table
const rows = ref<RowList[]>([]); //รายการ
const rowsMain = ref<RowList[]>([]); //รายการ
const keyword = ref<string>(""); //คำค้นหา
const columns = ref<QTableColumn[]>(
  baseColumns.value.filter((e: QTableColumn) => e.name !== "lastUpdateFullName")
);
const visibleColumns = ref<string[]>(
  baseVisibleColumns.value.filter((e: string) => e !== "lastUpdateFullName")
);
const pagination = ref({
  sortBy: "lastUpdatedAt",
});

const columnsHistory = ref<QTableColumn[]>(baseColumns.value);
const visibleColumnsHistory = ref<string[]>(baseVisibleColumns.value);

const fileGroup = ref<string>(`เอกสารบันทึกวันที่ไม่ได้รับ${salaryText.value}`);
const fileUpload = ref<File | null>(null);
const fileData = ref<ResFileData | null>(null);
const isUpload = ref<boolean>(false);

/** funciton ยืนยันการบันทึกข้อมูล*/
function onSubmit() {
  dialogConfirm($q, async () => {
    showLoader();
    const url = isStatusEdit.value
      ? config.API.profileNewNoPaidById(id.value, empType.value)
      : config.API.profileNewNoPaid(empType.value);

    const methods = isStatusEdit.value ? http.patch : http.post;

    await methods(url, {
      ...formData,
      date: convertDateToAPI(formData.date),
      refCommandDate: convertDateToAPI(formData.refCommandDate),
      isUpload: !isStatusEdit.value ? undefined : isUpload.value,
      profileId: isStatusEdit.value
        ? undefined
        : empType.value === ""
        ? profileId.value
        : undefined,
      profileEmployeeId: isStatusEdit.value
        ? undefined
        : empType.value !== ""
        ? profileId.value
        : undefined,
    })
      .then(async (res) => {
        if (fileUpload.value) {
          const isId = isStatusEdit.value ? id.value : res.data.result;
          await uploadfile(isId);
        }
        await getData();
        success($q, "บันทึกข้อมูลสำเร็จ");
        onClickCloseDialog();
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/**
 * ฟังก์ชันอัพโหลไฟล์
 * @param id id รายการที่อัพโหลไฟล์
 */
async function uploadfile(id: string) {
  try {
    //สร้าง Path url อัพโหลด
    const uploadUrl = await createPathUploadFlie(
      fileGroup.value,
      profileId.value,
      id
    );

    //อัพโหลไฟล์
    await uploadFile(uploadUrl, fileUpload.value);
    await updateIsUpload(id);
  } catch (err) {
    messageError($q, err);
  }
}

/** ฟังก์ชันอัพเดทสถานะอัพโหลด*/
async function updateIsUpload(id: string) {
  await http
    .patch(config.API.profileNewNoPaidById(id, empType.value), {
      isUpload: fileUpload.value ? true : false,
    })
    .then(() => {
      fileUpload.value = null;
    });
}

/**
 * function เปิด Didalig  บันทึกวันที่ไม่ได้รับเงินเดือนฯ
 * @param StatusEdit แก้ไข , เพิ่ม
 * @param data ข้อมูล
 */
async function onClickOpenDialog(
  StatusEdit: boolean = false,
  data: RowList = {} as RowList
) {
  isStatusEdit.value = StatusEdit;
  id.value = StatusEdit ? data.id : "";
  formData.date = StatusEdit ? data.date : null;
  formData.reference = StatusEdit ? data.reference : "";
  formData.detail = StatusEdit ? data.detail : "";
  formData.refCommandNo = StatusEdit ? data.refCommandNo : "";
  formData.refCommandDate = StatusEdit ? data.refCommandDate : null;
  isUpload.value = data.isUpload;
  modalDialog.value = true;
  if (isUpload.value) {
    const data = await getPathUploadFlie(
      fileGroup.value,
      profileId.value,
      id.value
    );
    fileData.value = data;
  }
}

/** function ปิด Didalig  บันทึกวันที่ไม่ได้รับเงินเดือนฯ*/
function onClickCloseDialog() {
  modalDialog.value = false;
  isStatusEdit.value = false;
}

async function onDownloadFile(id: string) {
  const data = await getPathUploadFlie(fileGroup.value, profileId.value, id);
  window.open(data.downloadUrl, "_blank");
}

/** function fetch รายการบันทึกวันที่ไม่ได้รับเงินเดือนฯ*/
async function getData() {
  showLoader();
  await http
    .get(config.API.profileNewNoPaidByProfileId(profileId.value, empType.value))
    .then(async (res) => {
      rowsMain.value = await res.data.result;
      serchDataTable();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/** function เปิดข้อมูลประวัติการแก้ไช*/
function onClickHistory(rowId: string) {
  id.value = rowId;
  modalHistory.value = true;
}

/** fetch รายการข้อมูลประวัติการแก้ไช*/
async function fetchDataHistory() {
  showLoader();
  try {
    const res = await http.get(
      config.API.profileNewNoPaidHisById(id.value, empType.value)
    );
    return res.data.result;
  } catch (err) {
    messageError($q, err);
  } finally {
    hideLoader();
  }
}

function serchDataTable() {
  rows.value = onSearchDataTable(
    keyword.value,
    rowsMain.value,
    columns.value ? columns.value : []
  );
}

function handleDelete(id: string) {
  dialogRemove($q, async () => {
    showLoader();
    try {
      await http.patch(
        config.API.profileNewNoPaidUpdateDelete(empType.value) + `${id}`
      );
      await getData();
      success($q, "ลบข้อมูลสำเร็จ");
    } catch (err) {
      messageError($q, err);
    } finally {
      hideLoader();
    }
  });
}

/** ทำงานเมื่อ Components ถูกเรียกใช้งาน */
onMounted(() => {
  getData();
});
</script>

<template>
  <div class="row items-center q-gutter-x-sm q-pb-sm">
    <q-btn
      v-if="isLeave == false && checkPermission($route)?.attrIsUpdate"
      dense
      color="primary"
      icon="add"
      flat
      round
      @click="onClickOpenDialog()"
      ><q-tooltip>เพิ่มข้อมูล</q-tooltip></q-btn
    >

    <q-space />
    <q-input
      standout
      dense
      v-model="keyword"
      ref="filterRef"
      outlined
      placeholder="ค้นหา"
      @keydown.enter.prevent="serchDataTable"
    >
      <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"
      style="min-width: 140px"
    />
    <q-btn-toggle
      v-model="modelView"
      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: modelView === 'table' ? '#787B7C' : '#C9D3DB',
          }"
        />
      </template>

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

  <d-table
    ref="table"
    row-key="id"
    flat
    bordered
    dense
    :grid="modelView === 'card'"
    :columns="columns"
    :rows="rows"
    v-model:pagination="pagination"
    :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-th auto-width />
      </q-tr>
    </template>
    <template v-slot:body="props" v-if="modelView === 'table'">
      <q-tr :props="props">
        <q-td auto-width>
          <q-btn
            flat
            dense
            round
            color="deep-purple"
            icon="mdi-history"
            @click.stop.prevent="onClickHistory(props.row.id)"
          >
            <q-tooltip>{{
              `ประวัติบันทึกวันที่ไม่ได้รับ${salaryText}ฯ`
            }}</q-tooltip>
          </q-btn>
          <q-btn
            v-if="isLeave == false && checkPermission($route)?.attrIsUpdate"
            flat
            dense
            round
            color="edit"
            icon="edit"
            @click="onClickOpenDialog(true, props.row)"
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>

          <q-btn
            v-if="!isLeave && checkPermission($route)?.attrIsDelete"
            color="red"
            flat
            dense
            round
            icon="delete"
            @click="handleDelete(props.row.id)"
          >
            <q-tooltip>ลบข้อมูล</q-tooltip>
          </q-btn>
        </q-td>
        <q-td
          v-for="col in props.cols"
          :key="col.id"
          :class="props.row.isEntry ? 'text-grey' : ''"
        >
          <div>{{ col.value ? col.value : "-" }}</div>
        </q-td>
        <q-td auto-width>
          <q-btn
            v-if="props.row.isUpload"
            color="green"
            flat
            dense
            round
            icon="mdi-file-document-outline"
            @click="onDownloadFile(props.row.id)"
          >
            <q-tooltip>ดาวน์โหลด</q-tooltip>
          </q-btn>
        </q-td>
      </q-tr>
    </template>
    <template v-slot:item="props" v-else>
      <div class="q-pa-xs col-xs-12 col-sm-4 col-md-3">
        <q-card flat bordered>
          <q-card-actions class="bg-grey-3" align="right">
            <q-btn
              v-if="props.row.isUpload"
              color="green"
              flat
              dense
              round
              icon="mdi-file-document-outline"
              @click="onDownloadFile(props.row.id)"
            >
              <q-tooltip>ดาวน์โหลด</q-tooltip>
            </q-btn>
            <q-btn
              flat
              round
              color="deep-purple"
              icon="mdi-history"
              @click="onClickHistory(props.row.id)"
            >
              <q-tooltip>{{
                `ประวัติบันทึกวันที่ไม่ได้รับ${salaryText}ฯ`
              }}</q-tooltip>
            </q-btn>
            <q-btn
              v-if="isLeave == false && checkPermission($route)?.attrIsUpdate"
              flat
              round
              color="edit"
              icon="edit"
              @click="onClickOpenDialog(true, props.row)"
            >
              <q-tooltip>แก้ไขข้อมูล</q-tooltip>
            </q-btn>

            <q-btn
              v-if="!isLeave && checkPermission($route)?.attrIsDelete"
              color="red"
              flat
              dense
              round
              icon="delete"
              @click="handleDelete(props.row.id)"
            >
              <q-tooltip>ลบข้อมูล</q-tooltip>
            </q-btn>
          </q-card-actions>
          <q-separator />
          <q-list>
            <div
              :class="`row q-pa-sm`"
              :style="`background-color: ${index % 2 !== 0 ? '#FAFAFA' : ''}`"
              v-for="(col, index) in props.cols"
              :key="col.name"
            >
              <div class="col text-grey-6">
                <div>{{ col.label }}</div>
              </div>
              <div class="col">
                <div>{{ col.value ? col.value : "-" }}</div>
              </div>
            </div>
          </q-list>
        </q-card>
      </div>
    </template>
  </d-table>

  <q-dialog v-model="modalDialog" persistent>
    <q-card>
      <q-form @submit.prevent greedy @validation-success="onSubmit">
        <DialogHeader
          :tittle="
            isStatusEdit
              ? `แก้ไขบันทึกวันที่ไม่ได้รับ${salaryText}ฯ`
              : `เพิ่มบันทึกวันที่ไม่ได้รับ${salaryText}ฯ`
          "
          :close="onClickCloseDialog"
        />
        <q-separator />

        <q-card-section>
          <div class="row col-12 q-col-gutter-sm">
            <div class="col-xs-12 col-sm-6 col-md-6">
              <datepicker
                menu-class-name="modalfix"
                v-model="formData.date"
                :locale="'th'"
                autoApply
                :enableTimePicker="false"
                week-start="0"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    ref="dateRef"
                    outlined
                    dense
                    borderless
                    class="inputgreen"
                    :model-value="date2Thai(formData.date)"
                    :rules="[(val:string) => !!val || `${'กรุณาเลือก วัน/เดือน/ปี'}`]"
                    hide-bottom-space
                    :label="`${'วัน/เดือน/ปี'}`"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        style="color: var(--q-primary)"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-input
                ref="referenceRef"
                outlined
                dense
                autogrow
                lazy-rules
                borderless
                v-model="formData.reference"
                class="inputgreen"
                :rules="[(val:string) => !!val || `${'กรุณากรอกเอกสารอ้างอิง'}`]"
                hide-bottom-space
                :label="`${'เอกสารอ้างอิง'}`"
              />
            </div>
            <div class="col-12">
              <q-input
                ref="detailRef"
                outlined
                dense
                autogrow
                lazy-rules
                borderless
                v-model="formData.detail"
                class="inputgreen"
                :rules="[(val:string) => !!val || `${'กรุณากรอกรายละเอียด'}`]"
                hide-bottom-space
                :label="`${'รายละเอียด'}`"
              />
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <q-input
                outlined
                dense
                lazy-rules
                borderless
                v-model="formData.refCommandNo"
                class="inputgreen"
                hide-bottom-space
                :label="`${'เลขที่คำสั่ง'}`"
              >
                <template v-slot:append>
                  <q-icon name="mdi-file" class="cursor-pointer" />
                </template>
              </q-input>
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <datepicker
                menu-class-name="modalfix"
                v-model="formData.refCommandDate"
                :locale="'th'"
                autoApply
                :enableTimePicker="false"
                week-start="0"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    clearable
                    outlined
                    dense
                    borderless
                    class="inputgreen"
                    :model-value="
                formData.refCommandDate == null ? null : date2Thai(formData.refCommandDate as Date)
                "
                    hide-bottom-space
                    :label="`${'เอกสารอ้างอิง (ลงวันที่)'}`"
                    @clear="formData.refCommandDate = null"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        style="color: var(--q-primary)"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>

            <div class="row col-xs-12 col-sm-12 col-md-12">
              <q-uploader
                v-if="!isUpload"
                color="gray"
                type="file"
                flat
                ref="uploader"
                class="full-width"
                text-color="white"
                :max-size="10000000"
                accept=".pdf"
                bordered
                label="[ไฟล์ pdf ขนาดไม่เกิน 10MB]"
                @added="(v:any) => (fileUpload = v[0])"
              >
                <template v-slot:header="scope">
                  <div class="row no-wrap items-center q-pa-sm q-gutter-xs">
                    <q-btn
                      v-if="scope.queuedFiles.length > 0"
                      icon="clear_all"
                      @click="scope.removeQueuedFiles"
                      round
                      dense
                      flat
                    >
                      <q-tooltip>ลบทั้งหมด</q-tooltip>
                    </q-btn>
                    <q-btn
                      v-if="scope.uploadedFiles.length > 0"
                      icon="done_all"
                      @click="scope.removeUploadedFiles"
                      round
                      dense
                      flat
                    >
                      <q-tooltip>ลบไฟล์ที่อัปโหลด</q-tooltip>
                    </q-btn>
                    <q-spinner
                      v-if="scope.isUploading"
                      class="q-uploader__spinner"
                    />
                    <div class="col">
                      <div class="q-uploader__title">
                        {{ "[ไฟล์ .pdf ขนาดไม่เกิน 10MB]" }}
                      </div>
                      <div class="q-uploader__subtitle">
                        {{ scope.uploadSizeLabel }} /
                        {{ scope.uploadProgressLabel }}
                      </div>
                    </div>
                    <q-btn
                      v-if="scope.canAddFiles"
                      type="a"
                      icon="add_box"
                      @click="scope.pickFiles"
                      round
                      dense
                      flat
                    >
                      <q-uploader-add-trigger />
                      <q-tooltip>เลือกไฟล์</q-tooltip>
                    </q-btn>
                    <q-btn
                      v-if="scope.isUploading"
                      icon="clear"
                      @click="scope.abort"
                      round
                      dense
                      flat
                    >
                      <q-tooltip>ยกเลิกการอัปโหลด</q-tooltip>
                    </q-btn>
                  </div>
                </template>
              </q-uploader>

              <q-list bordered dense separator v-else class="full-width">
                <q-item>
                  <q-item-section> {{ fileData?.fileName }}</q-item-section>
                  <q-item-section avatar>
                    <div class="row">
                      <q-btn
                        flat
                        round
                        color="primary"
                        icon="mdi-download"
                        @click="onDownloadFile(id)"
                      />

                      <q-btn
                        flat
                        round
                        color="grey"
                        icon="close"
                        @click="isUpload = false"
                      />
                    </div>
                  </q-item-section>
                </q-item>
              </q-list>
            </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>

  <DialogHistory
    v-model:modal="modalHistory"
    :visible-columns="visibleColumnsHistory"
    :title="`ประวัติแก้ไขบันทึกวันที่ไม่ได้รับ${salaryText}ฯ`"
    :columns="columnsHistory"
    :fetch-data="fetchDataHistory"
  />
</template>

<style scoped></style>
