<script setup lang="ts">
import { ref, watch, reactive } from "vue";
import { useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useOrganizational } from "@/modules/02_organization/store/organizational";

/** importType*/
import type { QTableProps } from "quasar";
import type { NewPagination } from "@/modules/02_organization/interface/index/Main";
import type { DataTree } from "@/modules/02_organization/interface/index/organizational";
import type {
  OrgTree,
  PosMaster,
} from "@/modules/02_organization/interface/response/organizational";
import type {
  FilterMaster,
  Inherit,
} from "@/modules/02_organization/interface/request/organizational";

/** importComponents*/
import Header from "@/components/DialogHeader.vue";

/** use*/
const $q = useQuasar();
const store = useOrganizational();
const {
  showLoader,
  hideLoader,
  dialogConfirm,
  messageError,
  dialogMessageNotify,
  success,
} = useCounterMixin();

/** props*/
const modal = defineModel<boolean>("modal", { required: true });
const props = defineProps({
  rowId: { type: String, default: "" },
});

/*************************** Tree ***********************************/
const filterTree = ref<string>("");
const nodeTree = ref<OrgTree[]>([]);
const selectedTree = ref<string>("");
const filterRef = ref();
const levelTree = ref<number>(0);

/**
 * function เรียกข้อมูล Tree แบบ ปัจจุบัน
 */
