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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useDataStoreUser } from "@/modules/02_users/stores/main";

import type { QTableProps } from "quasar";
import type {
  DataTree,
  DataProfile,
  Pagination,
} from "@/modules/02_users/interface/index/Main";
import type { QueryProfile } from "@/modules/02_users/interface/request/Main";

import DialogAddPerson from "@/modules/02_users/components/RoleOrganization/DialogAddPerson.vue";

const $q = useQuasar();
const store = useDataStoreUser();
const { showLoader, hideLoader, messageError, success, dialogRemove } =
  useCounterMixin();

/******* โครงสร้าง *******/
const filter = ref<string>(""); // ค้นหาข้อมูลรายการโครงสร้าง
const nodeTree = ref<DataTree[]>([]); // ข้อมูลรายการโครงสร้าง
const expanded = ref<Array<string>>([]); // เปิดรายการโครงสร้าง
const orgId = ref<string>(""); // id หน่วยงานที่เลือก

async function fatchOrgg() {
  showLoader();
  await http
    .get(config.API.permissionOrg)
    .then(async (res) => {
      const data = await res.data.result;
      nodeTree.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function selectedOrg(id: string) {
  orgId.value = id;
  qureyBody.id = id;
  fetchListPerson(true);
}

/******* รายชื่อคนที่มีสิทธิ์จัดการโครงสร้าง *******/
const qureyBody = reactive<QueryProfile>({
  searchKeyword: "",
  searchField: "fullName",
  page: 1,
  pageSize: 10,
  id: null,
});
const rows = ref<DataProfile[]>([]);
const total = ref<number>(0);
const maxPage = ref<number>(0);
const columns = ref<QTableProps["columns"]>([
  {
    name: "fullName",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: true,
    field: (row) => `${row.prefix}${row.firstName}  ${row.lastName}`,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "org",
    align: "left",
    label: "หน่วยงาน",
    sortable: true,
    field: "org",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posNo",
    align: "left",
    label: "เลขที่ตำแห่นง",
    sortable: true,
    field: "posNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "position",
    align: "left",
    label: "ตำแหน่งในสายงาน",
    sortable: true,
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },

  {
    name: "posType",
    align: "left",
    label: "ประเภทตำแหน่ง",
    sortable: true,
    field: (row) =>
      `${row.posType ? row.posType : "-"}  ${
        row.posLevel ? `(${row.posLevel})` : ``
      } `,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

const modalAdd = ref<boolean>(false);

async function fetchListPerson(newPage: boolean = false) {
  qureyBody.page = newPage ? 1 : qureyBody.page;
  showLoader();
  await http
    .post(config.API.permissionOrgProfile, qureyBody)
    .then(async (res) => {
      const data = await res.data.result;
      maxPage.value = Math.ceil(data.total / qureyBody.pageSize);
      total.value = data.total;
      rows.value = data.data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function onDeletePerson(id: string) {
  dialogRemove($q, async () => {
    showLoader();
    await http
      .delete(config.API.permissionOrg + `/${id}`)
      .then(async () => {
        if (maxPage.value !== 1) {
          if (rows.value.length === 1) {
            qureyBody.page = qureyBody.page - 1;
          }
          await fetchListPerson(false);
        } else {
          await fetchListPerson(true);
        }
        success($q, "ลบข้อมูสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

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

watch(
  () => qureyBody.pageSize,
  () => {
    fetchListPerson(true);
  }
);

/**
 * hook ทำงานเมื่อ Components ถูกเรียกใช้งาน
 *
 */
onMounted(async () => {
  await Promise.all([
    fatchOrgg(), // ดึงข้อมูลโครงสร้าง
    fetchListPerson(),
  ]);
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    กำหนดสิทธิ์จัดการโครงสร้าง
  </div>
  <q-card style="height: 100%">
    <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
                v-if="filter !== ''"
                name="clear"
                class="cursor-pointer"
                @click="filter = ''"
              />
              <q-icon name="search" color="grey-5" />
            </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"
            no-results-label="ไม่พบข้อมูลที่ค้นหา"
            no-nodes-label="ไม่มีข้อมูล"
            v-model:expanded="expanded"
          >
            <template v-slot:default-header="prop">
              <q-item
                clickable
                class="row col-12 items-center text-dark q-py-xs q-pl-sm rounded-borders my-list"
                :active="orgId == prop.node.id"
                active-class="my-list-link text-primary text-weight-medium"
                @click.stop="selectedOrg(prop.node.id)"
              >
                <div>
                  <div class="text-weight-medium">
                    {{ prop.node.orgRootName }}
                  </div>
                  <div class="text-weight-light text-grey-8">
                    {{
                      prop.node.orgRootCode == null
                        ? null
                        : prop.node.orgRootCode
                    }}
                    {{
                      prop.node.orgRootShortName == null
                        ? null
                        : prop.node.orgRootShortName
                    }}
                  </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 scroll"
        style="height: 83vh"
      >
        <q-card bordered style="height: 100%; border: 1px solid #d6dee1">
          <div class="col-12 text-weight-medium bg-grey-1 q-py-sm q-px-md">
            รายชื่อคนที่มีสิทธิ์จัดการโครงสร้าง
          </div>
          <div class="col-12"><q-separator /></div>
          <q-card-section>
            <div class="row col-12 q-col-md">
              <div class="col-2">
                <q-btn
                  v-if="orgId"
                  flat
                  dense
                  color="primary"
                  icon="add"
                  round
                  @click="modalAdd = true"
                >
                  <q-tooltip>เพิ่มข้อมูล</q-tooltip>
                </q-btn>
              </div>

              <div class="col-md-10">
                <div class="row col-12 q-col-gutter-sm">
                  <div class="col-md-4">
                    <q-select
                      outlined
                      dense
                      v-model="qureyBody.searchField"
                      :options="store.searchFieldOption"
                      label="เลือกที่ต้องการค้นหา"
                      emit-value
                      map-options
                      option-label="name"
                      option-value="id"
                    />
                  </div>
                  <div class="col-md-6">
                    <q-input
                      v-model="qureyBody.searchKeyword"
                      outlined
                      dense
                      lazy-rules
                      label="คำค้น"
                      hide-bottom-space
                    >
                      <template v-slot:append>
                        <q-icon
                          v-if="qureyBody.searchKeyword"
                          name="cancel"
                          @click="qureyBody.searchKeyword = ''"
                          class="cursor-pointer"
                        ></q-icon>
                      </template>
                    </q-input>
                  </div>
                  <div class="row col-md-2">
                    <q-btn
                      color="primary"
                      icon="search"
                      label="ค้นหา"
                      class="full-width"
                      @click="fetchListPerson(true)"
                    />
                  </div>
                </div>
              </div>
            </div>

            <div class="col-12 q-mt-sm">
              <d-table
                :columns="columns"
                :rows="rows"
                :paging="true"
                row-key="id"
                flat
                bordered
                dense
                :rows-per-page-options="[2, 10, 25, 50, 100]"
                @update:pagination="updatePagination"
              >
                <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-tr>
                </template>
                <template v-slot:body="props">
                  <q-tr :props="props">
                    <q-td auto-width>
                      <q-btn
                        flat
                        dense
                        color="red"
                        icon="delete"
                        round
                        @click.pervent="onDeletePerson(props.row.id)"
                      >
                        <q-tooltip>ลบข้อมูล</q-tooltip>
                      </q-btn>
                    </q-td>
                    <q-td
                      v-for="col in props.cols"
                      :key="col.name"
                      :props="props"
                    >
                      <div>
                        {{ col.value ? col.value : "-" }}
                      </div>
                    </q-td>
                  </q-tr>
                </template>
                <template v-slot:pagination="scope">
                  ทั้งหมด {{ total }} รายการ
                  <q-pagination
                    v-model="qureyBody.page"
                    active-color="primary"
                    color="dark"
                    :max="maxPage"
                    :max-pages="5"
                    size="sm"
                    boundary-links
                    direction-links
                    @update:model-value="fetchListPerson(false)"
                  >
                  </q-pagination>
                </template>
              </d-table>
            </div>
          </q-card-section>
        </q-card>
      </q-card-section>
    </q-card-section>
  </q-card>

  <DialogAddPerson
    v-model:modal="modalAdd"
    v-model:org-id="orgId"
    :fetch-data="fetchListPerson"
  />
</template>

<style scoped>
.tree-container {
  overflow: auto;
  height: 74vh;
  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>
