<script setup lang="ts">
import DialogHeader from "@/components/DialogHeader.vue";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";
import { ref, watch, reactive, onMounted, onBeforeMount } from "vue";
import type { QInput, QTableProps } from "quasar";
import { useRoute } from "vue-router";

import http from "@/plugins/http";
import config from "@/app.config";
import { useStructureTree } from "@/stores/structureTree";

import type {
  OrgTree,
  DataTree,
  Positions,
  DataPositionNo,
  FormActive,
  TreeMain,
} from "@/interface/request/orgSelect/org";

const { fetchStructureTree } = useStructureTree();

const rows = ref<any[]>([]);
const rowsData = ref<any[]>([]);
const filterRef = ref<QInput>();
const filterModal = ref<string>("");
const props = defineProps({
  dataRows: {
    type: Object,
    require: true,
  },
  onSubmit: Function,
  saveData: Function,
});
const $q = useQuasar();
const mixin = useCounterMixin();
const {
  dialogConfirm,
  showLoader,
  messageError,
  hideLoader,
  date2Thai,
  dialogMessageNotify,
  onSearchDataTable,
} = mixin;

const route = useRoute();

const modal = defineModel<boolean>("modal", { required: true });
const title = defineModel<string>("title", { required: true });
const selectedModal = defineModel<any[]>("selectedModal");

const filter = ref<string>("");
const isAll = ref<boolean>(false);
const positionNo = ref<DataPositionNo[]>([]);
const itemTaps = ref<string[]>();
const positionId = ref<string>("");
const selectedPos = ref<any[]>([]);
const seletcId = ref<string>("");
const datePos = ref<Date>(new Date());
const rowsPosition = ref<Positions[]>([]);
const positionData = ref<any[]>([]);
/** active form */
const formActive = reactive<FormActive>({
  activeId: "",
  activeName: "",
  draftId: "",
  draftName: "",
  orgPublishDate: null,
  isPublic: false,
});
/** node */
const nodes = ref<Array<OrgTree>>([]);
const lazy = ref(nodes);
const expanded = ref<string[]>([]);
const nodeLevel = ref<number>(0);
const nodeId = ref<string>(""); // id ของ Tree

const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "center",
    label: "ลำดับ",
    field: "no",
    sortable: true,
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "citizenId",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    field: "citizenId",
    sortable: true,
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "name",
    align: "left",
    label: "ชื่อ-นามสกุล",
    field: "name",
    sortable: true,
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "position",
    align: "left",
    label: "ตำแหน่ง",
    field: "position",
    sortable: true,
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

const visibleColumns = ref<String[]>(["no", "citizenId", "name", "position"]);

/** ปิด dialog */
function close() {
  modal.value = false;
  filter.value = "";
  isAll.value = false;
  expanded.value = [];
  nodeLevel.value = 0;
  nodeId.value = "";
  rows.value = [];
  selectedModal.value = [];
}

