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

/** importType*/
import type {
  PositionMaim,
  PositionNo,
  Positions,
  TreeMain,
} from "@/modules/05_placement/interface/response/SelectOrg";
import type { DataPositionNo } from "@/modules/05_placement/interface/index/SelectOrg";

/** importComponents*/
import Header from "@/components/DialogHeader.vue";
import CardPosition from "@/modules/05_placement/components/PersonalList/CardPosition.vue";

/** importStore*/
import { useCounterMixin } from "@/stores/mixin";
import { useSelectOrgStore } from "@/modules/05_placement/stores/storeSelect";

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

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

const props = defineProps({
  dataRow: {
    type: Object,
    require: true,
  },
});

/** Tree*/
const nodeId = ref<string>("");
const nodeLevel = ref<number>(0);
const filterTree = ref<string>("");
const nodes = ref<Array<TreeMain>>([]);
const lazy = ref(nodes);
const expanded = ref<string[]>([]);

const positionNo = ref<DataPositionNo[]>();
const positionId = ref<string>("");
const selectedPos = ref<any[]>([]);
const datePos = ref<Date>(new Date());

function closePopup() {
  modal.value = !modal.value;
}

/** function เรียกข้อมูลโครงสร้าง แบบปัจุบันและ แบบร่าง*/
async function fetchOrganizationActive() {
  showLoader();
  await http
    .get(config.API.activeOrganization)
    .then((res) => {
      const data = res.data.result;
      if (data) {
        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.toString()))
    .then((res) => {
      const data = res.data.result;
      if (data) {
        nodes.value = data;
        filterItemsTaps(data);
      }
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

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

/**
 * function fetch ข้อรายการตำแหน่ง
 * @param id  idTree
 * @param level  levelTree
 */
async function fetchDataTable(id: string, level: number = 0) {
  const body = {
    node: level,
    nodeId: id,
    position: props?.dataRow?.positionCandidate,
  };
  await http
    .post(config.API.orgPosPlacement, body)
    .then((res) => {
      const dataMain: PositionMaim[] = [];
      res.data.result.data.forEach((e: PositionNo) => {
        const p = e.positions;
        if (p.length !== 0) {
          const a = p.find((el: Positions) => el.positionIsSelected === true);
          const { id, ...rest } = a ? a : p[0];
          const test = { ...e, ...rest };
          dataMain.push(test);
        }
      });
      positionNo.value = store.fetchPosNo(dataMain);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {});
}

function onClickSubmit() {
  if (selectedPos.value.length === 0) {
    dialogMessageNotify($q, "กรุณาเลือกตำแหน่ง");
  } else {
    dialogConfirm($q, () => {
      const body = {
        node: nodeLevel.value,
        nodeId: nodeId.value,
        posmasterId: positionId.value,
        positionId: selectedPos.value[0].id,
        reportingDate: datePos.value,
      };
      console.log(body);
    });
  }
}

function clearData() {
  nodeId.value = "";
  expanded.value = [];
}

watch(
  () => modal.value,
  async () => {
    if (modal.value) {
      showLoader();
      await fetchOrganizationActive();
      // console.log(props.dataRow);

      expanded.value = [];
      // expanded.value = [
      //   "c6164a42-539d-401a-b289-653282c08e37",
      //   "277e5221-9c47-43ca-a7a5-0ba6e30039c4",
      // ];
      // nodeId.value = "c6164a42-539d-401a-b289-653282c08e37";
      // fetchDataTable(nodeId.value);
    } else {
      clearData();
    }
  }
);

const itemTaps = ref<string[]>();
function filterItemsTaps(data: TreeMain[]) {
  let orgTreeIds: string[] = [];
  for (const child of data) {
    orgTreeIds.push(child.orgTreeId);
    if (child.children) {
      orgTreeIds = orgTreeIds.concat(filterItemsTaps(child.children));
    }
  }
  itemTaps.value = orgTreeIds;
  return orgTreeIds;
}
</script>
<template>
  <q-dialog v-model="modal" full-width persistent>
    <q-card>
      <Header :tittle="'เลือกหน่วยงานที่รับบรรจุ'" :close="closePopup" />
      <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-3 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="filterTree = ''"
                />
              </template>
            </q-input>
            <q-tree
              class="q-pa-sm q-gutter-sm"
              dense
              default-expand-all
              :nodes="lazy"
              node-key="orgTreeId"
              label-key="orgTreeName"
              :filter="filterTree"
              no-results-label="ไม่พบข้อมูลที่ค้นหา"
              no-nodes-label="ไม่มีข้อมูล"
              v-model:expanded="expanded"
            >
              <template v-slot:default-header="prop">
                <q-item
                  clickable
                  :active="nodeId == 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-9 q-pa-sm">
            <q-tab-panels
              v-model="nodeId"
              animated
              transition-prev="jump-up"
              transition-next="jump-up"
            >
              <q-tab-panel
                v-for="(item, index) in itemTaps"
                :key="index"
                :name="item"
              >
                <CardPosition
                  :position="positionNo"
                  v-model:selectedPos="selectedPos"
                  v-model:datePos="datePos"
                  v-model:positionId="positionId"
                />
              </q-tab-panel>
            </q-tab-panels>
          </q-card>
        </div>
      </q-card-section>
      <q-separator />

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