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

import { useRoute } from "vue-router";
import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useSelectOrgStore } from "@/modules/05_placement/stores/storeSelect";
import { useStructureTree } from "@/stores/structureTree";

/** importType*/
import type {
  PositionMaim,
  PositionNo,
  Positions,
  TreeMain,
  FormPosType,
  FormPosLevel,
} 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";

const route = useRoute();
const $q = useQuasar();
const storeTree = useStructureTree();
const { fetchStructureTree } = useStructureTree();
const store = useSelectOrgStore();
const {
  success,
  showLoader,
  hideLoader,
  messageError,
  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 positionUse = ref<string[]>([]);
const positionNo = ref<DataPositionNo[]>([]);
const positionId = ref<string>("");
const seletcId = ref<string>("");
const posType = ref<FormPosType | null>(null);
const posLevel = ref<string>("");
const selectedPos = ref<any[]>([]);
const datePos = ref<Date>(new Date());
const posMasterMain = ref<any[]>([]);
const orgRevisionId = ref<string>("");
const optionPosType = ref<FormPosType[]>([]);
const optionPosLevel = ref<FormPosLevel[]>([]);

/** function เรียกข้อมูลโครงสร้าง แบบปัจุบันและ แบบร่าง*/
async function fetchStructure() {
  const dataTree = await fetchStructureTree(route.meta.Key as string, false);
  if (dataTree) {
    orgRevisionId.value = storeTree.activeId;
    nodes.value = dataTree;
    filterItemsTaps(dataTree);
  }
}

/**
 * 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
 */
const isAll = ref<boolean>(false);
const isBlank = ref<boolean>(true);
const isPosition = ref<string>("exam");
// const isPositionOld = ref<boolean>(false);
async function fetchDataTable(id: string, level: number = 0) {
  showLoader();
  const body = {
    node: level,
    nodeId: id,
    position:
      isPosition.value === "exam" ? props?.dataRow?.positionCandidate : null,
    posLevel:
      isPosition.value === "exam"
        ? props.dataRow?.posLevelCandidateId
        : posLevel.value
        ? posLevel.value
        : null,

    posType:
      isPosition.value === "exam"
        ? props.dataRow?.posTypeCandidateId
        : posType.value
        ? posType.value.id
        : null,
    isAll: isAll.value,
    isBlank: isBlank.value,
  };

  await http
    .post(config.API.orgPosPlacementAll, 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: any = { ...e, ...rest };
          dataMain.push(data);
        }
      });

      let posMain = store.fetchPosNo(dataMain);

      if (props.dataRow?.posmasterId) {
        const newUse = positionUse.value.filter(
          (e) => e !== props.dataRow?.posmasterId
        );

        positionNo.value = posMain.filter((e: any) => !newUse.includes(e.id));
      } else {
        positionNo.value = posMain.filter(
          (e: any) => !positionUse.value.includes(e.id)
        );
      }
    })
    .catch((err) => {
      messageError($q, err);
      hideLoader();
    })
    .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?.reportingDate;

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

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

      await http
        .post(config.API.placementPass(), body)
        .then(async () => {
          await Promise.all([props.fetchTable?.(), props.fetchStatCard?.()]);
          await success($q, "บันทึกข้อมูลสำเร็จ");
          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 = [];
  posType.value = null;
  posLevel.value = "";
  isPosition.value = "exam";
  filterTree.value = "";
}

/** callback function เมื่อมีการเปิด popup*/
watch(
  () => modal.value,
  async () => {
    if (modal.value) {
      await fetchPositionUes();

      if (props?.dataRow?.node !== null && props?.dataRow?.nodeId !== null) {
        await fetchPosFind(props?.dataRow?.node, props?.dataRow?.nodeId);
      } else {
        expanded.value = [];
      }
    }
  }
);

async function fetchPositionUes() {
  await http
    .get(config.API.placementPositionUse())
    .then((res) => {
      positionUse.value = res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

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

async function getOrgPosType() {
  await http
    .get(config.API.orgPosType)
    .then(async (res) => {
      const data = await res.data.result;
      optionPosType.value = data;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {});
}

function onPosType() {
  posLevel.value = "";
  if (posType.value) {
    optionPosLevel.value = posType.value.posLevels;
  }
  fetchDataTable(nodeId.value, nodeLevel.value);
}

watch(
  () => isAll.value,
  (value, oldVal) => {
    if (value !== oldVal) {
      fetchDataTable(nodeId.value, nodeLevel.value);
    }
  }
);

watch(
  () => isBlank.value,
  (value, oldVal) => {
    if (value !== oldVal) {
      fetchDataTable(nodeId.value, nodeLevel.value);
    }
  }
);

watch(
  () => isPosition.value === "select",
  (value, oldVal) => {
    if (value !== oldVal) {
      fetchDataTable(nodeId.value, nodeLevel.value);
      getOrgPosType();
    }
  }
);

onMounted(() => {
  fetchStructure();
});
</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: 80vh"
          >
            <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="labelName"
              :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 scroll"
            style="height: 80vh"
          >
            <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 as []"
                  v-model:selectedPos="selectedPos"
                  v-model:datePos="datePos"
                  v-model:positionId="positionId"
                  v-model:seletcId="seletcId"
                  v-model:is-all="isAll"
                  v-model:is-blank="isBlank"
                  v-model:is-position="isPosition"
                  v-model:pos-type="posType as FormPosType"
                  v-model:pos-level="posLevel"
                  v-model:option-pos-type="optionPosType"
                  v-model:option-pos-level="optionPosLevel"
                  :fetch-data-table="fetchDataTable"
                  :on-pos-type="onPosType"
                  :node-id="nodeId"
                  :node-level="nodeLevel"
                  :bma-officer="props.dataRow?.bmaOfficer"
                />
              </q-tab-panel>
            </q-tab-panels>
          </q-card>
        </div>
      </q-card-section>
      <q-separator />

      <q-card-actions align="right">
        <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>
