<!-- page:จัดการรอบการสอบ สรรหา -->
<script setup lang="ts">
import type { QTableProps } from "quasar";
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { useQuasar } from "quasar";
import genReport from "@/plugins/genreport";

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { checkPermission } from "@/utils/permissions";

import type {
  ResponseRecruitPeriod,
  ResponseHistoryObject,
} from "@/modules/03_recruiting/interface/response/Period";
import type { Pagination } from "@/modules/03_recruiting/interface/index/Main";

import Table from "@/modules/03_recruiting/components/Table.vue";
import DialogHeader from "@/components/DialogHeader.vue";
import HistoryTable from "@/components/TableHistory.vue";

const $q = useQuasar(); // show dialog
const router = useRouter();
const mixin = useCounterMixin();
const {
  success,
  dateText,
  messageError,
  showLoader,
  hideLoader,
  date2Thai,
  onSearchDataTable,
  dialogRemove,
} = mixin;

const name = ref<string>("");
const year = ref<number>(new Date().getFullYear() + 543);
const round = ref<number>(1);
const files = ref<any>(null);
const files_score = ref<any>(null);
const files_candidate = ref<any>(null);
const modalAdd = ref<boolean>(false);
const modalScore = ref<boolean>(false);
const modalCandidate = ref<boolean>(false);
const selected_row_id = ref<string>("");
const rowsHistory = ref<ResponseHistoryObject[]>([]); //select data history
const tittleHistory = ref<string>("ประวัติการนำเข้าข้อมูล"); //
const modalHistory = ref<boolean>(false); //modal ประวัติการแก้ไขข้อมูล
const rows = ref<any[]>([]);
const rowsData = ref<any[]>([]);
const filter = ref<string>(""); //search data table
const filterHistory = ref<string>(""); //search data table
const textTittle = ref<string>("");
const textTittleScore = ref<string>("");
const textTittleCandidate = ref<string>("");
const initialPagination = ref<Pagination>({
  rowsPerPage: 0,
  sortBy: "year",
});
const visibleColumns = ref<String[]>([
  "no",
  "name",
  "round",
  "year",
  "examCount",
  "scoreCount",
]);

