<script setup lang="ts">
import { useQuasar, QForm } from "quasar";
import { onMounted, reactive, ref, watch } from "vue";
import DialogHeader from "@/modules/05_placement/components/PersonalList/DialogHeader.vue";
import DialogFooter from "@/modules/05_placement/components/PersonalList/DialogFooter.vue";
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";

const $q = useQuasar();
const mixin = useCounterMixin(); //เรียกฟังก์ชันกลาง
const {
  date2Thai,
  hideLoader,
  messageError,
  showLoader,
  success,
  dialogConfirm,
} = mixin; //ฟังก์ชันกลางที่เรียกใช้

const notFound = ref<string>("ไม่พบข้อมูลที่ค้นหา");
const noData = ref<string>("ไม่พบข้อมูลผังโครงสร้าง");

const checkValidate = ref<boolean>(false);
const myFormPosition = ref<any>();
const selected = ref<string>("");
const selectedFile = ref<string>("");
const dataRespone = ref<any>();
const personal = ref<any>();
const expanded = ref<string[]>([]);
const treeData = ref<Array<any>>([]);
const placementPosition = ref<any>([]);
const search = ref<string>("");
const filterRef = ref<any>(null);
const id = ref<string>("");

const editDataStatus = ref<boolean>(false);
// Set form field
let dataForm = reactive({
  personalId: "",
  containDate: new Date(),
  posNoId: "",
  positionId: "",
  positionLevelId: "",
  positionLineId: "",
  positionPathSideId: "",
  positionTypeId: "",
});

