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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useChangeRoundDataStore } from "@/modules/09_leave/stores/ChangeRoundStore";
import { checkPermission } from "@/utils/permissions";
import { useStructureTree } from "@/stores/structureTree";
import { useRoute } from "vue-router";

import type { DataPost } from "@/modules/09_leave/interface/request/changeRound";

import Dialogform from "@/modules/09_leave/components/03_ChangeRound/DialogForm.vue";

/** useStore */
const route = useRoute();
const mixin = useCounterMixin();

const { showLoader, hideLoader, success, messageError, dialogConfirm } = mixin;
const dataStore = useChangeRoundDataStore();
const { fetchStructureTree } = useStructureTree();

/** use */
const $q = useQuasar();

const modal = ref<boolean>(false);
const dateWork = ref<string>("NORMAL");
const modalFix = ref<boolean>(false);
const editCheck = ref<string>("");
const DataRow = ref<any>();
const formData = reactive<DataPost>({
  cardId: "",
  firstName: "",
  lastName: "",
  page: 1,
  pageSize: 100,
  selectedNodeId: null,
  selectedNode: "",
});

const pagination = ref({
  page: 1,
  rowsPerPage: 0,
});

/** โครงสร้างข้อมูลต้นไม้ขององค์กร **/
const nodeTree = ref<any[]>([]);
const expanded = ref<string[]>([]);
const orgTreeId = ref<string | null>(null);
const filter = ref<string>("");
const selected = ref<any[]>([]);
const isMultiple = ref<boolean>(false);

/** client-side data & batch loading **/
const allRows = ref<any[]>([]);
const isLoadingAll = ref<boolean>(false);
const loadAllProgress = ref<number>(0);
const totalToLoad = ref<number | null>(null);
const BATCH_SIZE = 250;

function waitForUi() {
  return new Promise((resolve) => {
    setTimeout(resolve, 0);
  });
}

/** function fetch ข้อมูลของ Tree*/
async function fetchDataTree() {
  nodeTree.value = await fetchStructureTree(route.meta.Key as string, true);
}

/**
 * Function openPopup
 * @param check action edit,history
 * @param detail รายละเอียดข้อมูลรอบการปฏิบัติของผู้ใช้งาน
 */
async function Openmodal(check: string, detail: any) {
  DataRow.value = detail;
  modal.value = true;
  dataStore.setProfileId(DataRow.value.profileId);
  editCheck.value = check;
  if (check === "history") {
    modal.value = true;
    dataStore.changePage(1, dataStore.pageSize);
    // dataStore.fetchDatainHistory();
  }
}

/**
 * function เรียกข้อมูลปฏิทินวันทำงาน
 * @param id profileId
 */
