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

import { useRoute, useRouter } from "vue-router";
import { checkPermission } from "@/utils/permissions";
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";

import type { QTableColumn } from "quasar";
import type { DataOption } from "@/modules/04_registryPerson/interface/index/Main";
import type { DatAssistance } from "@/modules/04_registryPerson/interface/request/Government";
import type {
  ResAssistanceData,
  ResFileData,
} from "@/modules/04_registryPerson/interface/response/Government";

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

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

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 citizenId = defineModel<string>("citizenId", {
  required: true,
});

const baseColumns = ref<QTableColumn[]>([
  {
    name: "commandName",
    align: "left",
    label: "ประเภทคำสั่ง",
    sortable: true,
    field: "commandName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },

  {
    name: "agency",
    align: "left",
    label: "หน่วยงานที่ให้ช่วยราชการ/ส่งตัวกลับ",
    sortable: true,
    field: "agency",
    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: "commandNo",
    align: "left",
    label: "เลขที่คำสั่ง",
    sortable: true,
    field: "commandNo",
    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",
    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 baseVisibleColumns = ref<string[]>([
  "commandName",
  "agency",
  "dateStart",
  "dateEnd",
  "commandNo",
  "document",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);

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

/** Table*/
const rows = ref<ResAssistanceData[]>([]); //รายการวินัย
const rowsMain = ref<ResAssistanceData[]>([]); //รายการวินัย
const mode = ref<string>("table"); //การแสดงผล Table card
const filterKeyword = 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",
});

/** Dialog*/
const isStatusEdit = ref<boolean>(false);
const isUpload = ref<boolean>(false);

const rowId = ref<string>("");
const modal = ref<boolean>(false);
const modalHistory = ref<boolean>(false);

const modalCommand = ref<boolean>(false);
const command = ref<string>("");
const commandId = ref<string>("");

const commandCodeOptions = ref<DataOption[]>([
  {
    name: "ให้ช่วยราชการ",
    id: "ให้ช่วยราชการ",
  },
  {
    name: "ให้ข้าราชการกลับไปปฏิบัติงานทางต้นสังกัดเดิม",
    id: "ให้ข้าราชการกลับไปปฏิบัติงานทางต้นสังกัดเดิม",
  },
]); //รายการปรเภทคำสั่ง

const formData = reactive<DatAssistance>({
  agency: "",
  dateStart: null,
  dateEnd: null,
  commandNo: "",
  document: "",
  commandName: "",
  // isUpload: false,
});
const fileUpload = ref<File>();
const fileData = ref<ResFileData>();

/** ฟังก์ค้นหาข้อมูลรายการ */
function serchDataTable() {
  rows.value = onSearchDataTable(
    filterKeyword.value,
    rowsMain.value,
    columns.value ? columns.value : []
  );
}

async function fetchData() {
  showLoader();
  await http
    .get(config.API.profileAssistance(empType.value, profileId.value))
    .then((res) => {
      const data = res.data.result;
      rowsMain.value = data;
      serchDataTable();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

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

function onSubmit() {
  dialogConfirm($q, async () => {
    showLoader();
    const body = {
      ...formData,
      dateStart: convertDateToAPI(formData.dateStart),
      dateEnd: convertDateToAPI(formData.dateEnd),
      profileId: isStatusEdit.value ? undefined : profileId.value,
      isUpload: !isStatusEdit.value ? undefined : isUpload.value,
    };
    const method = isStatusEdit.value ? "patch" : "post";
    await http[method](
      config.API.profileAssistance(
        empType.value,
        isStatusEdit.value ? rowId.value : ""
      ),
      body
    )
      .then(async (res) => {
        if (fileUpload.value) {
          const id = isStatusEdit.value ? rowId.value : res.data.result;
          await uploadProfile(id);
        }
        await fetchData();
        success($q, "บันทึกข้อมูลสำเร็จ");
        closeDialogForm();
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/**
 * ฟังก์ชันส้ราง Path อัปโหลดไฟล์
 * @param id
 */
async function uploadProfile(id: string) {
  await http
    .post(
      config.API.subFile("ทะเบียนประวัติ", "ช่วยราชการ", profileId.value, id),
      {
        replace: true,
        fileList: [
          {
            fileName: "เอกสารหลักฐาน",
          },
        ],
      }
    )
    .then(async (res) => {
      const uploadUrl = res.data["เอกสารหลักฐาน"].uploadUrl;
      await uploadFileURL(uploadUrl, fileUpload.value, id);
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/**
 * ฟังก์ชันอัปโหลไฟล์
 * @param uploadUrl Path อัปโหลดไฟล์
 * @param file ไฟล์เอกสาร
 */
async function uploadFileURL(uploadUrl: string, file: any, id: string) {
  await axios
    .put(uploadUrl, file, {
      headers: {
        "Content-Type": file.type,
      },
    })
    .then(async () => {
      await updateIsUpload(id, true);
      fileUpload.value = undefined;
    })
    .catch(async (err) => {
      await updateIsUpload(id, false);
      messageError($q, err);
    });
}

async function updateIsUpload(id: string, val: boolean) {
  await http
    .patch(config.API.profileAssistance(empType.value, id), { isUpload: val })
    .then(async (res) => {})
    .catch((err) => {
      messageError($q, err);
    });
}

/**
 * ฟังก์ชันโหลไฟลเอกสารหลักฐาน
 * @param id รายการที่ต้องการโหลด
 */
async function onDownloadFile(id: string, isLoad: boolean = true) {
  showLoader();
  await http
    .get(
      config.API.subFileByFileName(
        "ทะเบียนประวัติ",
        "ช่วยราชการ",
        profileId.value,
        id,
        "เอกสารหลักฐาน"
      )
    )
    .then(async (res) => {
      const data = res.data;
      fileData.value = data;
      if (isLoad) {
        window.open(data.downloadUrl, "_blank");
      }
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function openEditDialog(data: ResAssistanceData) {
  modal.value = true;
  isStatusEdit.value = true;
  rowId.value = data.id;
  formData.agency = data.agency;
  formData.dateStart = data.dateStart;
  formData.dateEnd = data.dateEnd;
  formData.commandNo = data.commandNo;
  formData.document = data.document;
  formData.commandName = data.commandName;
  isUpload.value = data.isUpload;
  if (isUpload.value) {
    onDownloadFile(data.id, false);
  }
}

function showHistoryDialog(id: string) {
  modalHistory.value = true;
  rowId.value = id;
}

function openViewCommand(data: ResAssistanceData) {
  command.value = data.commandNo;
  commandId.value = data.commandId;
  modalCommand.value = true;
}

function closeDialogForm() {
  modal.value = false;
  isStatusEdit.value = false;
  rowId.value = "";
  formData.agency = "";
  formData.dateStart = null;
  formData.dateEnd = null;
  formData.commandNo = "";
  formData.document = "";
  formData.commandName = "";
  isUpload.value = false;
  fileUpload.value = undefined;
}

/**
 * ฟังก์ชันส่งตัวกลับ
 * @param refId  ของช่วยราชการ
 */
async function onReturner(refId: string) {
  showLoader();
  const formData = new FormData();
  formData.append("OfficerId", refId);
  formData.append("Id", profileId.value);

  await http
    .post(config.API.profileAssistanceReturn, formData)
    .then(async () => {
      router.push("/placement/repatriate");
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

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

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

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

    <q-space />
    <q-input
      standout
      dense
      v-model="filterKeyword"
      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="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"
    :visible-columns="visibleColumns"
    v-model:pagination="pagination"
  >
    >
    <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="mode === 'table'">
      <q-tr :props="props">
        <q-td auto-width>
          <q-btn
            flat
            dense
            round
            color="deep-purple"
            icon="mdi-history"
            @click.stop.prevent="showHistoryDialog(props.row.id)"
          >
            <q-tooltip>ประวัติแก้ไขรายการช่วยราชการ</q-tooltip>
          </q-btn>
          <q-btn
            v-if="!isLeave && checkPermission($route)?.attrIsUpdate"
            flat
            dense
            round
            :color="props.row.commandId ? 'grey-5' : 'edit'"
            :disable="props.row.commandId !== null"
            icon="edit"
            @click.stop.prevent="openEditDialog(props.row)"
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>

          <q-btn
            v-if="
              checkPermission($route)?.attrIsUpdate &&
              props.row.commandName === 'ให้ช่วยราชการ'
            "
            flat
            dense
            round
            :color="
              !props.row.refId || props.row.status !== 'PENDING'
                ? 'grey-5'
                : 'primary'
            "
            :disable="!props.row.refId || props.row.status !== 'PENDING'"
            icon="mdi-account-arrow-left-outline"
            @click.stop.prevent="onReturner(props.row.refId)"
          >
            <q-tooltip>ส่งตัวกลับ</q-tooltip>
          </q-btn>

          <q-btn
            v-if="
              !isLeave &&
              checkPermission($route)?.attrIsDelete &&
              !props.row.commandId
            "
            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">
          <div
            v-if="col.name == 'commandNo' && props.row.commandId"
            @click="col.value ? openViewCommand(props.row) : null"
            :class="
              col.value
                ? 'table_ellipsis text-blue cursor-pointer'
                : 'table_ellipsis'
            "
          >
            {{ col.value ? col.value : "-" }}
            <q-tooltip v-if="col.value">ดูคำสั่ง</q-tooltip>
          </div>
          <div v-else>
            {{ col.value ? col.value : "-" }}
          </div>
        </q-td>
        <q-td auto-width>
          <q-btn
            flat
            dense
            round
            color="green"
            icon="mdi-file-document-outline"
            v-if="props.row.isUpload"
            @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 align="right" class="bg-grey-3">
            <q-btn
              flat
              dense
              round
              color="green"
              icon="mdi-file-document-outline"
              v-if="props.row.isUpload"
              @click="onDownloadFile(props.row.id)"
            >
              <q-tooltip>ดาวน์โหลด</q-tooltip>
            </q-btn>
            <q-btn
              color="deep-purple"
              icon="mdi-history"
              flat
              round
              @click.stop.prevent="showHistoryDialog(props.row.id)"
            >
              <q-tooltip>ประวัติแก้ไขรายการช่วยราชการ</q-tooltip>
            </q-btn>
            <q-btn
              v-if="!isLeave && checkPermission($route)?.attrIsUpdate"
              :color="props.row.commandId ? 'grey-5' : 'edit'"
              :disable="props.row.commandId !== null"
              icon="edit"
              flat
              round
              @click.stop.prevent="openEditDialog(props.row)"
            >
              <q-tooltip>แก้ไขข้อมูล</q-tooltip>
            </q-btn>
            <q-btn
              v-if="checkPermission($route)?.attrIsUpdate"
              flat
              dense
              round
              :color="
                !props.row.refId || props.row.status !== 'PENDING'
                  ? 'grey-5'
                  : 'primary'
              "
              :disable="!props.row.refId || props.row.status !== 'PENDING'"
              icon="mdi-account-arrow-left-outline"
              @click.stop.prevent="onReturner(props.row.refId)"
            >
              <q-tooltip>ส่งตัวกลับ</q-tooltip>
            </q-btn>

            <q-btn
              v-if="
                !isLeave &&
                checkPermission($route)?.attrIsDelete &&
                !props.row.commandId
              "
              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
                  v-if="col.name == 'commandNo' && props.row.commandId"
                  @click="col.value ? openViewCommand(props.row) : null"
                  :class="
                    col.value
                      ? 'table_ellipsis text-blue cursor-pointer'
                      : 'table_ellipsis'
                  "
                >
                  {{ col.value ? col.value : "-" }}
                  <q-tooltip v-if="col.value">ดูคำสั่ง</q-tooltip>
                </div>
                <div v-else>{{ col.value ? col.value : "-" }}</div>
              </div>
            </div>
          </q-list>
        </q-card>
      </div>
    </template>
  </d-table>

  <q-dialog v-model="modal" persistent>
    <q-card style="width: 700px; max-width: 80vw">
      <q-form @submit.prevent greedy @validation-success="onSubmit()">
        <DialogHeader
          :tittle="
            isStatusEdit
              ? 'แก้ไขข้อมูลรายการช่วยราชการ'
              : 'เพิ่มข้อมูลรายการช่วยราชการ'
          "
          :close="closeDialogForm"
        />
        <q-separator />
        <q-card-section style="max-height: 50vh" class="scroll">
          <div class="row col-12 q-col-gutter-x-xs q-col-gutter-y-xs">
            <div class="col-xs-12 col-sm-12 col-md-12">
              <!-- :rules="[(val: string) => !!val || 'กรุณาเลือกประเภทคำสั่ง']" -->
              <q-select
                outlined
                class="full-width inputgreen cursor-pointer"
                dense
                lazy-rules
                borderless
                v-model="formData.commandName"
                :label="`${'ประเภทคำสั่ง'}`"
                emit-value
                map-options
                option-label="name"
                :options="commandCodeOptions"
                option-value="id"
                hide-bottom-space
                use-input
                hide-selected
                fill-input
                input-debounce="0"
              >
                <template v-slot:no-option>
                  <q-item>
                    <q-item-section class="text-grey">
                      ไม่มีข้อมูล
                    </q-item-section>
                  </q-item>
                </template>
              </q-select>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
              <q-input
                class="full-width inputgreen cursor-pointer"
                outlined
                dense
                lazy-rules
                v-model="formData.agency"
                :rules="[(val:string) => !!val || `${'กรุณากรอกหน่วยงานที่ให้ช่วยราชการ'}`]"
                hide-bottom-space
                :label="`${'หน่วยงานที่ให้ช่วยราชการ'}`"
              />
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <datepicker
                menu-class-name="modalfix"
                v-model="formData.dateStart"
                :locale="'th'"
                autoApply
                :enableTimePicker="false"
                week-start="0"
                :max-date="formData.dateEnd"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    ref="dateRef"
                    class="full-width inputgreen cursor-pointer"
                    outlined
                    dense
                    :model-value="date2Thai(formData.dateStart)"
                    :rules="[(val:string) => !!val || `${'กรุณาเลือก วันที่เริ่มต้น'}`]"
                    hide-bottom-space
                    :label="`${'วันที่เริ่มต้น'}`"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        color="primary"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
            <div class="col-xs-12 col-sm-6 col-md-6">
              <datepicker
                menu-class-name="modalfix"
                v-model="formData.dateEnd"
                :locale="'th'"
                autoApply
                :enableTimePicker="false"
                week-start="0"
                :min-date="formData.dateStart"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    ref="dateRef"
                    class="full-width inputgreen cursor-pointer"
                    outlined
                    dense
                    :model-value="date2Thai(formData.dateEnd)"
                    :rules="[(val:string) => !!val || `${'กรุณาเลือก วันที่สิ้นสุด'}`]"
                    hide-bottom-space
                    :label="`${'วันที่สิ้นสุด'}`"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        color="primary"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
              <q-input
                class="full-width inputgreen cursor-pointer"
                outlined
                dense
                lazy-rules
                v-model="formData.commandNo"
                :rules="[(val:string) => !!val || `${'กรุณากรอกเลขที่คำสั่ง'}`]"
                hide-bottom-space
                :label="`${'เลขที่คำสั่ง'}`"
              />
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
              <q-input
                class="full-width inputgreen cursor-pointer"
                outlined
                dense
                lazy-rules
                v-model="formData.document"
                hide-bottom-space
                :label="`${'เอกสารอ้างอิง'}`"
              />
            </div>
            <div class="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>
                <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(rowId)"
                      />

                      <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"
    :title="`ประวัติแก้ไขรายการช่วยราชการ`"
    :columns="columnsHistory"
    :visible-columns="visibleColumnsHistory"
    :fetch-data="fetchDataHistory"
  />

  <DialogPreviewCommand
    v-model:modal="modalCommand"
    v-model:command="command"
    v-model:command-id="commandId"
    :citizen-id="citizenId"
  />
</template>

<style scoped></style>