async function fetchTree() {
  showLoader();
  const id: string = store.activeId ? store.activeId?.toString() : "";
  await http
    .get(config.API.orgByid(id))
    .then((res) => {
      nodeTree.value = res.data.result.data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * resetFilterTree
 */
function resetFilter() {
  filterTree.value = "";
  filterRef.value.focus();
}

/**
 * function เลือกหน่วยงาน
 *
 * และโหลดช้อมูลตำแหน่ง
 */
async function updateSelected(data: DataTree) {
  levelTree.value = data.orgLevel;
  selectedTree.value = data.orgTreeId;
  reqMaster.id = data.orgTreeId;
  reqMaster.type = data.orgLevel;
  await fetchTable();
}

/*************************** TABLE ***********************************/
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posMasterNo",
    align: "left",
    label: "ตำแหน่งเลขที่",
    sortable: true,
    field: "posMasterNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const rows = ref<PosMaster[]>([]); //รายการตำแหน่ง
const reqMaster = reactive<FilterMaster>({
  id: "",
  type: 0,
  isAll: false,
  page: 1,
  pageSize: 10,
  keyword: "",
  revisionId: store.activeId,
});
const totalRow = ref<number>(0);
const selectedPos = ref<PosMaster[]>([]);

/**
 * function เรียกข้อมูลรายการตำแหน่ง
 */
async function fetchTable() {
  selectedPos.value = [];
  await http
    .post(config.API.orgPosMasterList, reqMaster)
    .then((res) => {
      totalRow.value = Math.ceil(res.data.result.total / reqMaster.pageSize);
      const data = res.data.result.data;
      const list = data.map((e: PosMaster) => ({
        ...e,
        posMasterNo:
          (e.orgShortname !== null ? e.orgShortname : "") +
          (e.posMasterNoPrefix ? e.posMasterNoPrefix : "") +
          (e.posMasterNo !== null ? e.posMasterNo : "") +
          (e.posMasterNoSuffix !== null ? e.posMasterNoPrefix : ""),
      }));

      rows.value = list;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/**
 * function updatePagination
 * @param newPagination ข้อมูล Pagination ใหม่
 */
function updatePagination(newPagination: NewPagination) {
  reqMaster.pageSize = newPagination.rowsPerPage;
  reqMaster.page = 1;
}

/**
 * funcion ค้นหาข้อมูลใน Table
 */
async function filterKeyword() {
  reqMaster.page = 1;
  fetchTable();
}

/**
 * function ยืนยันกาสืบทอดตำแหน่ง
 */
function onClickConfirm() {
  if (selectedPos.value.length === 0) {
    dialogMessageNotify($q, "กรุณาเลือกตำแหน่งสืบทอด");
  } else {
    dialogConfirm(
      $q,
      async () => {
        const body: Inherit = {
          draftPositionId: props.rowId,
          publishPositionId: selectedPos.value[0].id,
        };
        showLoader();
        await http
          .post(config.API.orgPosDNA, body)
          .then(() => {
            success($q, "การสืบทอดตำแหน่งสำเร็จ");
            modal.value = false;
          })
          .catch((err) => {
            messageError($q, err);
          })
          .finally(() => {
            hideLoader();
          });
      },
      "ยืนยันการสืบทอดตำแหน่ง",
      "ต้องการยืนยันการสืบทอดตำแหน่งนี้หรือไม่ ?"
    );
  }
}

/**
 * function clear ข้อมูล
 */
function clearForm() {
  nodeTree.value = [];
  rows.value = [];
  selectedTree.value = "";
  reqMaster.id = "";
  reqMaster.type = 0;
  reqMaster.isAll = false;
  reqMaster.page = 1;
  reqMaster.pageSize = 10;
  reqMaster.keyword = "";
}

/**
 * callblck function ทำการ fetch ข้อมูล tree เมื่อเปิด popup*
 */
watch(
  () => modal.value,
  async () => {
    modal.value ? await fetchTree() : clearForm();
  }
);

/**
 * callblck function ทำการ fetch ข้อมูล Table เมื่อมีการเปลี่ยนหน้า
 */
watch([() => reqMaster.page, () => reqMaster.pageSize], async () => {
  await fetchTable();
});
</script>

<template>
  <q-dialog v-model="modal" full-width persistent>
    <q-card>
      <Header
        :tittle="'เลือกตำแหน่งที่ต้องการสืบทอดจากโครงสร้างปัจจุบัน'"
        :close="
          () => {
            modal = false;
          }
        "
      />
      <q-separator />

      <q-card-section class="q-pt-none q-pa-sm bg-grey-2">
        <div class="row">
          <q-card
            bordered
            class="col-12 col-sm-4 scroll q-pa-sm"
            style="height: 75vh"
          >
            <q-toolbar style="padding: 0">
              <q-toolbar-title class="text-subtitle2 text-bold"
                >เลือกหน่วยงาน/ส่วนราชการ</q-toolbar-title
              >
            </q-toolbar>

            <q-input
              ref="filterRef"
              dense
              outlined
              v-model="filterTree"
              label="ค้นหา"
            >
              <template v-slot:append>
                <q-icon
                  v-if="filterTree !== ''"
                  name="clear"
                  class="cursor-pointer"
                  @click="resetFilter"
                />
              </template>
            </q-input>
            <q-tree
              class="q-pa-md q-gutter-sm"
              dense
              default-expand-all
              selected-color="primary"
              :nodes="nodeTree"
              node-key="orgTreeId"
              label-key="labelName"
              :filter="filterTree"
              no-results-label="ไม่พบข้อมูลที่ค้นหา"
              no-nodes-label="ไม่มีข้อมูล"
            >
              <template v-slot:default-header="prop">
                <!--แสดงชื่อแผนก พิมพ์ตัวหนา คลิกแล้วกาง/หุบ Tree-->

                <q-item
                  clickable
                  :active="selectedTree == prop.node.orgTreeId"
                  @click.stop="updateSelected(prop.node)"
                  active-class="my-list-link text-primary text-weight-medium"
                  class="row col-12 items-center text-dark 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">
                      {{ prop.node.orgCode == null ? null : prop.node.orgCode }}
                      {{
                        prop.node.orgTreeShortName == null
                          ? null
                          : prop.node.orgTreeShortName
                      }}
                    </div>
                  </div>
                </q-item>
              </template>
            </q-tree>
          </q-card>

          <q-card bordered class="col-12 col-sm-8 q-pa-sm">
            <q-toolbar style="padding: 0">
              <q-toolbar-title class="text-subtitle2 text-bold"
                >เลือกตำแหน่งที่ต้องการสืบทอด</q-toolbar-title
              >
              <q-space />

              <div>
                <q-input
                  outlined
                  dense
                  v-model="reqMaster.keyword"
                  label="ค้นหา"
                  @keyup.enter="filterKeyword"
                />
              </div>
            </q-toolbar>
            <div class="col-12">
              <d-table
                flat
                bordered
                :rows="rows"
                :columns="columns"
                row-key="id"
                no-data-label="ไม่มีข้อมูล"
                ref="table"
                :paging="true"
                dense
                :rows-per-page-options="[10, 25, 50, 100]"
                @update:pagination="updatePagination"
                selection="single"
                v-model:selected="selectedPos"
              >
                <template v-slot:header-selection="scope">
                  <q-checkbox
                    keep-color
                    color="primary"
                    dense
                    v-model="scope.selected"
                  />
                </template>
                <template v-slot:header="props">
                  <q-tr :props="props">
                    <q-th auto-width></q-th>
                    <q-th
                      v-for="col in props.cols"
                      :key="col.name"
                      :props="props"
                    >
                      <span class="text-weight-medium">{{ col.label }}</span>
                    </q-th>
                  </q-tr>
                </template>
                <template v-slot:body="props">
                  <q-tr :props="props">
                    <q-td>
                      <q-checkbox
                        keep-color
                        color="primary"
                        dense
                        v-model="props.selected"
                      />
                    </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>
                        {{ col.value }}
                      </div>
                    </q-td>
                  </q-tr>
                </template>
                <template v-slot:pagination="scope">
                  <q-pagination
                    v-model="reqMaster.page"
                    active-color="primary"
                    color="dark"
                    :max="totalRow"
                    size="sm"
                    boundary-links
                    direction-links
                  ></q-pagination>
                </template>
              </d-table>
            </div>
          </q-card>
        </div>
      </q-card-section>

      <q-separator />

      <q-card-actions align="right">
        <q-btn label="สืบทอดตำแหน่ง" color="public" @click="onClickConfirm">
          <q-tooltip>สืบทอดตำแหน่ง</q-tooltip></q-btn
        >
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<style scoped>
.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>