async function fetchDataCalendarWork(id: string) {
  showLoader();
  await http
    .get(config.API.leaveWorkByid(id))
    .then((res) => {
      dateWork.value = res.data.result.work;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

const detailByid = ref();
async function OpenmodalFix(detail: any) {
  detailByid.value = detail;
  modalFix.value = true;
  await fetchDataCalendarWork(detail.profileId);
}

/** Function closePopup */
function closeDialog() {
  modal.value = false;
  modalFix.value = false;
  isMultiple.value = false;
}

function save() {
  dialogConfirm($q, async () => {
    showLoader();
    await http
      .put(config.API.leaveWorkByid(detailByid.value.profileId), {
        work: dateWork.value,
      })
      .then(async () => {
        // await searchData();
        success($q, "บันทึกข้อมูลสำเร็จ");
        closeDialog();
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/** Function โหลดข้อมูลทั้งหมดแบบ batch แล้วให้ QTable ทำ pagination เอง */
async function fetchAllData() {
  isLoadingAll.value = true;
  allRows.value = [];
  loadAllProgress.value = 0;
  totalToLoad.value = null;
  selected.value = [];

  // ให้ UI แสดงสถานะกำลังโหลดทันที ก่อนรอผล API แรก
  await nextTick();
  await waitForUi();

  try {
    await dataStore.fetchDataForCardId({
      ...formData,
      page: 1,
      pageSize: BATCH_SIZE,
    });
    allRows.value = dataStore.rows.slice();

    const total = dataStore.totalListMain;
    totalToLoad.value = total;
    const totalPages = Math.ceil(total / BATCH_SIZE);
    loadAllProgress.value =
      totalPages <= 1 ? 100 : Math.round(100 / totalPages);
    await nextTick();

    for (let page = 2; page <= totalPages; page++) {
      await dataStore.fetchDataForCardId({
        ...formData,
        page,
        pageSize: BATCH_SIZE,
      });
      allRows.value.push(...dataStore.rows);
      loadAllProgress.value = Math.round((page / totalPages) * 100);
      await nextTick();
      await waitForUi();
    }
  } finally {
    isLoadingAll.value = false;
    totalToLoad.value = null;
  }
}

/** Function ค้นหาข้อมูล */
async function searchData() {
  await fetchAllData();
}

function submitSearchByEnter() {
  if (isLoadingAll.value) return;
  if (!checkPermission(route)?.attrIsGet) return;
  formData.page = 1;
  searchData();
}

/** Function เลือกทั้งหมด */
function selectAllRows() {
  selected.value = [...allRows.value];
}

function onSelectedOrgTree(data: any) {
  if (isLoadingAll.value) return;
  selected.value = [];
  allRows.value = [];
  orgTreeId.value = data.orgTreeId;
  formData.selectedNodeId = data.orgTreeDnaId;
  formData.selectedNode = data.orgLevel;
  formData.page = 1;
}

function handleSelectMultiple() {
  modal.value = true;
  isMultiple.value = true;
  editCheck.value = "edit";
}

function resetSelected() {
  selected.value = [];
}

watch(
  () => formData.pageSize,
  () => {
    // pageSize ถูกควบคุมโดย QTable (client-side) ไม่ต้อง fetch API ใหม่
  }
);

onMounted(() => {
  fetchDataTree();
  dataStore.rows = [];
  allRows.value = [];
});
</script>
<template>
  <div class="toptitle text-dark col-12 row items-center">
    เปลี่ยนแปลงรอบการปฏิบัติงานของข้าราชการ
  </div>

  <q-card>
    <q-card-section :horizontal="$q.screen.gt.xs">
      <q-card-section class="col-lg-3 col-md-4 col-xs-12 q-gutter-sm">
        <div>
          <q-input dense outlined v-model="filter" label="ค้นหา">
            <template v-slot:append>
              <q-icon name="search" />
            </template>
          </q-input>
        </div>
        <div class="bg-white tree-container q-pa-xs">
          <q-tree
            class="q-pa-sm q-gutter-sm"
            dense
            :nodes="nodeTree"
            node-key="orgTreeId"
            label-key="labelName"
            :filter="filter.trim()"
            no-results-label="ไม่พบข้อมูลที่ค้นหา"
            no-nodes-label="ไม่มีข้อมูล"
            v-model:expanded="expanded"
          >
            <template v-slot:default-header="prop">
              <q-item
                clickable
                :active="orgTreeId == prop.node.orgTreeId"
                @click.stop="onSelectedOrgTree(prop.node)"
                active-class="my-list-link text-primary text-weight-medium"
                class="row col-12 text-dark items-center q-py-xs q-pl-sm rounded-borders my-list"
              >
                <div>
                  <div class="text-weight-medium">
                    {{ prop.node.orgTreeName }}
                  </div>
                  <div class="text-weight-light text-grey-8">
                    {{ prop.node.orgCode == null ? null : prop.node.orgCode }}
                    {{
                      prop.node.orgTreeShortName == null
                        ? null
                        : prop.node.orgTreeShortName
                    }}
                  </div>
                </div>
              </q-item>
            </template>
          </q-tree>
        </div>
      </q-card-section>
      <q-separator :vertical="$q.screen.gt.xs" />
      <q-card-section
        class="col-lg-9 col-md-8 col-xs-12 q-gutter-sm scroll"
        style="height: 80vh"
      >
        <div class="row col-xs-12 col-sm-9">
          <q-card flat bordered class="bg-grey-2 col-12 bg-white q-pa-lg">
            <div class="text-dark col-12 text-weight-bold text-subtitle1">
              ค้นหารายชื่อ
            </div>
            <div class="row justify-between q-gutter-y-sm">
              <q-input
                :readonly="!checkPermission($route)?.attrIsGet || isLoadingAll"
                v-model="formData.cardId"
                outlined
                label="เลขประจำตัวประชาชน"
                class="col-6 col-md-4 bg-white inputgreen"
                dense
                hide-bottom-space
                maxlength="13"
                @keyup.enter="submitSearchByEnter"
              />
              <q-input
                :readonly="!checkPermission($route)?.attrIsGet || isLoadingAll"
                v-model="formData.firstName"
                outlined
                label="ชื่อ"
                class="col-5 col-md-3 bg-white inputgreen"
                dense
                hide-bottom-space
                @keyup.enter="submitSearchByEnter"
              />
              <q-input
                :readonly="!checkPermission($route)?.attrIsGet || isLoadingAll"
                v-model="formData.lastName"
                outlined
                label="นามสกุล"
                class="col-6 col-md-3 bg-white inputgreen"
                dense
                hide-bottom-space
                @keyup.enter="submitSearchByEnter"
              />
              <q-btn
                v-if="checkPermission($route)?.attrIsGet"
                @click="(formData.page = 1), searchData()"
                :disable="isLoadingAll"
                for="#search"
                dense
                unelevated
                color="primary"
                class="q-px-sm col-5 col-md-1"
                style="max-height: 40px"
                >ค้นหา</q-btn
              >
            </div>
          </q-card>
        </div>
        <div
          v-if="
            allRows.length === 0 &&
            dataStore.checkCilck === true &&
            !isLoadingAll
          "
        >
          <q-card
            flat
            bordered
            class="bg-grey-2 col-12 q-pa-lg text-center text-subtitle1 text-bold"
            >ไม่พบข้อมูล</q-card
          >
        </div>
        <div v-if="allRows.length !== 0 || isLoadingAll" class="col-12">
          <q-banner
            v-if="isLoadingAll"
            rounded
            class="bg-blue-1 text-primary q-mb-sm"
          >
            <div class="row items-center q-gutter-sm">
              <q-spinner color="primary" size="22px" />
              <div v-if="totalToLoad === null || totalToLoad <= 500">
                กำลังค้นหาข้อมูล กรุณารอสักครู่
              </div>
              <div v-else>
                กำลังโหลดข้อมูลจำนวนมาก กรุณารอสักครู่
                <div class="text-caption text-grey-7">
                  ระบบกำลังดึงข้อมูลทั้งหมด
                  {{ totalToLoad.toLocaleString() }} รายการ
                </div>
              </div>
            </div>
          </q-banner>
          <q-linear-progress
            v-if="isLoadingAll && totalToLoad === null"
            indeterminate
            color="primary"
            class="q-mb-xs"
          />
          <q-linear-progress
            v-if="isLoadingAll && totalToLoad !== null"
            :value="loadAllProgress / 100"
            color="primary"
            class="q-mb-xs"
          />
          <div
            v-if="isLoadingAll && totalToLoad !== null"
            class="text-caption text-grey-6 q-mb-xs"
          >
            กำลังโหลด... {{ allRows.length.toLocaleString() }} /
            {{ totalToLoad.toLocaleString() }} รายการ
          </div>
          <div class="row justify-between items-center q-mb-sm">
            <div class="row q-gutter-sm">
              <!-- <q-btn
                color="secondary"
                dense
                icon="mdi-checkbox-multiple-marked-outline"
                label="เลือกทั้งหมด"
                :disable="isLoadingAll || allRows.length === 0"
                @click="selectAllRows()"
              /> -->
              <q-btn
                :disable="selected.length === 0 || isLoadingAll"
                :color="selected.length === 0 ? 'grey' : 'info'"
                dense
                icon="mdi-shuffle-variant"
                :label="`เปลี่ยนรอบการลงเวลา${
                  selected.length > 0 ? ` (${selected.length})` : ''
                }`"
                @click="handleSelectMultiple()"
              />
            </div>
          </div>

          <d-table
            ref="table"
            :columns="dataStore.columns"
            :rows="allRows"
            row-key="profileId"
            flat
            bordered
            dense
            virtual-scroll
            table-style="max-height: 58vh"
            class="custom-header-table"
            :visible-columns="dataStore.visibleColumns"
            hide-pagination
            v-model:pagination="pagination"
            selection="multiple"
            v-model:selected="selected"
          >
            <template v-slot:header="props">
              <q-tr :props="props">
                <q-th auto-width>
                  <q-checkbox
                    keep-color
                    color="primary"
                    dense
                    :disable="isLoadingAll"
                    v-model="props.selected"
                  />
                </q-th>
                <q-th auto-width />
                <q-th
                  v-for="col in props.cols"
                  :key="col.name"
                  :props="props"
                  style="color: #000000; font-weight: 500"
                >
                  <span class="text-weight-medium">{{ col.label }}</span>
                </q-th>
              </q-tr>
            </template>
            <template v-slot:body="props">
              <q-tr :props="props">
                <q-td class="text-center">
                  <q-checkbox
                    keep-color
                    color="primary"
                    dense
                    :disable="isLoadingAll"
                    v-model="props.selected"
                  />
                </q-td>
                <q-td>
                  <div>
                    <q-btn
                      flat
                      icon="mdi-dots-horizontal-circle-outline"
                      color="secondary"
                      for="#cancel"
                      dense
                      round
                    >
                      <q-menu>
                        <q-list>
                          <q-item
                            v-if="checkPermission($route)?.attrIsUpdate"
                            clickable
                            v-close-popup
                            @click="Openmodal('edit', props.row)"
                          >
                            <q-item-section style="min-width: 0px" avatar>
                              <q-icon
                                color="primary"
                                name="mdi-shuffle-variant"
                                size="xs"
                              />
                            </q-item-section>

                            <q-item-section>
                              <q-item-label>เปลี่ยนรอบการลงเวลา</q-item-label>
                            </q-item-section>
                          </q-item>
                          <q-item
                            v-if="checkPermission($route)?.attrIsUpdate"
                            clickable
                            v-close-popup
                            @click="OpenmodalFix(props.row)"
                          >
                            <q-item-section style="min-width: 0px" avatar>
                              <q-icon color="edit" name="edit" size="xs" />
                            </q-item-section>

                            <q-item-section>
                              <q-item-label>แก้ไขปฏิทินวันทำงาน</q-item-label>
                            </q-item-section>
                          </q-item>
                          <q-item
                            clickable
                            v-close-popup
                            @click="Openmodal('history', props.row)"
                          >
                            <q-item-section style="min-width: 0px" avatar>
                              <q-icon
                                color="deep-purple"
                                name="mdi-history"
                                size="xs"
                              />
                            </q-item-section>
                            <q-item-section>
                              <q-item-label>ประวัติการเปลี่ยนรอบ</q-item-label>
                            </q-item-section>
                          </q-item>
                        </q-list>
                      </q-menu>
                    </q-btn>
                  </div>
                </q-td>
                <q-td v-for="col in props.cols" :key="col.name" :props="props">
                  <div>
                    {{ col.value ?? "-" }}
                  </div>
                </q-td>
              </q-tr>
            </template>
          </d-table>
          <div class="text-caption text-grey-7 q-mt-sm">
            ทั้งหมด {{ allRows.length }} รายการ
          </div>
        </div>
      </q-card-section>
    </q-card-section>
  </q-card>

  <!-- popup เปลี่ยนรอบการปฏิบัติงาน ,ประวัติการเปลี่ยนรอบการปฏิบัติงาน  -->
  <Dialogform
    :modal="modal"
    :closeDialog="closeDialog"
    :editCheck="editCheck"
    :DataRow="DataRow"
    :personId="DataRow == null ? '' : DataRow.profileId"
    @update:change-page="dataStore.changePage"
    v-model:isMultiple="isMultiple"
    :selectedMultiple="selected"
    @update:selected="resetSelected"
  />

  <!-- แก้ไขปฏิทินวันทำงาน -->
  <q-dialog v-model="modalFix" persistent>
    <q-card style="min-width: 800px"
      ><q-toolbar>
        <q-toolbar-title class="text-subtitle1 text-bold">
          {{ "แก้ไขปฏิทินวันทำงาน" }}
        </q-toolbar-title>
        <q-btn
          icon="close"
          unelevated
          round
          dense
          @click="closeDialog"
          style="color: #ff8080; background-color: #ffdede"
        />
      </q-toolbar>
      <q-separator color="grey-4" />
      <q-form @submit="save" class="q-gutter-md">
        <div class="q-pa-md">
          <q-radio
            name="dateWork"
            v-model="dateWork"
            val="NORMAL"
            label="ทำงาน 5 วัน"
          />
          <q-radio
            name="dateWork"
            v-model="dateWork"
            val="6DAY"
            label="ทำงาน 6 วัน"
          />
        </div>
        <q-separator color="grey-4" />
        <div class="q-pa-xs">
          <div class="row justify-end q-mr-sm q-py-sm">
            <q-btn
              id="onSubmit"
              type="submit"
              unelevated
              label="บันทึก"
              class="q-px-md items-center"
              color="secondary"
            />
          </div>
        </div>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style scoped lang="scss">
.q-table tbody td:before.no-background {
  background: none;
}

.tree-container {
  overflow: auto;
  height: 75vh;
  border: 1px solid #e6e6e7;
  border-radius: 10px;
}

.my-list-link {
  color: rgb(118, 168, 222);
  border-radius: 5px;
  background: #a3d3fb48 !important;
  font-weight: 600;
  border: 1px solid rgba(175, 185, 196, 0.217);
}
</style>
