<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";

/** importType*/
import type { QTableProps } from "quasar";

/** importStore*/
import { usePermissionsStore } from "@/modules/02_users/stores/permissions";
import { useCounterMixin } from "@/stores/mixin";

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

/** Tree*/
const filter = ref<string>("");
const nodes = ref<Array<any>>([]);
const lazy = ref(nodes);
const expanded = ref<string[]>([]);
const nodeId = ref<string>("");

/** Table*/
/** columns*/
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: false,
    field: "posMasterNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionName",
    align: "left",
    label: "ตำแหน่งในสายงาน",
    field: "positionName",
    sortable: false,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posTypeName",
    align: "left",
    label: "ประเภทตำแหน่ง",
    sortable: false,
    field: "posTypeName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posLevelName",
    align: "left",
    label: "ระดับตำแหน่ง",
    sortable: false,
    field: "posLevelName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionIsSelected",
    align: "left",
    label: "คนครอง",
    sortable: false,
    field: "positionIsSelected",
    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 fetchOrganizationActive() {
  showLoader();
  await http
    .get(config.API.activeOrganization)
    .then((res) => {
      const data = res.data.result;
      if (data) {
        store.activeId = data.activeId;
        store.draftId = data.draftId;

        const id =
          store.typeOrganizational === "current"
            ? store.activeId
            : store.draftId;
        fetchDataTree(id);
      }
    })
    .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.toString()))
    .then((res) => {
      const data = res.data.result;
      nodes.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function updateSelected(data: any) {
  console.log(data);
  nodeId.value = data.orgTreeId;
}

onMounted(() => {
  fetchOrganizationActive();
});
</script>

<template>
  <div class="row items-center">
    <div class="toptitle text-dark row items-center q-py-xs">จัดการสิทธิ์</div>
  </div>

  <q-card flast bordered>
    <q-card-section>
      <q-toolbar class="q-gutter-md items-center" style="padding: 0px">
        <q-btn-group outline>
          <q-btn
            dense
            class="q-px-md"
            :outline="store.typeOrganizational === 'current' ? false : true"
            color="blue"
            label="ปัจจุบัน"
            :disable="store.activeId == '' || store.activeId == null"
            @click="store.typeOrganizational = 'current'"
          />

          <q-btn
            dense
            class="q-px-md"
            :outline="store.typeOrganizational === 'draft' ? false : true"
            color="blue"
            label="แบบร่าง"
            :disable="store.draftId == '' || store.draftId == null"
            @click="store.typeOrganizational = 'draft'"
          />
        </q-btn-group>
      </q-toolbar>
    </q-card-section>
    <q-separator />
    <q-card-section style="padding: 0px">
      <div class="col-12">
        <q-card bordered class="col-12 row caedNone">
          <!-- Tree -->
          <div class="col-xs-12 col-sm-3 row">
            <div class="col-12 row no-wrap bg-grey-1">
              <div class="col-12 q-py-sm q-px-sm">
                <div class="q-gutter-sm">
                  <div class="row q-col-gutter-sm q-pl-sm">
                    <div class="col-12">
                      <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>
                  <div class="bg-white tree-container q-pa-xs">
                    <q-tree
                      class="q-pa-sm q-gutter-sm"
                      dense
                      default-expand-all
                      :nodes="lazy"
                      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
                          @click.stop="updateSelected(prop.node)"
                          :active="nodeId == prop.node.orgTreeId"
                          clickable
                          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 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>
                </div>
              </div>
            </div>
            <div class="col-12 row">
              <q-separator :vertical="!$q.screen.lt.md" />
            </div>
          </div>

          <div class="col-xs-12 col-sm-9 q-pa-md row">
            <div class="col-12 row">
              <!-- TABLE -->
              <div class="col-12">
                <d-table
                  ref="table"
                  :columns="columns"
                  :rows="posMaster"
                  :paging="true"
                  row-key="id"
                  flat
                  bordered
                  dense
                  :rows-per-page-options="[10, 25, 50, 100]"
                  @update:pagination="updatePagination"
                  v-model:pagination="pagination"
                >
                  <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-th auto-width></q-th>
                    </q-tr>
                  </template>
                  <template v-slot:body="props">
                    <q-tr :props="props" class="cursor-pointer">
                      <q-td>
                        <q-btn
                          flat
                          size="14px"
                          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 == 'no'">
                          {{
                            (reqMaster.page - 1) * Number(reqMaster.pageSize) +
                            props.rowIndex +
                            1
                          }}
                        </div>
                        <div v-else-if="col.name === 'posMasterNo'">
                          {{
                            props.row.isSit
                              ? col.value + " " + "(ทับที่)"
                              : col.value
                          }}
                        </div>
                        <div v-else-if="col.name === 'posLevelName'">
                          {{
                            props.row.posLevelName
                              ? props.row.isSpecial == true
                                ? `${props.row.posLevelName} (ฉ)`
                                : props.row.posLevelName
                              : "-"
                          }}
                        </div>
                        <div v-else>
                          {{ col.value ? col.value : "-" }}
                        </div>
                      </q-td>
                      <q-td>
                        <q-btn
                          flat
                          dense
                          icon="mdi-dots-vertical"
                          class="q-pa-none q-ml-xs"
                          color="grey-13"
                          size="12px"
                        >
                          <q-menu>
                            <q-list dense style="min-width: 150px">
                              <!-- เลือกคนครอง -->
                              <q-item
                                v-if="
                                  props.row.positionIsSelected == 'ว่าง' &&
                                  store.typeOrganizational === 'draft'
                                "
                                clickable
                                v-close-popup
                                @click="openSelectPerson(props.row)"
                              >
                                <q-item-section>
                                  <div class="row items-center">
                                    <q-icon
                                      color="secondary"
                                      size="17px"
                                      name="mdi-account"
                                    />
                                    <div class="q-pl-md">เลือกคนครอง</div>
                                  </div>
                                </q-item-section>
                              </q-item>
                              <q-item
                                v-else-if="
                                  props.row.positionIsSelected != 'ว่าง' &&
                                  store.typeOrganizational === 'draft'
                                "
                                clickable
                                v-close-popup
                                @click="removePerson(props.row.id)"
                              >
                                <q-item-section>
                                  <div class="row items-center">
                                    <q-icon
                                      color="red"
                                      size="17px"
                                      name="mdi-account-remove"
                                    />
                                    <div class="q-pl-md">ลบคนครอง</div>
                                  </div>
                                </q-item-section>
                              </q-item>
                              <q-item
                                v-for="(
                                  item, index
                                ) in store.typeOrganizational === 'draft'
                                  ? listMenu
                                  : listMenu.filter(
                                      (e) => e.type === 'HISTORY'
                                    )"
                                :key="index"
                                clickable
                                v-close-popup
                                @click="
                                  item.type === 'EDIT'
                                    ? onClickPosition('EDIT', props.row.id)
                                    : item.type === 'DEL'
                                    ? onClickDelete(props.row.id)
                                    : item.type === 'MOVE'
                                    ? onClickMovePos(props.row.id, 'SINGER')
                                    : item.type === 'HISTORY'
                                    ? onClickHistoryPos(props.row.id)
                                    : item.type === 'INHERIT'
                                    ? onClickInherit(props.row.id)
                                    : item.type === 'COPY'
                                    ? onClickCopyPosition('COPY', props.row.id)
                                    : null
                                "
                              >
                                <q-item-section>
                                  <div class="row items-center">
                                    <q-icon
                                      :color="item.color"
                                      size="17px"
                                      :name="item.icon"
                                    />
                                    <div class="q-pl-md">{{ item.label }}</div>
                                  </div>
                                </q-item-section>
                              </q-item>
                              <q-item
                                v-if="props.row.positionIsSelected != 'ว่าง'"
                                clickable
                                v-close-popup
                                @click="onClickViewDetail(props.row)"
                              >
                                <q-item-section>
                                  <div class="row items-center">
                                    <q-icon
                                      color="blue"
                                      size="17px"
                                      name="mdi-eye"
                                    />
                                    <div class="q-pl-md">ดูรายละเอียด</div>
                                  </div>
                                </q-item-section>
                              </q-item>
                            </q-list>
                          </q-menu>
                        </q-btn>
                      </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" class="cursor-pointer">
                                <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">
                    <q-pagination
                      v-model="reqMaster.page"
                      active-color="primary"
                      color="dark"
                      :max="totalPage"
                      :max-pages="5"
                      size="sm"
                      boundary-links
                      direction-links
                    ></q-pagination>
                  </template> -->
                </d-table>
              </div>
            </div>
          </div>
        </q-card>
      </div>
    </q-card-section>
  </q-card>
</template>

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