onMounted(async () => {
  await fetchPublishFile();
  await loadTreeData();
  await fetchplacementPosition();
});
const fetchPublishFile = async () => {
  await http
    .get(config.API.getPublishFileHistory)
    .then((res) => {
      let data = res.data.result;
      selectedFile.value = data[0].fileName;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
    });
};
// โหลดข้อมูลโครงสร้างจาก json
const loadTreeData = async () => {
  expanded.value = [];
  await http
    .get(`${config.s3ClusterUrl}${selectedFile.value}`)
    .then((res: any) => {
      treeData.value = res.data;
      dataRespone.value = res.data;
      // Filter objects with "name" null
      const filteredData = res.data.filter(filterByPersonIdNull);
      treeData.value = filteredData;
    })
    .catch((e: any) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};
function filterByPersonIdNull(obj: any) {
  if (obj.name === null && obj.isCondition != true) {
    return true;
  }
  if (obj.children && obj.children.length > 0) {
    obj.children = obj.children.filter(filterByPersonIdNull);
    return obj.children.length > 0;
  }
  return false;
}
// โหลด position
const fetchplacementPosition = async () => {
  await http
    .get(config.API.apppointmentPositionUse())
    .then((res: any) => {
      placementPosition.value = res.data.result;
    })
    .catch((e: any) => {
      messageError($q, e);
    });
};
const props = defineProps({
  personalId: String,
  modal: Boolean,
  close: {
    type: Function,
    default: () => console.log("close modal"),
  },
  personal: Object,
});
const myFilterMethod = (node: any, filter: string) => {
  const filt = filter;
  return (
    (node.name && node.name.indexOf(filt) > -1) ||
    (node.organizationName && node.organizationName.indexOf(filt) > -1) ||
    (node.positionNum && node.positionNum.indexOf(filt) > -1) ||
    (node.positionName && node.positionName.indexOf(filt) > -1) ||
    (node.governmentCode &&
      node.governmentCode.toString().indexOf(filt) > -1) ||
    (node.agency && node.agency.indexOf(filt) > -1) ||
    (node.government && node.government.indexOf(filt) > -1) ||
    (node.department && node.department.indexOf(filt) > -1) ||
    (node.pile && node.pile.indexOf(filt) > -1) ||
    (node.organizationShortName &&
      node.organizationShortName.indexOf(filt) > -1) ||
    (node.positionSideName && node.positionSideName.indexOf(filt) > -1) ||
    (node.executivePosition && node.executivePosition.indexOf(filt) > -1) ||
    (node.executivePositionSide &&
      node.executivePositionSide.indexOf(filt) > -1) ||
    (node.positionLevel && node.positionLevel.indexOf(filt) > -1)
  );
};
const validateData = async () => {
  checkValidate.value = true;
  await myFormPosition.value.validate().then((result: boolean) => {
    if (result == false) {
      checkValidate.value = false;
    }
  });
};
const saveAppoint = async () => {
  myFormPosition.value.validate().then(async (result: boolean) => {
    if (props.personalId !== undefined) {
      id.value = props.personalId.toString();
    }
    if (result) {
      const dataAppoint = await {
        recruitDate: dataForm.containDate,
        posNoId: dataForm.posNoId,
        positionId: dataForm.positionId,
        positionLevelId: dataForm.positionLevelId,
        positionLineId: dataForm.positionLineId,
        positionPathSideId: dataForm.positionPathSideId,
        positionTypeId: dataForm.positionTypeId,
      };
      showLoader();
      await http
        .put(config.API.appointEmployeePosition(id.value), dataAppoint)
        .then(() => {
          success($q, "บันทึกสำเร็จ");
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(async () => {
          await closeAndClear();
          await fetchPublishFile();
          await loadTreeData();
          await fetchplacementPosition();
          hideLoader();
        });
    }
  });
};
const closeModal = () => {
  if (editDataStatus.value == true) {
    dialogConfirm(
      $q,
      async () => {
        editDataStatus.value = false;
        await closeAndClear();
      },
      `ข้อมูลมีการแก้ไข`,
      `ยืนยันที่จะปิดโดยไม่บันทึกใช่หรือไม่?`
    );
  } else {
    closeAndClear();
  }
};
const closeAndClear = async () => {
  await props.close();
  editDataStatus.value = false;
  selected.value = "";
  dataForm.personalId = "";
  dataForm.containDate = new Date();
  dataForm.posNoId = "";
  dataForm.positionId = "";
  dataForm.positionLevelId = "";
  dataForm.positionLineId = "";
  dataForm.positionPathSideId = "";
  dataForm.positionTypeId = "";
};
// ตำแหน่งเลขที่
const posNoOptions = ref<Object[]>([
  {
    label: "",
    value: "",
  },
]);
// ตำแหน่ง
const positionOptions = ref<Object[]>([
  {
    label: "",
    value: "",
  },
]);
// ด้าน/สาขา
const positionPathSideOptions = ref<Object[]>([
  {
    label: "",
    value: "",
  },
]);
// ประเภทตำแหน่ง
const positionTypeOptions = ref<Object[]>([
  {
    label: "",
    value: "",
  },
]);
// สายงาน
const positionLineOptions = ref<Object[]>([
  {
    label: "",
    value: "",
  },
]);
// ระดับ
const positionLevelOptions = ref<Object[]>([
  {
    label: "",
    value: "",
  },
]);

const selectedPosition = async (data: any) => {
  if (data.name == null && selected.value != data.keyId) {
    editDataStatus.value = true;
    selected.value = data.keyId;

    // posNo Options
    posNoOptions.value = [
      {
        label: data.positionNum,
        value: data.positionNumId,
      },
    ];
    dataForm.posNoId = data.positionNumId;

    // position Options
    positionOptions.value = [
      {
        label: data.positionName,
        value: data.positionNameId,
      },
    ];
    dataForm.positionId = data.positionNameId;

    // positionPathSide Options
    let positionPathSideArr: any = [];
    if (data.positionSideNameObj && data.positionSideNameObj != null) {
      data.positionSideNameObj.map((x: any) => {
        positionPathSideArr.push({
          label: x.Name,
          value: x.Id,
        });
      });
      positionPathSideOptions.value = positionPathSideArr;
      dataForm.positionPathSideId =
        positionPathSideArr.length > 1 || positionPathSideArr.length == 0
          ? ""
          : positionPathSideArr[0].value;
    }

    // positionType Options
    positionTypeOptions.value = [
      {
        label: data.positionType,
        value: data.positionTypeId,
      },
    ];
    dataForm.positionTypeId = data.positionTypeId;

    // positionLine Options
    positionLineOptions.value = [
      {
        label: data.positionLine,
        value: data.positionLineId,
      },
    ];
    dataForm.positionLineId = data.positionLineId;

    // positionLevel Options
    let positionLevelsArr: any = [];
    if (data.positionLevelObj != null) {
      data.positionLevelObj.map((x: any) => {
        positionLevelsArr.push({
          label: x.Name,
          value: x.Id,
        });
      });
      positionLevelOptions.value = positionLevelsArr;
      dataForm.positionLevelId =
        positionLevelsArr.length > 1 || positionLevelsArr.length == 0
          ? ""
          : positionLevelsArr[0].value;
      dataForm.positionLevelId = data.positionLevelObj[0].Id;
    }
  } else if (selected.value == data.keyId) {
    selected.value = "";
    dataForm.posNoId = "";
    dataForm.positionId = "";
    dataForm.positionLevelId = "";
    dataForm.positionLineId = "";
    dataForm.positionPathSideId = "";
    dataForm.positionTypeId = "";
  }
};

const checkPosition = (val: string) => {
  const num = placementPosition.value.findIndex((e: string) => e === val);
  return num;
};

watch(props, () => {
  expanded.value = [];
  const dataPersonal = props.personal;

  if (dataPersonal) {
    dataPersonal.map((data: any) => {
      personal.value = data;
    });
  }

  if (personal.value) {
    let findData: any = null;
    dataRespone.value.map((x: any) => {
      findData = findByPerson(x);
      if (findData != null) {
        selectedPosition(findData);
        for (let i = 3; i <= findData.keyId.length; i += 2) {
          expanded.value.push(findData.keyId.slice(0, i));
        }
      }
    });
  }
});

function findByPerson(element: any): any {
  if (
    element.positionNumId &&
    element.positionLineId === personal.value.positionLineId &&
    element.positionTypeId === personal.value.positionTypeId &&
    element.positionNumId === personal.value.posNoId &&
    (element.positionLevelObj === null ||
      element.positionLevelObj[0].Id === personal.value.positionLevelId)
  ) {
    return element;
  } else if (element.children) {
    var i;
    var result = null;
    for (i = 0; result == null && i < element.children.length; i++) {
      result = findByPerson(element.children[i]);
    }
    return result;
  }
  return null;
}
</script>

<template>
  <q-dialog v-model="props.modal" persistent>
    <q-card style="width: 900px; max-width: 80vw">
      <q-form ref="myFormPosition">
        <DialogHeader title="เลือกหน่วยงาน" :close="closeModal" />
        <q-separator />
        <q-card-section class="q-pa-sm bg-grey-1">
          <div class="row col-12 q-col-gutter-sm">
            <div class="col-xs-12 col-sm-7 row">
              <q-card flat bordered class="fit q-pa-sm">
                <q-scroll-area visible style="height: 70vh">
                  <q-input
                    outlined
                    dense
                    ref="filterRef"
                    v-model="search"
                    placeholder="ค้นหา"
                    class="q-mb-sm"
                  >
                    <template v-slot:append>
                      <q-icon name="mdi-magnify" />
                    </template>
                  </q-input>
                  <div class="q-pa-sm q-gutter-sm">
                    <q-tree
                      no-transition
                      dense
                      :nodes="treeData"
                      node-key="keyId"
                      :filter="search"
                      :no-results-label="notFound"
                      :no-nodes-label="noData"
                      :filter-method="myFilterMethod"
                      v-model:expanded="expanded"
                    >
                      <template v-slot:header-organization="prop">
                        <div class="col">
                          <div
                            class="row items-center q-px-xs q-pt-xs q-gutter-sm"
                          >
                            <!--แสดงชื่อแผนก พิมพ์ตัวหนา คลิกแล้วกาง/หุบ Tree-->
                            <div class="text-weight-medium">
                              {{ prop.node.organizationName }}
                            </div>
                            <q-badge
                              v-if="prop.node.totalPositionVacant > 0"
                              rounded
                              color="red"
                              outline
                              :label="prop.node.totalPositionVacant"
                            />

                            <q-space />
                          </div>
                          <div class="col items-center q-px-xs q-pt-xs">
                            <div class="text-weight-medium text-grey-7">
                              {{ prop.node.governmentCode }}
                              {{ prop.node.organizationShortName }}
                            </div>
                          </div>
                        </div>
                      </template>

                      <template v-slot:header-person="prop">
                        <q-item
                          clickable
                          :active="selected == prop.node.keyId"
                          @click="selectedPosition(prop.node)"
                          :disable="
                            prop.node.name != null ||
                            checkPosition(prop.node.positionNumId) != -1
                          "
                          active-class="my-list-link text-primary text-weight-medium"
                          class="row items-center text-dark q-py-xs q-pl-sm rounded-borders my-list"
                        >
                          <img
                            v-if="
                              prop.node.avatar == '' ||
                              prop.node.avatar ==
                                'https://cdn.quasar.dev/img/boy-avatar.png'
                            "
                            src="@/assets/avatar_user.jpg"
                            class="col-xs-1 col-sm-2"
                            style="
                              width: 28px;
                              height: 28px;
                              border-radius: 50%;
                            "
                          />
                          <img
                            v-else
                            :src="prop.node.avatar"
                            class="col-xs-1 col-sm-2"
                            style="
                              width: 28px;
                              height: 28px;
                              border-radius: 50%;
                            "
                          />
                          <!--=====ตำแหน่งว่าง สีแดง=====-->
                          <div
                            v-if="prop.node.name == null"
                            class="q-px-sm text-weight-medium text-red"
                          >
                            ว่าง
                          </div>
                          <!--=====หัวหน้า สีเขียว=====-->
                          <div v-else-if="prop.node.positionLeaderFlag">
                            <div
                              class="q-px-sm text-weight-medium text-primary"
                            >
                              {{ prop.node.name }}
                            </div>
                          </div>
                          <!--=====ลูกน้อง สีปกติ=====-->
                          <div v-else>
                            <div class="q-px-sm text-weight-medium">
                              {{ prop.node.name }}
                            </div>
                          </div>
                          <!--ต่อท้ายชื่อคน แสดงสีปกติ-->
                          <div class="q-pr-sm">
                            {{ prop.node.positionName }}
                          </div>
                          <div class="q-pr-sm">
                            {{ prop.node.positionNum }}
                          </div>
                          <div class="q-pr-sm">
                            {{ prop.node.positionLevel }}
                          </div>
                          <q-icon
                            v-if="prop.node.positionLeaderFlag"
                            class="q-mr-sm"
                            size="15px"
                            color="primary"
                            name="mdi-bookmark"
                          ></q-icon>

                          <q-space />
                        </q-item>
                      </template>
                    </q-tree>
                  </div>
                </q-scroll-area>
              </q-card>
            </div>
            <div class="col-xs-12 col-sm-5">
              <q-card flat bordered class="fit q-pa-sm">
                <q-scroll-area visible style="height: 70vh">
                  <div class="row col-12 q-col-gutter-xs">
                    <div class="col-xs-12 col-sm-12 col-md-12"></div>
                    <div class="col-xs-12 col-sm-12 col-md-12">
                      <datepicker
                        menu-class-name="modalfix"
                        v-model="dataForm.containDate"
                        :locale="'th'"
                        autoApply
                        :enableTimePicker="false"
                        week-start="0"
                      >
                        <template #year="{ year }">{{ year + 543 }}</template>
                        <template #year-overlay-value="{ value }">{{
                          parseInt(value + 543)
                        }}</template>
                        <template #trigger>
                          <q-input
                            class="full-width inputgreen cursor-pointer"
                            outlined
                            dense
                            :model-value="
                              date2Thai(new Date(dataForm.containDate))
                            "
                            :rules="[(val: string) => !!val || `${'วันที่รายงานตัว'}`]"
                            :label="`${'วันที่รายงานตัว'}`"
                            hide-bottom-space
                          >
                            <template v-slot:prepend>
                              <q-icon
                                name="event"
                                class="cursor-pointer"
                                style="color: var(--q-primary)"
                              >
                              </q-icon>
                            </template>
                          </q-input>
                        </template>
                      </datepicker>
                    </div>
                    <q-space />
                    <div class="col-xs-12 col-sm-12 col-md-12">
                      <q-select
                        class="full-width inputgreen cursor-pointer custom-input"
                        outlined
                        standout
                        dense
                        hide-bottom-space
                        lazy-rules
                        :options="posNoOptions"
                        v-model="dataForm.posNoId"
                        :label="`${'ตำแหน่งเลขที่'}`"
                        map-options
                      />
                    </div>
                    <div class="col-xs-12 col-sm-12 col-md-12">
                      <q-select
                        outlined
                        class="full-width inputgreen cursor-pointer custom-input"
                        standout
                        dense
                        hide-bottom-space
                        lazy-rules
                        :options="positionOptions"
                        v-model="dataForm.positionId"
                        :label="`${'ตำแหน่ง'}`"
                        map-options
                      />
                    </div>
                    <div class="col-xs-12 col-sm-12 col-md-12">
                      <q-select
                        outlined
                        class="full-width inputgreen cursor-pointer custom-input"
                        standout
                        dense
                        hide-bottom-space
                        lazy-rules
                        emit-value
                        :options="positionPathSideOptions"
                        v-model="dataForm.positionPathSideId"
                        :label="`${'ด้าน/สาขา'}`"
                        map-options
                      />
                    </div>

                    <div class="col-xs-12 col-sm-12 col-md-12">
                      <q-select
                        outlined
                        class="full-width inputgreen cursor-pointer custom-input"
                        standout
                        dense
                        hide-bottom-space
                        lazy-rules
                        :options="positionTypeOptions"
                        v-model="dataForm.positionTypeId"
                        :label="`${'ประเภทตำแหน่ง'}`"
                        map-options
                      />
                    </div>
                    <div class="col-xs-12 col-sm-12 col-md-12">
                      <q-select
                        outlined
                        class="full-width inputgreen cursor-pointer custom-input"
                        standout
                        dense
                        hide-bottom-space
                        lazy-rules
                        :options="positionLineOptions"
                        v-model="dataForm.positionLineId"
                        :label="`${'สายงาน'}`"
                        map-options
                      />
                    </div>
                    <div class="col-xs-12 col-sm-12 col-md-12">
                      <q-select
                        outlined
                        class="full-width inputgreen cursor-pointer custom-input"
                        standout
                        dense
                        lazy-rules
                        :options="positionLevelOptions"
                        v-model="dataForm.positionLevelId"
                        :label="`${'ระดับ'}`"
                        hide-bottom-space
                        :rules="[(val: string) => !!val || `${'กรุณาเลือกระดับ'}`]"
                        emit-value
                        map-options
                      />
                    </div>
                  </div>
                </q-scroll-area>
              </q-card>
            </div>
          </div>
        </q-card-section>

        <q-separator />
        <DialogFooter
          :editvisible="true"
          :validate="validateData"
          :save="saveAppoint"
          v-model:modalEdit="editDataStatus"
        />
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style scoped lang="scss">
.q-tree__node-header {
  padding: 0px;
  margin-top: 0px;
  border-radius: 4px;
  outline: 0;
}

.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>
