<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 {
  success,
  showLoader,
  hideLoader,
  messageError,
  date2Thai,
  dialogMessageNotify,
  dialogConfirm,
} = useCounterMixin();

/**props*/
const modal = defineModel<boolean>("modal", { required: true });
const props = defineProps({
  dataRow: {
    type: Object,
    require: true,
  },
  fetchTable: {
    type: Function,
    require: true,
  },
  fetchStatCard: { type: Function, 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[]>([]);

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

/** 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);
    });
}

/**
 * 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(() => {
      setTimeout(() => {
        hideLoader();
      }, 1000);
    });
}

/**
 * funtion เลือกข้อมูล Tree
 * @param data ข่อมูล Tree
 */
function updateSelected(data: TreeMain) {
  if (props?.dataRow?.nodeId === data.orgTreeId) {
    positionId.value = props?.dataRow?.posmasterId;
    seletcId.value = props?.dataRow?.positionId;
    datePos.value = props?.dataRow?.reportingDateFullDate;
  } else {
    positionId.value = "";
    seletcId.value = "";
    selectedPos.value = [];
    datePos.value = new Date();
  }

  nodeId.value = data.orgTreeId ? data.orgTreeId : "";
  nodeLevel.value = data.orgLevel;
  fetchDataTable(data.orgTreeId, data.orgLevel);
}

/**
 * function fetch ข้อรายการตำแหน่ง
 * @param id  idTree
 * @param level  levelTree
 */
async function fetchDataTable(id: string, level: number = 0) {
  showLoader();
  const body = {
    node: level,
    nodeId: id,
    position: props?.dataRow?.positionCandidate,
  };
  await http
    .post(config.API.orgPosPlacement, body)
    .then((res) => {
      const dataMain: PositionMaim[] = [];
      posMasterMain.value = res.data.result.data;
      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 data = { ...e, ...rest };
          dataMain.push(data);
        }
      });

      positionNo.value = store.fetchPosNo(dataMain);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      setTimeout(() => {
        hideLoader();
      }, 1000);
    });
}

/**
 * function fetch ข้อมูล expanded tree
 * @param level levelTree
 * @param id treeId
 */
async function fetchPosFind(level: number, id: string) {
  showLoader();
  const body = {
    node: level,
    nodeId: id,
  };
  await http
    .post(config.API.orgPosFind, body)
    .then((res) => {
      const data = res.data.result;
      expanded.value = data;
      nodeId.value = id;
      positionId.value = props?.dataRow?.posmasterId;
      seletcId.value = props?.dataRow?.positionId;
      datePos.value = props?.dataRow?.reportingDateFullDate;

      fetchDataTable(nodeId.value, level);
    })
    .catch((e) => {
      messageError($q, e);
      hideLoader();
    });
}

/** function บันทึกข้อมูลตำแหน่ง*/
async function onClickSubmit() {
  const dataPosMaster = await posMasterMain.value?.find(
    (e: any) => e.id === positionId.value
  );
  const dataNode = await filterNodeFn(nodes.value, nodeId.value);

  if (selectedPos.value.length === 0) {
    dialogMessageNotify($q, "กรุณาเลือกตำแหน่ง");
  } else {
    dialogConfirm($q, async () => {
      showLoader();
      const body = {
        PersonalId: props?.dataRow?.personalId,
        node: nodeLevel.value,
        nodeId: nodeId.value,
        posmasterId: positionId.value,
        positionId: selectedPos.value[0].id,
        reportingDate: datePos.value,
        organizationName: dataNode.orgTreeName, //ชื่อหน่วยงาน
        orgTreeShortName: dataNode.orgTreeShortName, //ชื่อย่อ
        posPath: selectedPos.value[0].positionName, //ชื่อตำแหน่ง
        posNumber: dataPosMaster.posMasterNo, //เลขที่ตำแหน่ง(เลขอย่่างเดียว)
      };

      await http
        .post(config.API.placementPass(), body)
        .then(() => {
          success($q, "บันทึกข้อมูลสำเร็จ");
          props.fetchStatCard?.();
          props.fetchTable?.();
          closePopup();
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    });
  }
}

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

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

/** callback function เมื่อมีการเปิด popup*/
watch(
  () => modal.value,
  async () => {
    if (modal.value) {
      await fetchOrganizationActive();
      if (props?.dataRow?.node !== null && props?.dataRow?.nodeId !== null) {
        await fetchPosFind(props?.dataRow?.node, props?.dataRow?.nodeId);
      } else {
        expanded.value = [];
      }
    }
  }
);

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;
}

function filterNodeFn(data: any, id: string) {
  for (const child of data) {
    if (child.orgTreeId === id) {
      return child;
    } else if (child.children) {
      const result: any = filterNodeFn(child.children, id);
      if (result !== null) {
        return result;
      }
    }
  }
  return null;
}
</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
                  v-model:position="positionNo"
                  v-model:selectedPos="selectedPos"
                  v-model:datePos="datePos"
                  v-model:positionId="positionId"
                  v-model:seletcId="seletcId"
                />
              </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>
