<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";
import { useStructureTree } from "@/stores/structureTree";
import { useCounterMixin } from "@/stores/mixin";

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

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

/**
 * props
 */
const isChangeData = defineModel<boolean>("isChangeData", { required: true });
const props = defineProps({
  nextStep: { type: Function, required: true },
  onCheckChangeData: { type: Function, required: true },
});

const projectId = ref<string>(route.params.id.toLocaleString()); // เก็บ id
const checkRoutePermission = ref<boolean>(
  route.name == "developmentDetailPage"
); // check ชื่อ route

const formData = reactive<FormBasicinfo>({
  year: new Date().getFullYear(), //ปี
  projectName: "", //ชืื่อ
  reason: "", //หลักการเเละเหตุผล
  objective: "", //วัตถุประสงค์
  node: null, //หน่วยงาน/ส่วนราชการ
  nodeId: null, //id หน่วยงาน/ส่วนราชการ
  orgRevisionId: null,
});

const orgName = ref<string>(""); //ชื่อ หน่วยงาน/ส่วนราชการ
const node = ref<any[]>([]); //โครงสร้าง หน่วยงาน/ส่วนราชการ
const filter = ref<string>(""); //input ค้นหา
const expanded = ref<string[]>([]);
const nodeDnaId = ref<string>('');

/**
 * function fetch ข้อมูลเบื้องต้น
 * @param id ProjectId
 */
async function fetchData(id: string) {
  showLoader();
  await 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;
      formData.node = data.node;
      formData.orgRevisionId = data.revisionId;
      nodeDnaId.value = data.nodeDnaId

      const arrayExpanded = [
        data.root,
        data.child1,
        data.child2,
        data.child3,
        data.child4,
      ];
      expanded.value = arrayExpanded.filter((e) => e !== null).slice(0, -1);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
      isChangeData.value = false;
    });
}

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

/**
 * ดึงข้อมูลโครง้ราง
 */
async function fetchActive() {
  const dataTree = await fetchStructureTree(route.meta.Key as string, true);
  if (dataTree) {
    node.value = dataTree;
    await fetchData(projectId.value);
  }
}

/** function เลือกหน่วยงาน
 * @param data ข้อมูลทั้งหมดของ row
 */
function updateSelected(data: DataTree) {
  orgName.value = data.orgTreeName;
  formData.node = data.orgLevel;
  formData.nodeId = data.orgTreeId;
  formData.orgRevisionId = data.orgRevisionId;
  nodeDnaId.value = data.orgTreeDnaId
  props.onCheckChangeData();
}

/**
 * function ไปยัง Tab ค่อไป
 */
function onNextTab() {
  props.nextStep();
}

/**
 * เรียก function ไปใช่หน้าหลัก
 */
defineExpose({
  onSubmit,
});

/**
 * ดึงข้อมูลเมื่อโหลดหน้าเสร็จสิ้น
 */
onMounted(async () => {
  fetchActive();
});
</script>

<template>
  <q-form greedy @submit.prevent @validation-success="onNextTab">
    <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
              :readonly="checkRoutePermission"
              dense
              outlined
              v-model="filter"
              label="ค้นหา"
            >
              <template v-slot:append>
                <q-icon name="search" />
              </template>
            </q-input>
            <q-tree
              class="tree-container"
              dense
              :nodes="node"
              node-key="orgTreeId"
              label-key="labelName"
              v-model:expanded="expanded"
              :filter="filter.trim()"
              no-results-label="ไม่พบข้อมูลที่ค้นหา"
              no-nodes-label="ไม่มีข้อมูล"
              :style="
                checkRoutePermission ? 'pointer-events: none !important;' : ''
              "
            >
              <template v-slot:default-header="prop">
                <q-item
                  clickable
                  :disable="checkRoutePermission"
                  @click.stop="updateSelected(prop.node)"
                  :active="nodeDnaId === prop.node.orgTreeDnaId"
                  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
                  v-model="formData.year"
                  :locale="'th'"
                  autoApply
                  year-picker
                  :enableTimePicker="false"
                  :readonly="checkRoutePermission"
                  @update:model-value="props.onCheckChangeData()"
                >
                  <template #year="{ year }">{{ year + 543 }}</template>
                  <template #year-overlay-value="{ value }">{{
                    parseInt(value + 543)
                  }}</template>
                  <template #trigger>
                    <q-input
                      dense
                      :readonly="checkRoutePermission"
                      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"></div>
              <div class="col-xs-12 col-sm-12 col-md-12">
                <q-input
                  outlined
                  class="inputgreen"
                  dense
                  :readonly="checkRoutePermission"
                  v-model="formData.projectName"
                  label="ชื่อโครงการ/กิจกรรม/หลักสูตร"
                  rows="6"
                  type="textarea"
                  hide-bottom-space
                  @update:model-value="props.onCheckChangeData()"
                  :rules="[
            (val:string) =>
              !!val || `${'กรุณากรอกชื่อโครงการ/กิจกรรม/หลักสูตร'}`,
          ]"
                />
              </div>
              <div class="col-xs-12 col-sm-12 col-md-12">
                <q-input
                  outlined
                  class="inputgreen"
                  dense
                  :readonly="checkRoutePermission"
                  v-model="formData.reason"
                  label="หลักการและเหตุผล"
                  rows="6"
                  hide-bottom-space
                  type="textarea"
                  @update:model-value="props.onCheckChangeData()"
                />
              </div>
              <div class="col-xs-12 col-sm-12 col-md-12">
                <q-input
                  outlined
                  class="inputgreen"
                  dense
                  :readonly="checkRoutePermission"
                  v-model="formData.objective"
                  label="วัตถุประสงค์"
                  rows="6"
                  hide-bottom-space
                  type="textarea"
                  @update:model-value="props.onCheckChangeData()"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </q-card>

    <div class="text-center q-pa-sm" v-if="!checkRoutePermission">
      <q-btn
        disabled
        rounded
        label="ก่อนหน้า"
        icon="mdi-chevron-left"
        id="onSubmit"
        type="submit"
        color="public"
        class="q-mr-xs"
        style="width: 120px"
      >
      </q-btn>
      <q-btn
        rounded
        label="ถัดไป"
        icon-right="mdi-chevron-right"
        id="onSubmit"
        type="submit"
        color="public"
        class="q-ml-xs"
        style="width: 120px"
      >
      </q-btn>
    </div>
  </q-form>
</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>
