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

import { useQuasar, QForm } from "quasar";
import { useRoute } from "vue-router";

import http from "@/plugins/http";
import config from "@/app.config";
import genReport from "@/plugins/genreport";
import { useCounterMixin } from "@/stores/mixin";

import type { RetirementList } from "@/modules/06_retirement/interface/index/Main";

import DialogHeader from "@/components/DialogHeader.vue";
import DialogPopupReason from "@/components/Dialogs/PopupReason.vue";
import PopupPersonal from "@/components/Dialogs/PopupPersonalNew.vue";
import AddList from "@/modules/06_retirement/components/01_retirement/AddList.vue";

/** Use */
const route = useRoute();
const checkRoutePermisson = ref<boolean>(route.name == "retirementidDetail");
const $q = useQuasar();
const mixin = useCounterMixin();
const {
  showLoader,
  hideLoader,
  messageError,
  success,
  dialogConfirm,
  dialogRemove,
  date2Thai,
  dateToISO,
  findOrgName,
  findOrgNameHtml,
  onSearchDataTable,
} = mixin;
const myForm = ref<QForm | null>(null);

/** ตัวแปร  */
const linkFile = ref<string>("");
const modal = ref<boolean>(false);
const retireld_params = route.params.retirementId;
const retireld = ref<string>(retireld_params.toString());
const modalPersonal = ref<boolean>(false);
const personId = ref<string>("");
const modalNote = ref<boolean>(false);
const note = ref<string>("");
const retireProfileId = ref<string>("");
const profileId = ref<string>("");
const filter = ref<string>("");
const statusUpload = ref<boolean>();
const modalEdit = ref<boolean>(false);
const textReport = ref<string>("");
const employeeType = ref<string>("OFFICER");
const action = ref<string>("");
const fileUpload = ref<any>(null);
const round = ref<number>();
const typeReport = ref<string>("");
const statusReport = ref<boolean>();
const dataProfile = ref<any>([]);

/** คอลัมน์ที่แสดง */
const columns = computed(() => [
  {
    name: "order",
    label: "ลำดับ",
    title: "ลำดับ",
    field: "order",
    align: "left",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val: number, row: RetirementList) {
      return val === 0 ? "" : val;
    },
  },
  {
    name: "name",
    align: "left",
    label: "ชื่อ-นามสกุล",
    title: "ชื่อ-นามสกุล",
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val: string, row: RetirementList) {
      return `${row.prefix ?? ""}${row.firstName ?? ""} ${row.lastName ?? ""}`;
    },
  },
  {
    name: "position",
    align: "left",
    label: `ตำแหน่ง ${employeeType.value == "OFFICER" ? "(ในสายงาน)" : ""}`,
    title: "ตำแหน่ง",
    subtitle: employeeType.value == "OFFICER" ? "ในสายงาน" : "",
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionType",
    align: "left",
    label: `ตำแหน่ง (${
      employeeType.value == "OFFICER" ? "ประเภท" : "กลุ่มงาน"
    })`,
    title: employeeType.value == "OFFICER" ? "ตำแหน่ง" : "กลุ่มงาน",
    subtitle: employeeType.value == "OFFICER" ? "ประเภท" : "",
    field: "positionType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },

  {
    name: "positionNumber",
    align: "left",
    label: "ตำแหน่ง (เลขที่)",
    title: employeeType.value == "OFFICER" ? "เลขที่" : "ตำแหน่ง",
    subtitle: employeeType.value == "OFFICER" ? "ตำแหน่ง" : "เลขที่",
    field: "positionNumber",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "organization",
    align: "left",
    label: "สังกัด",
    title: "สังกัด",
    field: "organization",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val: any, row: any) {
      return findOrgName(row);
    },
  },
]);
const rows = ref<RetirementList[]>([]);
const rowsData = ref<RetirementList[]>([]);
const visibleColumns = ref<string[]>([
  "order",
  "name",
  "organizationOrganization",
  "position",
  "positionType",
  "positionNumber",
  "govGroup",
  "govOffice",
  "organization",
]);

/**
 * ฟังก์ชั่นปิด Dialog
 */
function closeDialog() {
  modalNote.value = false;
  modalUpload.value = false;
}

