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

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

import type { QTableProps } from "quasar";
import type {
  OrgTree,
  DataPositionCondition,
} from "@/modules/19_condition/interface/response/Main";
import type { Pagination } from "@/modules/19_condition/interface/index/Main";

import LoadView from "@/components/LoadView.vue";
import DialogCondition from "@/modules/19_condition/components/DialogCondition.vue";

const $q = useQuasar();
const { showLoader, hideLoader, messageError } = useCounterMixin();

const isLoadTable = ref<boolean>(false);

//Tree
const activeId = ref<string>("");
const filter = ref<string>("");
const orgTreeId = ref<string>("");
const nodeTree = ref<OrgTree[]>([]);
const expanded = ref<string[]>([]);

//Table
const isAll = ref<boolean>(false);
const keyword = ref<string>("");
const page = ref<number>(1);
const pageSize = ref<number>(10);
const orgLevel = ref<number>(0);
const totalPage = ref<number>(1);
const totalRow = ref<number>(0);
const modalCondition = ref<boolean>(false);
const dataCondition = ref<DataPositionCondition>();

const rows = ref<DataPositionCondition[]>([]);
const pagination = ref({
  page: 1,
  rowsPerPage: 10,
});
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    format(val, row) {
      return (page.value - 1) * pageSize.value + rows.value.indexOf(row) + 1;
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posMasterNo",
    align: "left",
    label: "ตำแหน่งเลขที่",
    sortable: false,
    field: "posMasterNo",
    format(val, row) {
      return row.isSit
        ? `${row.orgShortname}${row.posMasterNo}(นั่งทับตำแหน่ง)`
        : `${row.orgShortname}${row.posMasterNo}`;
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "profilePosition",
    align: "left",
    label: "ตำแหน่งในสายงาน",
    field: "profilePosition",
    sortable: false,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "profilePostype",
    align: "left",
    label: "ประเภทตำแหน่ง",
    sortable: false,
    field: "profilePostype",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "profilePoslevel",
    align: "left",
    label: "ระดับตำแหน่ง",
    sortable: false,
    field: "profilePoslevel",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "isCondition",
    align: "center",
    label: "ตำแหน่งติดเงื่อนไข",
    sortable: false,
    field: "isCondition",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },

  {
    name: "conditionReason",
    align: "left",
    label: "หมายเหตุ",
    sortable: false,
    field: "conditionReason",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const columnsExpand = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionName",
    align: "left",
    label: "ตำแหน่งในสายงาน",
    sortable: true,
    field: "positionName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionField",
    align: "left",
    label: "สายงาน",
    sortable: true,
    field: "positionField",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posTypeName",
    align: "left",
    label: "ประเภทตำเเหน่ง",
    sortable: true,
    field: "posTypeName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posLevelName",
    align: "left",
    label: "ระดับตำแหน่ง",
    sortable: true,
    field: "posLevelName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posExecutiveName",
    align: "left",
    label: "ตำแหน่งทางการบริหาร",
    sortable: true,
    field: "posExecutiveName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionExecutiveField",
    align: "left",
    label: "ด้านทางการบริหาร",
    sortable: true,
    field: "positionExecutiveField",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionArea",
    align: "left",
    label: "ด้าน/สาขา",
    sortable: true,
    field: "positionArea",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

/**
 * function เรียกข้อมูลโครงสร้าง แบบปัจุบัน
 */
async function fetchOrgActive() {
  showLoader();
  http
    .get(config.API.activeOrganization)
    .then(async (res) => {
      const data = res.data.result;
      if (data) {
        activeId.value = data.activeId;
        await fetchDataTree(data.activeId);
      }
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * function fetch ข้อมูลของ Tree
 * @param id id โครงสร้าง
 */
async function fetchDataTree(id: string) {
  showLoader();
  await http
    .get(config.API.orgByid(id))
    .then((res) => {
      const data = res.data.result;
      nodeTree.value = data.data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function onSelectedOrgTree(data: OrgTree) {
  orgTreeId.value = data.orgTreeId;
  orgLevel.value = data.orgLevel;
  fetchDataTable();
}

/**
 * function fetch ข้อรายการตำแหน่ง
 */
async function fetchDataTable() {
  rows.value = [];
  isLoadTable.value = true;
  await http
    .post(config.API.positionCondition, {
      id: orgTreeId.value,
      type: orgLevel.value,
      isAll: isAll.value,
      page: page.value,
      pageSize: pageSize.value,
      keyword: keyword.value,
      revisionId: activeId.value,
    })
    .then(async (res) => {
      const data = await res.data.result;
      totalRow.value = data.total;
      totalPage.value = Math.ceil(data.total / pageSize.value);

      rows.value = data.data.map((e: DataPositionCondition) => ({
        ...e,
        profilePosition: e.profilePosition
          ? e.profilePosition
          : e.positions[0].positionName,
        profilePostype: e.profilePostype
          ? e.profilePostype
          : e.positions[0].posTypeName,
        profilePoslevel: e.profilePoslevel
          ? e.profilePoslevel
          : e.positions[0].posTypeName,
      }));
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      isLoadTable.value = false;
    });
}

function onSearchDataTable() {
  page.value = 1;
  fetchDataTable();
}

function updatePagination(newPagination: Pagination) {
  pageSize.value = newPagination.rowsPerPage;
}

function onSetCondution(data: DataPositionCondition) {
  dataCondition.value = data;
  modalCondition.value = true;
}

watch(pageSize, () => {
  onSearchDataTable();
});

onMounted(async () => {
  await fetchOrgActive();
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    จัดการตำแหน่งติดเงื่อนไข
  </div>

  <q-card>
    <q-card-section :horizontal="$q.screen.gt.xs">
      <!-- Tree -->
      <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="ค้นหา" clearable>
            <template v-slot:append>
              <q-icon v-if="!filter" 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
                :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" />

      <!-- Table -->
      <q-card-section
        class="col-lg-9 col-md-8 col-xs-12 q-gutter-sm"
        v-if="orgTreeId"
      >
        <div class="row col-12 q-gutter-sm">
          <div class="row col-12">
            <q-space />
            <div class="row q-gutter-sm">
              <q-checkbox
                v-model="isAll"
                label="แสดงตำแหน่งทั้งหมด"
                color="primary"
                keep-color
                @update:model-value="onSearchDataTable"
              />

              <q-input
                outlined
                dense
                v-model="keyword"
                label="ค้นหา"
                @keydown.enter.prevent="onSearchDataTable"
              >
                <template v-slot:append>
                  <q-icon name="search" color="grey-5" />
                </template>
              </q-input>
            </div>
          </div>
          <div class="col-12">
            <d-table
              ref="table"
              :columns="columns"
              :rows="rows"
              :paging="true"
              row-key="id"
              flat
              bordered
              dense
              :rows-per-page-options="[10, 25, 50, 100]"
              :loading="isLoadTable"
              v-model:pagination="pagination"
              @update:pagination="updatePagination"
            >
              <template v-slot:header="props">
                <q-tr :props="props">
                  <q-th auto-width></q-th>
                  <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 auto-width>
                    <q-btn
                      flat
                      color="edit"
                      round
                      dense
                      icon="edit"
                      @click.stop.pervent="onSetCondution(props.row)"
                    />
                  </q-td>
                  <q-td auto-width>
                    <q-btn
                      flat
                      color="primary"
                      round
                      dense
                      @click="props.expand = !props.expand"
                      :icon="props.expand ? 'mdi-menu-down' : 'mdi-menu-right'"
                    />
                  </q-td>

                  <q-td
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                  >
                    <div v-if="col.name === 'isCondition'">
                      <q-icon
                        v-if="col.value"
                        name="check"
                        color="primary"
                        size="sm"
                      />
                      <span v-else>-</span>
                    </div>
                    <div v-else>
                      {{ col.value ? col.value : "-" }}
                    </div>
                  </q-td>
                </q-tr>

                <q-tr v-show="props.expand" :props="props">
                  <q-td colspan="100%" class="bg-grey-1">
                    <q-card flat bordered class="text-left q-ma-sm">
                      <d-table
                        flat
                        :columns="columnsExpand"
                        :rows="props.row.positions"
                        table-class="text-grey-9"
                        row-key="id"
                        dense
                        hide-bottom
                        bordered
                        separator="vertical"
                        class="custom-header-table-expand"
                      >
                        <template v-slot:header="props">
                          <q-tr :props="props" class="bg-grey-2">
                            <q-th
                              v-for="col in props.cols"
                              :key="col.name"
                              :props="props"
                            >
                              <span class="q-px-sm text-body2 text-black">{{
                                col.label
                              }}</span>
                            </q-th>
                          </q-tr>
                        </template>
                        <template v-slot:body="props">
                          <q-tr :props="props">
                            <q-td
                              v-for="col in props.cols"
                              :key="col.name"
                              :props="props"
                            >
                              <div v-if="col.name == 'no'" class="text-body2">
                                {{ props.rowIndex + 1 }}
                              </div>
                              <div
                                v-else-if="col.name === 'posExecutiveName'"
                                class="text-body2"
                              >
                                {{ col.value ? col.value : "-" }}
                              </div>

                              <div
                                v-else-if="
                                  col.name === 'positionExecutiveField'
                                "
                                class="text-body2"
                              >
                                {{ col.value ? col.value : "-" }}
                              </div>

                              <div
                                v-else-if="col.name === 'positionArea'"
                                class="text-body2"
                              >
                                {{ col.value ? col.value : "-" }}
                              </div>

                              <div v-else class="text-body2">
                                {{ col.value }}
                              </div>
                            </q-td>
                          </q-tr>
                        </template>
                      </d-table>
                    </q-card>
                  </q-td>
                </q-tr>
              </template>
              <template v-slot:pagination="scope">
                ทั้งหมด {{ totalRow }} รายการ
                <q-pagination
                  v-model="page"
                  active-color="primary"
                  color="dark"
                  :max="totalPage"
                  :max-pages="5"
                  size="sm"
                  boundary-links
                  direction-links
                  @update:model-value="fetchDataTable"
                ></q-pagination>
              </template>
              <template v-slot:loading>
                <LoadView />
              </template>
            </d-table>
          </div>
        </div>
      </q-card-section>
    </q-card-section>
  </q-card>

  <DialogCondition
    v-model:modal="modalCondition"
    :fetch-data="fetchDataTable"
    :data-condition="dataCondition"
  />
</template>

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