async function getDataTable(id: string, level: number = 0) {
  showLoader();
  await http
    .post(config.API.orgDeceasedProfile, {
      nodeId: id,
      node: level,
      isAll: isAll.value,
    })
    .then(async (res) => {
      const data = await res.data.result.data;
      rows.value = data;
      rowsData.value = data;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * funtion เลือกข้อมูล Tree
 * @param data ข่อมูล Tree
 */
function updateSelected(data: DataTree) {
  positionId.value = "";
  seletcId.value = "";
  selectedPos.value = [];
  datePos.value = new Date();
  selectedModal.value = [];
  nodeId.value = data.orgTreeId ? data.orgTreeId : "";
  nodeLevel.value = data.orgLevel;
  getDataTable(data.orgTreeId, data.orgLevel);
}

const isLoad = ref<boolean>(false);

/** ดึงข้อมูล active */
async function getTreeData() {
  nodes.value = await fetchStructureTree(route.meta.Key as string, true);
  isLoad.value = true;
}

/**
 * function เลือกตำแหน่งเลขที่
 * @param id เลชที่ตำแหน่ง
 */
async function onClickSelectPos(id: string) {
  positionData.value = positionNo.value;
  positionId.value = id;
  selectedPos.value = [];
  const position: DataPositionNo = positionData.value.find(
    (e: DataPositionNo) => e.id === id
  );

  // หาตำแหน่ง
  if (position) {
    rowsPosition.value = position.positions;
    if (seletcId.value) {
      selectedPos.value = rowsPosition.value.filter(
        (e) => e.id === seletcId.value
      );
    }
  }
}

watch(
  () => modal.value,
  async (n) => {
    if (n == true) {
      !isLoad.value && showLoader();
    }
  }
);

watch(
  () => positionId.value,
  (n) => {
    if (n) {
      onClickSelectPos(n);
    }
  }
);
function onSubmit() {
  if (selectedModal.value?.length == 0) {
    dialogMessageNotify($q, "กรุณาเลือกตำแหน่ง");
  } else {
    dialogConfirm($q, async () => {
      props.saveData?.();
      close();
    });
  }
}

function onSearch() {
  rows.value = onSearchDataTable(
    filterModal.value,
    rowsData.value,
    columns.value ? columns.value : []
  );
}

watch(
  () => modal.value,
  async () => {
    modal.value && (await getTreeData());
  }
);
</script>
<template>
  <q-dialog v-model="modal" persistent full-width>
    <q-card class="no-scroll">
      <DialogHeader :tittle="title" :close="close" />
      <q-separator />
      <q-card-section style="max-height: 70vh">
        <div class="row">
          <q-card
            bordered
            class="col-12 col-sm-3 scroll q-pa-sm"
            style="height: 75vh"
          >
            <q-input dense outlined v-model="filter" label="ค้นหา">
              <template v-slot:append>
                <q-icon name="search" />
              </template>
            </q-input>
            <q-tree
              class="q-pa-sm q-gutter-sm"
              dense
              :nodes="lazy"
              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
                  @click.stop="updateSelected(prop.node)"
                  clickable
                  :active="nodeId == prop.node.orgTreeId"
                  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
            style="height: 75vh"
            class="col-12 col-sm-9 q-pa-sm scroll"
          >
            <div class="col-12 row q-py-sm items-center q-col-gutter-sm">
              <q-space />
              <div class="items-center" style="display: flex">
                <q-checkbox
                  keep-color
                  v-model="isAll"
                  label="แสดงทั้งหมด"
                  color="primary"
                  @click="getDataTable(nodeId, nodeLevel)"
                >
                  <q-tooltip>แสดงทั้งหมด</q-tooltip>
                </q-checkbox>
                <q-input
                  standout
                  dense
                  v-model="filterModal"
                  ref="filterRef"
                  outlined
                  debounce="300"
                  placeholder="ค้นหา"
                  class="q-ml-sm"
                  @keydown.enter="onSearch"
                >
                  <template v-slot:append>
                    <q-icon name="search" />
                  </template>
                </q-input>

                <q-select
                  v-model="visibleColumns"
                  :display-value="$q.lang.table.columns"
                  multiple
                  outlined
                  dense
                  :options="columns"
                  options-dense
                  option-value="name"
                  map-options
                  emit-value
                  style="min-width: 140px"
                  class="gt-xs q-ml-sm"
                />
              </div>
              <div class="col-12">
                <d-table
                  :rows="rows"
                  :columns="columns"
                  :visible-columns="visibleColumns"
                  row-key="id"
                  selection="multiple"
                  v-model:selected="selectedModal"
                  :rows-per-page-options="[10, 25, 50, 100]"
                >
                  <template v-slot:header="props">
                    <q-tr :props="props">
                      <q-th auto-width>
                        <q-checkbox
                          keep-color
                          color="primary"
                          dense
                          v-model="props.selected"
                        />
                      </q-th>
                      <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" class="cursor-pointer">
                      <q-td auto-width>
                        <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>
                </d-table>
              </div>
            </div>
          </q-card>
        </div>
      </q-card-section>
      <q-separator />

      <q-card-actions align="right" class="bg-white text-teal">
        <q-btn label="บันทึก" color="secondary" type="submit" @click="onSubmit"
          ><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>