// fecthlist
async function fetchlistprofile(id: string) {
  showLoader();
  await http
    .get(config.API.listRetire(id))
    .then(async (res) => {
      const data = await res.data.result;

      dataProfile.value = data;
      round.value = data.round;
      statusReport.value = data.json;
      typeReport.value = data.typeReport;
      textReport.value = data.detail;
      employeeType.value = data.type;
      linkFile.value = data.file;

      // รายชื่อผู้เกษียณอายุราชการ
      if (data.profile !== null) {
        const listData = data.profile.map((e: any) => ({
          id: e.id,
          profileId: e.profileId,
          order: e.order,
          prefix: e.prefix,
          firstName: e.firstName,
          lastName: e.lastName,
          organization: e.root,
          position: e.position,
          positionNumber: e.posNo,
          positionType:
            e.posTypeName && e.posLevelName !== null
              ? `${e.posTypeName} ${
                  e.posLevelName ? `(${e.posLevelName})` : ""
                }`
              : "-",
          positionLevel: e.posLevelName,
          reason: e.reason,
          remove: e.remove,
          root: e.root,
          rootId: e.rootId,
          child1: e.child1,
          child1Id: e.child1Id,
          child2: e.child2,
          child2Id: e.child2Id,
          child3: e.child3,
          child3Id: e.child3Id,
          child4: e.child4,
          child4Id: e.child4Id,
        }));
        rows.value = listData;
        rowsData.value = listData;
      }

      if (statusReport.value == false) {
        await fecthCheck(retireld.value);
      } else statusUpload.value = true;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

// เช็คสถานะการอัพโหลด
async function fecthCheck(id: string) {
  await http
    .get(config.API.checkfileupload(id))
    .then((res) => {
      statusUpload.value = res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

// DelProfile
function clickDelete() {
  dialogRemove(
    $q,
    async () => {
      showLoader();
      await http
        .post(config.API.removeProfile(), {
          retireProfileId: retireProfileId.value,
          reason: note.value,
        })
        .then(async () => {
          retireld.value = retireld_params.toString();
          await fetchlistprofile(retireld.value);
          modalNote.value = false;
          success($q, "ลบข้อมูลสำเร็จ");
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(async () => {
          hideLoader();
        });
    },
    "ยืนยันการลบข้อมูล",
    "ต้องการลบข้อมูลนี้ใช่หรือไม่ ?"
  );
}

// แก้ไข้ข้อมูล
function saveNote() {
  dialogConfirm(
    $q,
    async () => {
      showLoader();
      await http
        .post(config.API.createnote(), {
          retireProfileId: retireProfileId.value,
          reason: note.value,
        })
        .then(async () => {
          retireld.value = retireld_params.toString();
          await fetchlistprofile(retireld.value);
          modalNote.value = false;
          success($q, "บันทึกข้อมูลสำเร็จ");
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(() => {
          hideLoader();
        });
    },
    "ยืนยันการบันทึกข้อมูล",
    "ต้องการบันทึกข้อมูลนี้ใช่หรือไม่ ?"
  );
}

//อัพเดท ListId
function UpdateListId(retireld: string, pId: string) {
  profileId.value = pId;
  fetchlistprofile(retireld);
}

// กลับหน้าเดิม
function backHistory() {
  window.history.back();
}

const visibleNote = computed(() => {
  if (note.value === "" || note.value === undefined) {
    return true;
  }
});

// อัปโหลดไฟล์
const modalUpload = ref<boolean>(false);
const signDate = ref<Date | null>(null);
async function uploadFile(event: any, signDate: any) {
  if (myForm.value !== null) {
    myForm.value.validate().then((successmyForm) => {
      if (successmyForm) {
        dialogConfirm(
          $q,
          async () => {
            showLoader();
            const selectedFile = event;
            const formdata = new FormData();
            formdata.append("file", selectedFile);
            if (signDate != null)
              formdata.append("signDate", dateToISO(signDate));
            await http
              .put(
                config.API.fileRetirement(retireld.value.toString()),
                formdata
              )
              .then(async (res) => {
                await fetchlistprofile(retireld.value);
                modalUpload.value = false;
                success($q, "เพิ่มไฟล์สำเร็จ");
                fileUpload.value = null;
                signDate.value = null;
              })
              .catch((err) => {
                messageError($q, err);
              })
              .finally(() => {
                hideLoader();
              });
          },
          "ยืนยันการอัปโหลดเอกสาร",
          "ต้องการยืนยันการอัปโหลดเอกสารนี้หรือไม่ ?"
        );
      }
    });
  }
}

/**
 * ดาวห์โหลด ไฟล์
 * @param type pdf/docx
 * @param id
 */
async function downloadAttachment(type: string, id: string) {
  showLoader();
  await http
    .get(config.API.reportRetireList(type, id))
    .then(async (res) => {
      const data = res.data.result;
      await genReport(data, `รายชื่อผู้เกษียณอายุราชการ`, type);
    })
    .catch(async (e) => {
      messageError($q, JSON.parse(await e.response.data.text()));
    })
    .finally(() => {
      hideLoader();
    });
}

// ยืนยันการแก้ไขข้อมูล
function saveEdiitReport(reason: string) {
  const formdata = new FormData();
  formdata.append("Detail", reason);
  dialogConfirm(
    $q,
    async () => {
      showLoader();
      await http
        .put(config.API.editDetail(retireld.value), formdata)
        .then(() => {
          fetchlistprofile(retireld.value);
          modalEdit.value = false;
          success($q, "แก้ไขข้อความสำเร็จ");
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    },
    "ยืนยันการแก้ไขข้อมูล",
    "ต้องการยืนยันการแก้ไขข้อมูลนี้หรือไม่ ?"
  );
}

// เปิด popup เหตุผล
function openmodalEditReport() {
  modalEdit.value = true;
}

/** Setting Pagination */
const paging = ref<boolean>(true);
const pagination = ref({
  sortBy: "order",
  descending: false,
  page: 1,
  rowsPerPage: 10,
});
function paginationLabel(start: number, end: number, total: number) {
  if (paging.value == true) return " " + start + "-" + end + " ใน " + total;
  else return start + "-" + end + " ใน " + total;
}

/**
 * ดูข้อมูลในทะเบียนประวัติ
 * @param id บุคคล
 */
function onclickViewinfo(id: string) {
  modalPersonal.value = true;
  personId.value = id;
}

/** ทะเบียนประวัติ */
function updatemodalPersonal(modal: boolean) {
  modalPersonal.value = modal;
}

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

function downloadFile(path: string) {
  window.open(path);
}

/** Hook */
onMounted(async () => {
  linkFile.value = "";
  retireld.value = retireld_params.toString();
  await fetchlistprofile(retireld.value);
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    <q-btn
      icon="mdi-arrow-left"
      unelevated
      round
      dense
      flat
      color="primary"
      class="q-mr-sm"
      @click="backHistory"
    />
    รายชื่อผู้เกษียณอายุราชการ
    {{ employeeType === "OFFICER" ? "ข้าราชการ กทม.สามัญ" : "ลูกจ้างประจำ" }}
  </div>
  <div>
    <q-card class="col-12 q-pa-md">
      <div class="row col-12 q-pb-sm">
        <div class="row">
          <q-btn
            v-if="
              !checkRoutePermisson &&
              !statusReport &&
              (typeReport == 'ADD' || typeReport == '' || typeReport == null) &&
              !statusUpload
            "
            flat
            round
            color="primary"
            icon="mdi-plus"
            @click="modal = true"
          >
            <q-tooltip>เพิ่มรายชื่อ</q-tooltip></q-btn
          >
          <q-btn
            v-if="statusUpload"
            outline
            color="primary"
            @click="downloadFile(linkFile)"
            >ดาวน์โหลดไฟล์</q-btn
          >
          <q-btn
            color="primary"
            flat
            round
            icon="mdi-dots-vertical"
            v-if="!statusUpload"
          >
            <q-menu>
              <q-list style="min-width: 100px">
                <q-item
                  clickable
                  v-close-popup
                  type="a"
                  @click="
                    (modalUpload = true), (signDate = null), (fileUpload = null)
                  "
                  target="_blank"
                  v-if="!statusUpload && !checkRoutePermisson"
                >
                  <q-item-section avatar
                    ><q-icon color="blue" name="attach_file"
                  /></q-item-section>
                  <q-item-section>อัปโหลดไฟล์ </q-item-section>
                </q-item>
                <q-item
                  v-if="!checkRoutePermisson"
                  clickable
                  v-close-popup
                  type="a"
                  @click="openmodalEditReport()"
                  target="_blank"
                >
                  <q-item-section avatar
                    ><q-icon color="primary" name="mdi-pencil"
                  /></q-item-section>
                  <q-item-section>แก้ไข มติ อ.ก.ก. </q-item-section>
                </q-item>
                <q-separator v-if="!checkRoutePermisson" />
                <q-item
                  clickable
                  v-close-popup
                  type="a"
                  @click="downloadAttachment('pdf', retireld)"
                  target="_blank"
                >
                  <q-item-section avatar
                    ><q-icon color="red" name="mdi-file-pdf"
                  /></q-item-section>
                  <q-item-section>ไฟล์ .pdf</q-item-section>
                </q-item>
                <q-item
                  clickable
                  v-close-popup
                  type="a"
                  @click="downloadAttachment('docx', retireld)"
                  target="_blank"
                >
                  <q-item-section avatar
                    ><q-icon color="blue" name="mdi-file-word"
                  /></q-item-section>
                  <q-item-section>ไฟล์ .docx</q-item-section>
                </q-item>
              </q-list>
            </q-menu>
            <q-tooltip>ดาวน์โหลดไฟล์</q-tooltip>
          </q-btn>
        </div>
        <q-space />
        <div class="row">
          <q-tabs shrink>
            <q-input
              borderless
              outlined
              dense
              v-model="filter"
              placeholder="ค้นหา"
              style="max-width: 200px"
              class="q-ml-sm"
              @keydown.enter="onSearch"
            >
              <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"
              class="gt-xs q-ml-sm"
            >
            </q-select>
          </q-tabs>
        </div>
      </div>

      <div>
        <d-table
          flat
          dense
          bordered
          :rows="rows"
          :columns="columns"
          row-key="order"
          :visible-columns="visibleColumns"
          no-data-label="ไม่มีข้อมูล"
          :pagination-label="paginationLabel"
          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">
                <div class="text-grey-7 text-weight-medium">
                  <span class="row">{{ col.title }}</span>
                  <span class="row" style="font-size: 12px">{{
                    col.subtitle
                  }}</span>
                </div>
              </q-th>
            </q-tr>
          </template>
          <template v-slot:body="props">
            <q-tr
              :props="props"
              :style="props.row.profileId === profileId && 'color: #26a69a;'"
            >
              <q-td auto-width>
                <q-btn
                  flat
                  round
                  dense
                  icon="mdi-eye"
                  color="info"
                  @click.stop="onclickViewinfo(props.row.profileId)"
                >
                  <q-tooltip>ดูข้อมูลในทะเบียนประวัติ</q-tooltip>
                </q-btn>
                <q-btn
                  v-if="
                    (props.row.remove === 'EDIT' ||
                      props.row.remove === 'REMOVE') &&
                    statusUpload
                  "
                  flat
                  round
                  :color="props.row.remove === 'EDIT' ? 'edit' : 'red-14'"
                  icon="info"
                  dense
                  @click.stop="
                    (modalNote = true),
                      (action = 'delete'),
                      (note = props.row.reason),
                      (retireProfileId = props.row.id)
                  "
                  ><q-tooltip>ดูเหตุผล</q-tooltip></q-btn
                >
                <q-btn
                  v-if="
                    (!checkRoutePermisson || props.row.remove === 'EDIT') &&
                    (typeReport === 'EDIT' ||
                      typeReport === null ||
                      typeReport === '') &&
                    !statusReport &&
                    !statusUpload
                  "
                  flat
                  round
                  color="edit"
                  :icon="props.row.remove === 'EDIT' ? 'info' : 'mdi-pencil'"
                  dense
                  @click.stop="
                    (modalNote = true),
                      (note = props.row.reason),
                      (action = 'edit'),
                      (retireProfileId = props.row.id)
                  "
                >
                  <q-tooltip>กรอกเหตุผล</q-tooltip>
                </q-btn>
                <q-btn
                  v-if="
                    (!checkRoutePermisson || props.row.remove === 'REMOVE') &&
                    (typeReport === 'REMOVE' ||
                      typeReport === null ||
                      typeReport === '') &&
                    !statusReport &&
                    statusUpload !== true
                  "
                  flat
                  round
                  color="red"
                  :icon="props.row.remove === 'REMOVE' ? 'info' : 'mdi-delete'"
                  dense
                  @click.stop="
                    (modalNote = true),
                      (action = 'delete'),
                      (note = props.row.reason),
                      (retireProfileId = 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 == 'organization'" class="text-html">
                  {{ props.row ? findOrgNameHtml(props.row) : "-" }}
                </div>
                <div v-else class="table_ellipsis">
                  {{ col.value ? col.value : "-" }}
                </div>
              </q-td>
              <!-- <q-td key="order" :props="props">{{ props.row.order }} </q-td>
              <q-td key="name" :props="props"
                >{{ props.row.prefix ? props.row.prefix : ""
                }}{{ props.row.firstName ? props.row.firstName : "" }}
                {{ props.row.lastName ? props.row.lastName : "" }}</q-td
              >

              <q-td key="position" :props="props">{{
                props.row.position ? props.row.position : "-"
              }}</q-td>
              <q-td key="positionType" :props="props"
                >{{ props.row.positionType ? props.row.positionType : "-" }}
                {{
                  props.row.positionLevel
                    ? " (" + props.row.positionLevel + ")"
                    : ""
                }}
              </q-td>

              <q-td key="positionNumber" :props="props">{{
                props.row.positionNumber ? props.row.positionNumber : "-"
              }}</q-td>

              <q-td class="table_ellipsis" key="organization" :props="props">{{
                props.row.organization ? props.row.organization : "-"
              }}</q-td> -->
            </q-tr>
          </template>
        </d-table>
      </div>
    </q-card>
  </div>

  <!-- note -->
  <q-dialog v-model="modalNote" persistent>
    <q-card style="width: 50vw">
      <DialogHeader
        :tittle="checkRoutePermisson ? 'เหตุผล' : 'กรอกเหตุผล'"
        :close="closeDialog"
      />
      <q-separator />
      <q-card-section>
        <div class="row q-col-gutter-sm">
          <div class="col-12">
            <q-input
              outlined
              dense
              lazy-rules
              hide-bottom-space
              v-model="note"
              :rules="[(val:string) => !!val || 'กรุณากรอกเหตุผล']"
              :label="`${'กรอกเหตุผล'}`"
              type="textarea"
              :readonly="statusUpload || checkRoutePermisson"
            />
          </div>
        </div>
      </q-card-section>

      <q-separator v-if="!checkRoutePermisson" />

      <q-card-actions
        align="right"
        v-if="!statusUpload && !checkRoutePermisson"
      >
        <q-btn
          v-if="action === 'delete'"
          unelevated
          label="บันทึก"
          color="secondary"
          :disable="visibleNote"
          @click="clickDelete"
        />
        <q-btn
          v-else
          unelevated
          label="บักทึก"
          color="secondary"
          @click="saveNote"
          :disable="visibleNote"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>

  <!-- อัปโหลดไฟล์ -->
  <q-dialog v-model="modalUpload" persistent>
    <q-card style="width: 50vw">
      <DialogHeader tittle="อัปโหลดเอกสาร" :close="closeDialog" />
      <q-separator />
      <q-card-section>
        <q-form ref="myForm">
          <div class="row q-gutter-md">
            <div class="col-12 q-pr-md">
              <q-file
                hide-bottom-space
                bg-color="white"
                clearable
                outlined
                dense
                v-model="fileUpload"
                accept=".pdf"
                label="อัปโหลดเอกสาร"
                :rules="[(val:string) => !!val || `${'กรุณาเลือกเอกสารอัปโหลด'}`]"
                lazy-rules
              >
                <template v-slot:prepend>
                  <q-icon color="light-blue" name="attach_file" />
                  <q-tooltip>อัปโหลดไฟล์</q-tooltip>
                </template>
              </q-file>
            </div>
            <div class="col-12 q-pr-md">
              <datepicker
                menu-class-name="modalfix"
                v-model="signDate"
                :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
                    dense
                    outlined
                    :rules="[(val:string) => !!val || `${'กรุณาเลือกวันที่'}`]"
                    :model-value="
                      signDate !== null ? date2Thai(signDate) : null
                    "
                    hide-bottom-space
                    :label="`${'ประกาศ ณ วันที่'}`"
                  >
                    <template v-slot:prepend>
                      <q-icon name="event" class="cursor-pointer text-primary">
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
          </div>
        </q-form>
      </q-card-section>

      <q-separator />

      <q-card-actions align="right">
        <q-btn
          unelevated
          label="บันทึก"
          color="public"
          @click="uploadFile(fileUpload, signDate)"
        >
          <q-tooltip>บันทึก</q-tooltip>
        </q-btn>
      </q-card-actions>
    </q-card>
  </q-dialog>

  <DialogPopupReason
    v-model:modal="modalEdit"
    title="แก้ไขมติ อ.ก.ก."
    label="มติ อ.ก.ก."
    :savaForm="saveEdiitReport"
    :textReport="textReport"
  />

  <AddList
    v-model:modal="modal"
    v-model:dataProfile="dataProfile"
    :retireld="retireld"
    :employeeType="employeeType == 'OFFICER' ? true : false"
    :profile-id="profileId"
    :UpdateListId="UpdateListId"
  />

  <PopupPersonal
    :modal="modalPersonal"
    :id="personId"
    @update:modal="updatemodalPersonal"
    v-model:is-employee="employeeType"
    :type="employeeType === 'OFFICER' ? 'officer' : 'employee'"
  />
</template>

<style lang="scss" scope>
.q-btn-dropdown__arrow {
  display: none;
}
</style>
