<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,
  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 },
  typeCommand: {
    type: String,
    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 selectedPos = ref<any[]>([]);
const datePos = ref<Date>(new Date());
const posMasterMain = ref<any[]>([]);
const orgRevisionId = ref<string>("");

/** function เรียกข้อมูลโครงสร้าง แบบปัจุบันและ แบบร่าง*/
async function fetchOrganizationActive() {
  showLoader();
  await http
    .get(config.API.activeOrganization)
    .then((res) => {
      const data = res.data.result;
      if (data) {
        orgRevisionId.value = data.activeId;
        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
 */
const isAll = ref<boolean>(false);
const isBlank = ref<boolean>(true);
async function fetchDataTable(id: string, level: number = 0) {
  showLoader();
  const body = {
    node: level,
    nodeId: id,
    position: props?.dataRow?.positionCandidate,
    typeCommand: props.typeCommand,
    posLevel: props.dataRow?.posLevelCandidateId
      ? props.dataRow?.posLevelCandidateId
      : "",
    posType: props.dataRow?.posTypeCandidateId
      ? props.dataRow?.posTypeCandidateId
      : "",
    isAll: isAll.value,
    isBlank: isBlank.value,
  };

  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: 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);
    })
    .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,
        typeCommand: props.typeCommand,
      };

      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 = [];
}

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

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

function fetchPositionUes() {
  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;
}

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

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