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

/** importType*/
import type { FormBasicinfo } from "@/modules/15_development/interface/request/Main";
import type { DataTree } from "@/modules/15_development/interface/response/Main";

/** importStore*/
import { useCounterMixin } from "@/stores/mixin";

/** use*/
const $q = useQuasar();
const route = useRoute();
const mixin = useCounterMixin();
const { dialogConfirm, showLoader, hideLoader, messageError, success } = mixin;

const projectId = ref<string>(route.params.id.toLocaleString());

const formData = reactive<FormBasicinfo>({
  year: new Date().getFullYear(),
  projectName: "",
  reason: "",
  objective: "",
  node: null,
  nodeId: null,
  orgRevisionId: null,
});

const orgName = ref<string>("");
const node = ref<any>([]);
const filter = ref<string>("");
const expanded = ref<string[]>([]);

/**
 * function fetch ข้อมูลเบื้องต้น
 * @param id ProjectId
 */
function fetchData(id: string) {
  showLoader();
  http
    .get(config.API.developmentMainTab("tab1", id))
    .then(async (res) => {
      const data = res.data.result;
      formData.year = data.year;
      formData.reason = data.reason;
      formData.projectName = data.projectName;
      formData.objective = data.objective;
      formData.nodeId = data.nodeId;

      if (node.value && formData?.nodeId) {
        const nodeTree = await searchAndReplace(node.value, formData?.nodeId);
        if (nodeTree) {
          expanded.value = [];
          const parts = nodeTree?.orgName.split("/");
          for (let i = 1; i < parts.length; i++) {
            const arrangedParts = parts[i];
            expanded.value.push(arrangedParts);
          }
          updateSelected(nodeTree);
        }
      }
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** function บันทึกข้อมูล*/
function onSubmit() {
  dialogConfirm($q, () => {
    showLoader();
    http
      .put(config.API.developmentMainTab("tab1", projectId.value), formData)
      .then(() => {
        fetchData(projectId.value);
        success($q, "บันทึกข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/** function fetch หา Id หน่วยงานที่ Active*/
function fetchActive() {
  showLoader();
  http
    .get(config.API.activeOrganization)
    .then((res) => {
      const data = res.data.result;
      fetchTree(data.activeId);
    })
    .catch((err) => {
      messageError($q, err);
      hideLoader();
    });
}

/**
 * function fetch โครงสร้างปจุบัน
 * @param id โครงสร้างปจุบัน
 */
function fetchTree(id: string) {
  showLoader();
  http
    .get(config.API.orgByid(id.toString()))
    .then((res) => {
      const data = res.data.result;
      node.value = data;
      fetchData(projectId.value);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** function เลือกหน่วยงาน*/
function updateSelected(data: DataTree) {
  orgName.value = data.orgTreeName;
  formData.node = data.orgLevel;
  formData.nodeId = data.orgTreeId;
  formData.orgRevisionId = data.orgRevisionId;
}

/**
 * function หาหน่วยงานที่รับผิดชอบ
 * @param orgTreeData ข้อมูล  nodeTree
 * @param treeId tree ID
 */
async function searchAndReplace(orgTreeData: any, treeId: string | null) {
  if (orgTreeData) {
    for (let orgTree of orgTreeData) {
      if (orgTree.orgTreeId === treeId) {
        return orgTree;
      }
      let foundOrg: any = await searchAndReplace(orgTree.children, treeId);
      if (foundOrg) {
        return foundOrg;
      }
    }
    return false;
  }
}

onMounted(async () => {
  fetchActive();
});
</script>

<template>
  <q-form greedy @submit.prevent @validation-success="onSubmit">
    <q-card bordered class="col-12 row caedNone">
      <div class="col-xs-12 col-sm-3 row">
        <div class="col-12 row no-wrap">
          <div class="col-12 q-py-sm q-px-sm q-gutter-sm">
            <div class="text-subtitle2 text-bold">หน่วยงาน/ส่วนราชการ</div>
            <q-input dense outlined v-model="filter" label="ค้นหา">
              <template v-slot:append>
                <q-icon
                  v-if="filter !== ''"
                  name="clear"
                  class="cursor-pointer"
                  @click="filter = ''"
                />
                <q-icon v-else name="search" color="grey-5" />
              </template>
            </q-input>
            <q-tree
              class="tree-container"
              dense
              :nodes="node"
              node-key="orgTreeName"
              label-key="labelName"
              v-model:expanded="expanded"
              :filter="filter"
              no-results-label="ไม่พบข้อมูลที่ค้นหา"
              no-nodes-label="ไม่มีข้อมูล"
            >
              <template v-slot:default-header="prop">
                <q-item
                  clickable
                  @click.stop="updateSelected(prop.node)"
                  :active="formData.nodeId === prop.node.orgTreeId"
                  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 text-grey-8">
                      {{ prop.node.orgCode == null ? null : prop.node.orgCode }}
                      {{
                        prop.node.orgTreeShortName == null
                          ? null
                          : prop.node.orgTreeShortName
                      }}
                    </div>
                  </div>
                </q-item>
              </template>
            </q-tree>
          </div>

          <div class="col-12 row">
            <q-separator :vertical="!$q.screen.lt.md" />
          </div>
        </div>
      </div>
      <div class="col-xs-12 col-sm-9 q-pa-md row">
        <div class="col-12 row">
          <div class="col-12">
            <div class="row col-12 q-col-gutter-md q-pa-md">
              <div class="col-xs-6 col-sm-2 col-md-2">
                <datepicker
                  menu-class-name="modalfix"
                  v-model="formData.year"
                  :locale="'th'"
                  autoApply
                  year-picker
                  :enableTimePicker="false"
                >
                  <template #year="{ year }">{{ year + 543 }}</template>
                  <template #year-overlay-value="{ value }">{{
                    parseInt(value + 543)
                  }}</template>
                  <template #trigger>
                    <q-input
                      dense
                      lazy-rules
                      outlined
                      class="inputgreen"
                      :model-value="Number(formData.year) + 543"
                      :label="`${'ปีงบประมาณ'}`"
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          style="color: var(--q-primary)"
                        >
                        </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>
              <div class="col-xs-10 col-sm-10 col-md-10">
                <q-input
                  dense
                  outlined
                  class="inputgreen"
                  v-model="orgName"
                  inputgreen
                  label="ชื่อหน่วยงานที่รับผิดชอบ"
                  hide-bottom-space
                  lazy-rules
                  readonly
                />
              </div>
              <div class="col-xs-12 col-sm-12 col-md-12">
                <q-input
                  outlined
                  class="inputgreen"
                  dense
                  v-model="formData.projectName"
                  label="ชื่อโครงการ/กิจกรรม/หลักสูตร"
                  rows="6"
                  type="textarea"
                  hide-bottom-space
                  :rules="[
            (val:string) =>
              !!val || `${'กรุณากรอกชื่อโครงการ/กิจกรรม/หลักสูตร'}`,
          ]"
                />
              </div>
              <div class="col-xs-12 col-sm-12 col-md-12">
                <q-input
                  outlined
                  class="inputgreen"
                  dense
                  v-model="formData.reason"
                  label="หลักการและเหตุผล"
                  rows="6"
                  hide-bottom-space
                  type="textarea"
                />
              </div>
              <div class="col-xs-12 col-sm-12 col-md-12">
                <q-input
                  outlined
                  class="inputgreen"
                  dense
                  v-model="formData.objective"
                  label="วัตถุประสงค์"
                  rows="6"
                  hide-bottom-space
                  type="textarea"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </q-card>

    <q-separator />
    <div class="text-right q-pa-sm">
      <q-btn
        dense
        unelevated
        label="บันทึก"
        id="onSubmit"
        type="submit"
        color="public"
        class="q-px-md"
      >
        <q-tooltip>บันทึกข้อมูล</q-tooltip>
      </q-btn>
    </div>
  </q-form>

  <!-- <DialogSelectAgency
    v-model:modal="modalDialogSelect"
    @update:updateAgency="updateAgency"
  /> -->
</template>

<style scoped>
.tree-container {
  overflow: auto;
  height: 70vh;
  border: 1px solid #e6e6e7;
  border-radius: 10px;
}

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