const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    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",
  },
  {
    name: "round",
    align: "left",
    label: "ครั้งที่",
    sortable: true,
    field: "round",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "year",
    align: "left",
    label: "ปีงบประมาณ",
    sortable: true,
    field: "year",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return `${row.year + 543}`;
    },
    sort: (a: number, b: number) => b - a,
  },
  {
    name: "examCount",
    label: "จำนวนผู้สอบทั้งหมด",
    align: "right",
    field: "examCount",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "scoreCount",
    label: "จำนวนที่บันทึกผลสอบ",
    align: "right",
    field: "scoreCount",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

const columnsHistory = ref<QTableProps["columns"]>([
  {
    name: "description",
    align: "left",
    label: "รายละเอียด",
    sortable: true,
    field: "description",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "createdAt",
    align: "left",
    label: "วันที่ดำเนินการ",
    sortable: true,
    field: "createdAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return `${date2Thai(row.createdAt)}`;
    },
  },
  {
    name: "createdFullName",
    align: "left",
    label: "ผู้ดำเนินการ",
    sortable: true,
    field: "createdFullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

const visibleColumnsHistory = ref<String[]>([
  "description",
  "createdAt",
  "createdFullName",
]);

/**  ดาวน์โหลดรายชื่อผู้สอบคัดเลือกคนพิการได้ */
async function clickPassExam(id: string) {
  showLoader();
  await http
    .get(config.API.exportDisablePassExamList(id))
    .then(async (res) => {
      const data = res.data.result;
      data.reportName = `CandidateList`;
      await genReport(data, data.reportName, "pdf");
    })
    .catch(async (e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/** ดาวน์โหลดรายชื่อผู้มีสิทธิ์สอบ */
async function clickCandidateList(id: string) {
  showLoader();
  await http
    .get(config.API.exportDisableCandidateList(id))
    .then(async (res) => {
      const data = res.data.result;
      data.reportName = `CandidateList`;
      await genReport(data, data.reportName, "pdf");
    })
    .catch(async (e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ฟังก์ชันแปลง date เป็นภาษาไทย
 * @param value วันที่ type datetime ที่จะแปลงเป็นไทย
 */
function textDate(value: Date) {
  return dateText(value);
}

/** ดึง list ข้อมูล */
async function fetchData(actionType?: string) {
  showLoader();
  await http
    .get(config.API.getDisableCandidates)
    .then((res) => {
      const data = res.data.result;
      let result: ResponseRecruitPeriod[] = [];
      if (data.length > 0) {
        data.map((r: ResponseRecruitPeriod) => {
          if (r.score != null) {
            r.scoreCount = r.score.scoreCount;
            r.scoreImportDate = r.score.importDate;
          }
          result.push(r);
        });
      }

      rows.value = result;
      rowsData.value = result;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
      if (actionType == "delete") {
        success($q, "ลบข้อมูลสำเร็จ");
      }
    });
}

/**
 * ไปหน้ารายละเอียด
 * @param id รอบการคัดเลือก
 */
function clickDetail(id: string) {
  router.push(`/disable/import/${id}`);
}

/** นำเข้าไฟล์ผลคะแนนสอบ */
async function clickEdit(id: string) {
  modalScore.value = true;
  textTittleScore.value = "นำเข้าผลการคัดเลือกคนพิการ";
  selected_row_id.value = id;
}

/** นำเข้าไฟล์ผู้สมัครสอบ */
async function clickUpload(id: string) {
  modalCandidate.value = true;
  textTittleCandidate.value = "นำเข้าผู้สมัครคัดเลือกคนพิการ";
  selected_row_id.value = id;
}

/** ไปหน้าแก้ไข */
function clickEditPeriod(id: string) {
  router.push(`/disable/period/${id}`);
}

/** เปิด ประวัติ */
async function clickHistory(id: string) {
  modalHistory.value = true;
  showLoader();
  await http
    .get(config.API.getDisableImportHistory(id))
    .then((res) => {
      const data = res.data.result;
      rowsHistory.value = [];
      if (data.length > 0) {
        data.map((i: ResponseHistoryObject) => {
          rowsHistory.value.push({
            createdAt: i.createdAt,
            createdFullName: i.createdFullName,
            createdUserId: i.createdUserId,
            id: i.id,
            isActive: i.isActive,
            lastUpdateFullName: i.lastUpdateFullName,
            lastUpdateUserId: i.lastUpdateUserId,
            lastUpdatedAt: i.lastUpdatedAt,
            description: i.description,
          });
        });
      }
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
    });
}

/** ลบ รอบการคัดเลือก */
function clickDelete(id: string) {
  dialogRemove($q, async () => {
    showLoader();
    await http
      .delete(config.API.deleteDisableCandidates(id))
      .then((res) => {
        fetchData("delete");
      })
      .catch((e) => {
        messageError($q, e);
        hideLoader();
      })
      .finally(() => {});
  });
}

/** ไปหน้าเพิ่มข้อมูล */
function clickAdd() {
  router.push({ name: "disablePeriodAdd" });
}

/** ปิด dialog */
async function clickClose() {
  modalAdd.value = false;
  await fetchData();
}

/** ปิด dialog คะเเนน */
async function clickCloseScore() {
  modalScore.value = false;
  await fetchData();
}

/** ปิด dialog เลือกไฟล์ผู้สมัครคัดเลือกคนพิการ */
async function clickCloseCandidate() {
  modalCandidate.value = false;
  await fetchData();
}

/** บันทึก รอบการคัดเลือก */
async function checkSaveCandidate() {
  const fd = new FormData();
  fd.append("attachment", files_candidate.value[0]);
  showLoader();
  await http
    .post(config.API.uploadDisableCandidates(selected_row_id.value), fd)
    .then((res) => {
      success($q, "นำเข้าข้อมูลผู้สมัครสอบสำเร็จ");
      modalCandidate.value = false;
      selected_row_id.value = "";
      fetchData();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**  บันทึก คะเเนน*/
async function checkSaveScore() {
  const fd = new FormData();
  fd.append("attachment", files_score.value[0]);
  showLoader();
  await http
    .post(config.API.saveDisableScores(selected_row_id.value), fd)
    .then((res) => {
      success($q, "นำเข้าข้อมูลผลคะแนนสอบสำเร็จ");
      modalScore.value = false;
      selected_row_id.value = "";
      fetchData();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/** บันทึกข้อมูล */
async function checkSave() {
  const fd = new FormData();
  fd.append("attachment", files.value[0]);
  fd.append("year", year.value.toString());
  fd.append("round", round.value.toString());
  fd.append("name", name.value);
  showLoader();
  await http
    .post(config.API.saveDisableCandidates, fd)
    .then((res) => {
      success($q, "นำเข้าข้อมูลผู้สมัครคัดเลือกคนพิการสำเร็จ");
      modalAdd.value = false;
      fetchData();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

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

onMounted(async () => {
  hideLoader();
  await fetchData();
});
</script>
<template>
  <div class="toptitle text-dark col-12 row items-center">
    จัดการรอบคัดเลือกคนพิการ
  </div>
  <q-card flat bordered class="col-12 q-mt-sm q-pt-sm q-pa-md">
    <div>
      <Table
        style="max-height: 80vh"
        :rows="rows"
        :columns="columns"
        v-model:filter="filter"
        :onSearch="onSearch"
        :visible-columns="visibleColumns"
        v-model:inputfilter="filter"
        v-model:inputvisible="visibleColumns"
        v-model:pagination="initialPagination"
        :nornmalData="true"
        :add="clickAdd"
        :paging="true"
        :titleText="''"
      >
        <template #columns="props">
          <q-tr :props="props">
            <q-td>
              <q-btn
                icon="mdi-dots-horizontal-circle-outline"
                color="secondary"
                flat
                round
                dense
                v-if="
                  checkPermission($route)?.attrIsCreate ||
                  checkPermission($route)?.attrIsDelete ||
                  checkPermission($route)?.attrIsGet ||
                  checkPermission($route)?.attrIsUpdate
                "
              >
                <q-menu transition-show="jump-down" transition-hide="jump-up">
                  <q-list dense style="min-width: 100px">
                    <q-item
                      v-if="checkPermission($route)?.attrIsGet"
                      clickable
                      v-close-popup
                      @click="clickDetail(props.row.id)"
                    >
                      <q-item-section style="min-width: 0px" avatar>
                        <q-icon color="info" size="xs" name="mdi-eye" />
                      </q-item-section>
                      <q-item-section>รายละเอียด</q-item-section>
                    </q-item>

                    <q-item
                      v-if="
                        checkPermission($route)?.attrIsUpdate &&
                        checkPermission($route)?.attrIsGet
                      "
                      clickable
                      v-close-popup
                      @click="clickEditPeriod(props.row.id)"
                    >
                      <q-item-section style="min-width: 0px" avatar>
                        <q-icon color="edit" size="xs" name="mdi-pencil" />
                      </q-item-section>
                      <q-item-section>แก้ไขข้อมูล</q-item-section>
                    </q-item>

                    <q-item
                      v-if="checkPermission($route)?.attrIsDelete"
                      clickable
                      v-close-popup
                      @click="clickDelete(props.row.id)"
                    >
                      <q-item-section style="min-width: 0px" avatar>
                        <q-icon color="red" size="xs" name="mdi-delete" />
                      </q-item-section>
                      <q-item-section>ลบข้อมูล</q-item-section>
                    </q-item>
                    <q-item
                      v-if="checkPermission($route)?.attrIsGet"
                      clickable
                      v-close-popup
                      @click="clickHistory(props.row.id)"
                    >
                      <q-item-section style="min-width: 0px" avatar>
                        <q-icon
                          color="deep-purple"
                          size="xs"
                          name="mdi-history"
                        />
                      </q-item-section>
                      <q-item-section>แสดงประวัติการทำงาน</q-item-section>
                    </q-item>
                  </q-list>
                </q-menu>
              </q-btn>
            </q-td>
            <q-td v-for="col in props.cols" :key="col.name" :props="props">
              <div v-if="col.name == 'no'">
                {{ props.rowIndex + 1 }}
              </div>
              <div v-else-if="col.name == 'name'" class="table_ellipsis2">
                {{ col.value }}
              </div>
              <div v-else-if="col.name == 'scoreCount'" class="table_ellipsis2">
                <q-btn
                  flat
                  dense
                  size="12px"
                  round
                  color="green"
                  @click.stop.prevent="clickEdit(props.row.id)"
                  v-if="
                    col.value == null && checkPermission($route)?.attrIsUpdate
                  "
                >
                  <q-icon name="mdi-file-excel-outline" size="20px" />
                  <!-- นำเข้าไฟล์ผลคะแนนสอบ -->
                  <q-tooltip>นำเข้าไฟล์ผลคะแนนสอบ</q-tooltip>
                </q-btn>
                <div v-else>
                  {{ col.value }}
                  <q-btn
                    v-if="checkPermission($route)?.attrIsUpdate"
                    dense
                    size="12px"
                    flat
                    round
                    color="green"
                    @click.stop.prevent="clickEdit(props.row.id)"
                    icon="mdi-file-excel-outline"
                  >
                    <q-tooltip>นำเข้าไฟล์ผลคะแนนสอบอีกครั้ง</q-tooltip>
                  </q-btn>

                  <q-btn
                    v-if="checkPermission($route)?.attrIsGet"
                    dense
                    size="12px"
                    flat
                    round
                    color="indigo"
                    @click.stop.prevent="clickPassExam(props.row.id)"
                    icon="mdi-clipboard-arrow-down"
                  >
                    <q-tooltip
                      >ดาวน์โหลดรายชื่อผู้สอบคัดเลือกคนพิการได้</q-tooltip
                    >
                  </q-btn>
                </div>
              </div>
              <div v-else-if="col.name == 'examCount'" class="table_ellipsis2">
                <q-btn
                  flat
                  dense
                  size="12px"
                  color="green"
                  round
                  @click.stop.prevent="clickUpload(props.row.id)"
                  v-if="
                    (col.value == null || col.value == '0') &&
                    checkPermission($route)?.attrIsUpdate
                  "
                >
                  <q-icon name="mdi-file-excel-outline" size="20px" />
                  <q-tooltip>นำเข้าไฟล์ผู้สมัครสอบ</q-tooltip>
                </q-btn>
                <div v-else>
                  {{ col.value }}

                  <q-btn
                    v-if="checkPermission($route)?.attrIsUpdate"
                    dense
                    size="12px"
                    flat
                    round
                    color="green"
                    @click.stop.prevent="clickUpload(props.row.id)"
                    icon="mdi-file-excel-outline"
                  >
                    <q-tooltip>นำเข้าไฟล์ผู้สมัครสอบอีกครั้ง</q-tooltip>
                  </q-btn>

                  <q-btn
                    v-if="checkPermission($route)?.attrIsGet"
                    dense
                    size="12px"
                    flat
                    round
                    color="indigo"
                    @click.stop.prevent="clickCandidateList(props.row.id)"
                    icon="mdi-clipboard-arrow-down"
                  >
                    <q-tooltip>ดาวน์โหลดรายชื่อผู้มีสิทธิ์สอบ</q-tooltip>
                  </q-btn>
                </div>
              </div>
              <div v-else>
                {{ col.value }}
              </div>
            </q-td>
          </q-tr>
        </template>
      </Table>
    </div>
  </q-card>

  <HistoryTable
    :rows="rowsHistory"
    :columns="columnsHistory"
    :visible-columns="visibleColumnsHistory"
    v-model:modal="modalHistory"
    v-model:inputvisible="visibleColumnsHistory"
    v-model:tittle="tittleHistory"
    v-model:inputfilter="filterHistory"
    :filter="filterHistory"
  >
    <template #columns="props">
      <q-tr :props="props">
        <q-td v-for="col in props.cols" :key="col.name" :props="props">
          <div v-if="col.name == 'isActive'" class="">
            <q-icon
              v-if="col.value == false"
              name="mdi-close"
              color="red"
              class="text-h5"
            />
            <q-icon v-else name="mdi-check" color="positive" class="text-h5" />
          </div>

          <div v-else class="">
            {{ col.value }}
          </div>
        </q-td>
      </q-tr>
    </template>
  </HistoryTable>

  <!-- popup Edit window-->
  <q-dialog v-model="modalAdd" persistent>
    <q-card style="width: 600px">
      <q-form ref="myForm">
        <DialogHeader :tittle="textTittle" :close="clickClose" />
        <q-separator />
        <q-card-section>
          <div class="col-12 row items-center q-col-gutter-sm">
            <div class="col-12">
              <q-input
                outlined
                v-model="name"
                label="ชื่อการคัดเลือกคนพิการ"
                dense
                autogrow
                lazy-rules
                autofocus
                hide-bottom-space
              ></q-input>
            </div>
            <div class="col-12">
              <q-input
                outlined
                v-model="round"
                label="ครั้งที่"
                dense
                autogrow
                lazy-rules
                autofocus
                hide-bottom-space
              ></q-input>
            </div>
            <div class="col-12">
              <q-input
                outlined
                v-model="year"
                label="ปีงบประมาณ"
                dense
                autogrow
                lazy-rules
                autofocus
                hide-bottom-space
              ></q-input>
            </div>
            <div class="col-12">
              <q-file
                v-model="files"
                dense
                label="เลือกไฟล์รายชื่อผู้สมัครคัดเลือกคนพิการ"
                outlined
                use-chips
                multiple
              >
                <template v-slot:prepend>
                  <q-icon name="attach_file" />
                </template>
              </q-file>
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions class="text-primary q-py-sm">
          <q-space />
          <q-btn
            flat
            round
            color="public"
            @click="checkSave"
            icon="mdi-content-save-outline"
          >
            <q-tooltip>บันทึก</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>

  <q-dialog v-model="modalScore" persistent>
    <q-card style="width: 600px">
      <q-form ref="myFormScore">
        <DialogHeader :tittle="textTittleScore" :close="clickCloseScore" />
        <q-separator />
        <q-card-section>
          <div class="col-12 row items-center q-col-gutter-sm">
            <div class="col-12">
              <q-file
                v-model="files_score"
                dense
                label="เลือกไฟล์ผลการคัดเลือกคนพิการ"
                outlined
                use-chips
                multiple
              >
                <template v-slot:prepend>
                  <q-icon name="attach_file" />
                </template>
              </q-file>
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions class="text-primary q-py-sm">
          <q-space />
          <q-btn
            flat
            round
            color="public"
            @click="checkSaveScore"
            icon="mdi-content-save-outline"
          >
            <q-tooltip>บันทึก</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>

  <q-dialog v-model="modalCandidate" persistent>
    <q-card style="width: 600px">
      <q-form ref="myFormScore">
        <DialogHeader
          :tittle="textTittleCandidate"
          :close="clickCloseCandidate"
        />
        <q-separator />
        <q-card-section>
          <div class="col-12 row items-center q-col-gutter-sm">
            <div class="col-12">
              <q-file
                v-model="files_candidate"
                dense
                label="เลือกไฟล์ผู้สมัครคัดเลือกคนพิการ"
                outlined
                use-chips
                multiple
              >
                <template v-slot:prepend>
                  <q-icon name="attach_file" />
                </template>
              </q-file>
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions class="text-primary q-py-sm">
          <q-space />
          <q-btn
            flat
            round
            color="public"
            @click="checkSaveCandidate"
            icon="mdi-content-save-outline"
          >
            <q-tooltip>บันทึก</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style></style>
