<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { useQuasar } from "quasar";
import { useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";

/**importType*/
import type {
  DataOptionTechnique,
  FormProjectDetail,
} from "@/modules/15_development/interface/index/Main";
import type { DataStrategic } from "@/modules/15_development/interface/response/Main";

import { useDevelopmentDataStore } from "@/modules/15_development/store/developmentStore";
import http from "@/plugins/http";
import config from "@/app.config";

const $q = useQuasar();
const store = useDevelopmentDataStore();
const route = useRoute();
const projectId = ref<string>(route.params.id.toLocaleString());
const { showLoader, hideLoader, dialogConfirm, messageError, success } =
  useCounterMixin();

const projectTypeOp = ref<String[]>([
  "โครงการตามยุทธศาสตร์",
  "โครงการตามภารกิจประจำของหน่วยงาน",
  "โครงการใหม่",
  "โครงการต่อเนื่อง",
]);

const projectTechniquesOp = ref<DataOptionTechnique[]>([
  { value: "การอบรม", label: "การอบรม" },
  { value: "การประชุม", label: "การประชุม" },
  { value: "การสัมมนา", label: "การสัมมนา" },
  { value: "การศึกษาดูงาน", label: "การศึกษาดูงาน" },
  { value: "การสัมมนาทางวิชาการ", label: "การสัมมนาทางวิชาการ" },
  { value: "การสัมมนาเชิงปฏิบัติการ", label: "การสัมมนาเชิงปฏิบัติการ" },
  { value: "การบรรยายพิเศษ", label: "การบรรยายพิเศษ" },
  { value: "การฝึกศึกษา", label: "การฝึกศึกษา" },
]);

const formData = reactive<FormProjectDetail>({
  developmentProjectTypes: [],
  projectModal: null,
  isBackPlanned: false,
  isHoldPlanned: false,
  projectDayBackPlanned: null,
  projectDayHoldPlanned: null,
  projectNigthHoldPlanned: null,
  developmentProjectTechniquePlanneds: [],
  isBackActual: false,
  isHoldActual: false,
  projectDayBackActual: null,
  projectDayHoldActual: null,
  projectNigthHoldActual: null,
  developmentProjectTechniqueActuals: [],
  projectModalActual: null,
  projectModalPlanned: null,
  strategyChildPlannedId: null, //id ยุทธศาสตร์เป้าหมายตามแผน
  strategyChildPlannedNode: 0, //node ยุทธศาสตร์เป้าหมายตามแผน
  strategyChildActualId: null, //id ยุทธศาสตร์เป้าหมายตามจริง
  strategyChildActualNode: 0, //node ยุทธศาสตร์เป้าหมายตามจริง
});

const nodes = ref<any>([]);
const filter = ref<string>("");
const filter2 = ref<string>("");
const notFound = ref<string>("ไม่พบข้อมูลที่ค้นหา");
const noData = ref<string>("ไม่มีข้อมูล");
const expanded = ref<Array<string | null>>([]);
const expanded2 = ref<Array<string | null>>([]);
function fetchData() {
  showLoader();
  http
    .get(config.API.developmentMainTab("tab3", projectId.value))
    .then((res) => {
      const data = res.data.result;

      formData.developmentProjectTypes = data.developmentProjectTypes;
      formData.projectModal = data.projectModal;
      formData.isBackPlanned = data.isBackPlanned;
      formData.isHoldPlanned = data.isHoldPlanned;
      formData.projectDayBackPlanned = data.projectDayBackPlanned;
      formData.projectDayHoldPlanned = data.projectDayHoldPlanned;
      formData.projectNigthHoldPlanned = data.projectNigthHoldPlanned;
      formData.developmentProjectTechniquePlanneds =
        data.developmentProjectTechniquePlanneds;
      formData.isBackActual = data.isBackActual;
      formData.isHoldActual = data.isHoldActual;
      formData.projectDayBackActual = data.projectDayBackActual;
      formData.projectDayHoldActual = data.projectDayHoldActual;
      formData.projectNigthHoldActual = data.projectNigthHoldActual;
      formData.developmentProjectTechniqueActuals =
        data.developmentProjectTechniqueActuals;
      formData.projectModalPlanned = data.projectModalPlanned;
      expanded.value = [
        data.strategyChild1Planned,
        data.strategyChild2Planned,
        data.strategyChild3Planned,
        data.strategyChild4Planned,
        data.strategyChild5Planned,
      ];
      expanded2.value = [
        data.strategyChild1Actual,
        data.strategyChild2Actual,
        data.strategyChild3Actual,
        data.strategyChild4Actual,
        data.strategyChild5Actual,
      ];
      const filteredArray = expanded.value.filter((item) => item !== null);
      const filteredArray2 = expanded2.value.filter((item) => item !== null);
      const lastItem = filteredArray[filteredArray.length - 1];
      const lastItem2 = filteredArray2[filteredArray2.length - 1];
      formData.strategyChildPlannedId =
        lastItem !== undefined ? lastItem : null;
      formData.strategyChildPlannedNode =
        lastItem !== undefined ? filteredArray.length : null;
      formData.strategyChildActualId =
        lastItem2 !== undefined ? lastItem2 : null;
      formData.strategyChildActualNode =
        lastItem2 !== undefined ? filteredArray2.length : null;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function fetchTree() {
  showLoader();
  http
    .get(config.API.devStrategy)
    .then((res) => {
      const data = res.data.result;
      nodes.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

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

function updateSelected(data: DataStrategic, type: string) {
  if (type === "1") {
    formData.strategyChildPlannedId = data.id;
    formData.strategyChildPlannedNode = data.level;
  } else if (type === "2") {
    formData.strategyChildActualId = data.id;
    formData.strategyChildActualNode = data.level;
  }
}

onMounted(() => {
  fetchData();
  fetchTree();
});
</script>

<template>
  <q-form greedy @submit.prevent @validation-success="onSubmit">
    <div class="row">
      <div class="col-12">
        <q-select
          dense
          outlined
          v-model="formData.developmentProjectTypes"
          :options="projectTypeOp"
          label="ประเภทโครงการ"
          option-label="name"
          option-value="id"
          emit-value
          map-options
          multiple
        />
      </div>
    </div>

    <q-card bordered class="col-12 q-my-sm">
      <div
        class="col-xs-12 col-sm-12 text-weight-medium bg-grey-3 q-py-xs q-px-md"
      >
        ความสอดคล้องหรือเชื่อมโยงกับยุทธศาสตร์/แผน
      </div>
      <q-separator />

      <q-card-section>
        <div class="row col-12 q-col-gutter-sm">
          <div class="col-6">
            <q-card bordered class="col-12">
              <div
                class="col-xs-12 col-sm-12 text-weight-medium bg-grey-1 q-py-xs q-px-md"
              >
                ยุทธศาสตร์/แผน
              </div>
              <q-separator />

              <q-card-section class="q-pa-sm">
                <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
                  dense
                  :nodes="nodes"
                  selected-color="primary"
                  node-key="id"
                  label-key="id"
                  :filter="filter"
                  :no-results-label="notFound"
                  :no-nodes-label="noData"
                  v-model:expanded="expanded"
                >
                  <template v-slot:default-header="prop">
                    <q-item
                      clickable
                      @click.stop="updateSelected(prop.node, '1')"
                      :active="formData.strategyChildPlannedId == prop.node.id"
                      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.name }}
                        </div>
                      </div>
                    </q-item>
                  </template>
                </q-tree>
              </q-card-section>
            </q-card>
          </div>
          <div class="col-6">
            <q-card bordered class="col-12">
              <div
                class="col-xs-12 col-sm-12 text-weight-medium bg-grey-1 q-py-xs q-px-md"
              >
                ยุทธศาสตร์/แผน
              </div>
              <q-separator />

              <q-card-section class="q-pa-sm">
                <q-input dense outlined v-model="filter2" label="ค้นหา">
                  <template v-slot:append>
                    <q-icon
                      v-if="filter2 !== ''"
                      name="clear"
                      class="cursor-pointer"
                      @click="filter2 = ''"
                    />
                    <q-icon v-else name="search" color="grey-5" />
                  </template>
                </q-input>
                <q-tree
                  dense
                  :nodes="nodes"
                  node-key="id"
                  label-key="id"
                  :filter="filter2"
                  :no-results-label="notFound"
                  :no-nodes-label="noData"
                  v-model:expanded="expanded2"
                >
                  <template v-slot:default-header="prop">
                    <q-item
                      clickable
                      @click.stop="updateSelected(prop.node, '2')"
                      :active="formData.strategyChildActualId == prop.node.id"
                      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.name }}
                        </div>
                      </div>
                    </q-item>
                  </template>
                </q-tree>
              </q-card-section>
            </q-card>
          </div>
        </div>
      </q-card-section>
    </q-card>

    <q-card bordered class="col-12 q-my-sm">
      <div
        class="col-xs-12 col-sm-12 text-weight-medium bg-grey-3 q-py-xs q-px-md"
      >
        รูปแบบโครงการ
      </div>
      <q-separator />

      <q-card-section>
        <div class="row col-12 q-col-gutter-sm">
          <div class="col-6 q-col-gutter-sm">
            <div class="col-12 text-bold">รูปแบบโครงการตามแผน</div>

            <div class="row col-12 q-col-gutter-sm">
              <div class="col-12 col-md-3">
                <q-checkbox
                  :disable="store.projectStatus === 'FINISH'"
                  keep-color
                  color="primary"
                  dense
                  value="GO_BLACK"
                  label="ไป-กลับ"
                  v-model="formData.isBackPlanned"
                ></q-checkbox>
              </div>
              <div class="col-12 col-md-4">
                <q-input
                  :readonly="store.projectStatus === 'FINISH'"
                  dense
                  outlined
                  v-model="formData.projectDayBackPlanned"
                  label="จำนวน (วัน)"
                  mask="#"
                  reverse-fill-mask
                />
              </div>
            </div>
            <div class="row col-12 q-col-gutter-sm">
              <div class="col-12 col-md-3">
                <q-checkbox
                  :disable="store.projectStatus === 'FINISH'"
                  keep-color
                  color="primary"
                  dense
                  value="HOLD"
                  label="พักค้าง"
                  v-model="formData.isHoldPlanned"
                ></q-checkbox>
              </div>
              <div class="col-12 col-md-4">
                <q-input
                  :readonly="store.projectStatus === 'FINISH'"
                  dense
                  outlined
                  v-model="formData.projectDayHoldPlanned"
                  label="จำนวน (วัน)"
                  mask="#"
                  reverse-fill-mask
                />
              </div>
              <div class="col-12 col-md-4">
                <q-input
                  :readonly="store.projectStatus === 'FINISH'"
                  dense
                  outlined
                  v-model="formData.projectNigthHoldPlanned"
                  label="จำนวน (คืน)"
                  mask="#"
                  reverse-fill-mask
                />
              </div>
            </div>

            <div class="col-12 q-py-md">
              <q-label class="q-mb-sm">เทคนิควิธีการที่ใช้ในการพัฒนา</q-label>
              <q-option-group
                :disable="store.projectStatus === 'FINISH'"
                keep-color
                color="primary"
                dense
                v-model="formData.developmentProjectTechniquePlanneds"
                :options="projectTechniquesOp"
                type="checkbox"
              />
            </div>

            <div class="col-12 col-sm-6 col-md-4">
              <q-input
                :disable="store.projectStatus === 'FINISH'"
                dense
                outlined
                v-model="formData.projectModalPlanned"
                label="จำนวน (รุ่น)"
                mask="#"
                reverse-fill-mask
              />
            </div>
          </div>

          <div
            v-if="store.projectStatus === 'FINISH'"
            class="col-6 q-col-gutter-sm"
          >
            <div class="col-12 text-bold">รูปแบบโครงการตามจริง</div>

            <div class="row col-12 q-col-gutter-sm">
              <div class="col-md-3">
                <q-checkbox
                  keep-color
                  color="primary"
                  dense
                  value="GO_BLACK"
                  label="ไป-กลับ"
                  v-model="formData.isBackActual"
                ></q-checkbox>
              </div>
              <div class="col-12 col-md-4">
                <q-input
                  dense
                  outlined
                  v-model="formData.projectDayBackActual"
                  label="จำนวน (วัน)"
                  mask="#"
                  reverse-fill-mask
                />
              </div>
            </div>
            <div class="row col-12 q-col-gutter-sm">
              <div class="col-12 col-md-3">
                <q-checkbox
                  keep-color
                  color="primary"
                  dense
                  value="HOLD"
                  label="พักค้าง"
                  v-model="formData.isHoldActual"
                ></q-checkbox>
              </div>
              <div class="col-12 col-md-4">
                <q-input
                  dense
                  outlined
                  v-model="formData.projectDayHoldActual"
                  label="จำนวน (วัน)"
                  mask="#"
                  reverse-fill-mask
                />
              </div>
              <div class="col-12 col-md-4">
                <q-input
                  dense
                  outlined
                  v-model="formData.projectNigthHoldActual"
                  label="จำนวน (คืน)"
                  mask="#"
                  reverse-fill-mask
                />
              </div>
            </div>
            <div class="col-12 q-py-md">
              <q-label class="q-mb-sm">เทคนิควิธีการที่ใช้ในการพัฒนา</q-label>
              <q-option-group
                keep-color
                color="primary"
                dense
                v-model="formData.developmentProjectTechniqueActuals"
                :options="projectTechniquesOp"
                type="checkbox"
              />
            </div>
            <div class="col-12 col-sm-6 col-md-4">
              <q-input
                dense
                outlined
                v-model="formData.projectModalActual"
                label="จำนวน (รุ่น)"
                mask="#"
                reverse-fill-mask
              />
            </div>
          </div>
        </div>
      </q-card-section>
    </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>
</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>
