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

import type {
  ResDataProject,
  ResPlannedGoals,
  ResActualGoals,
  ResPeople,
} from "@/modules/15_development/interface/response/Main";

import BasicInfo from "@/modules/15_development/components/BasicInfo.vue";
import Target from "@/modules/15_development/components/Target.vue";
import ProjectDetail from "@/modules/15_development/components/ProjectDetail.vue";
import FollowResult from "@/modules/15_development/components/FollowResult.vue";
import Other from "@/modules/15_development/components/Other.vue";

import { useCounterMixin } from "@/stores/mixin";
import { useDevelopmentDataStore } from "@/modules/15_development/store/developmentStore";

const $q = useQuasar();
const router = useRouter();
const route = useRoute();
const store = useDevelopmentDataStore();
const {
  success,
  showLoader,
  hideLoader,
  messageError,
  dialogConfirm,
  dialogMessageNotify,
} = useCounterMixin();

const title = ref<string>(route.params.id ? "แก้ไข" : "เพิ่ม");
const projectId = ref<string | null>(
  route.params.id ? route.params.id.toLocaleString() : null
);
const tab = ref<string>("BasicInfo");

function fetchDataProject(id: string) {
  showLoader();
  http
    .get(config.API.developmentMainById(id))
    .then((res) => {
      const data: ResDataProject = res.data.result;
      console.log(data);
      /** ข้อมูลเบื้องต้น*/
      store.formAddProject.year = data.year;
      store.formAddProject.projectName = data.projectName;
      store.formAddProject.reason = data.reason;
      store.formAddProject.objective = data.objective;

      /**เป้าหมาย*/
      const plannedGoals = data.plannedGoals.map((e: ResPlannedGoals) => ({
        groupTarget: e.groupTarget,
        groupTargetSub: e.groupTargetSub,
        position: e.position,
        posTypePlannedId: e.posTypePlannedId,
        posLevelPlannedId: e.posLevelPlannedId,
        type: e.type,
        amount: e.amount,
      }));
      const plannedPeoples = data.plannedPeoples.map((e: ResPeople) => ({
        groupTarget: e.groupTarget,
        amount: e.amount,
      }));
      store.formAddProject.plannedGoals = plannedGoals;
      store.formAddProject.plannedPeoples = plannedPeoples;

      const actualGoals = data.actualGoals.map((e: ResActualGoals) => ({
        groupTarget: e.groupTarget,
        groupTargetSub: e.groupTargetSub,
        position: e.position,
        posTypeActualId: e.posTypeActualId,
        posLevelActualId: e.posLevelActualId,
        type: e.type,
        amount: e.amount,
      }));
      const actualPeoples = data.actualPeoples.map((e: ResPeople) => ({
        groupTarget: e.groupTarget,
        amount: e.amount,
      }));
      store.formAddProject.actualGoals = actualGoals;
      store.formAddProject.actualPeoples = actualPeoples;

      /** การติดตามผลดารประเมิน*/
      store.formAddProject.metricType = data.metricType;
      store.formAddProject.indicators = data.indicators;
      store.formAddProject.target = data.target;
      store.formAddProject.calculation = data.calculation;
      store.formAddProject.measuRement = data.measuRement;
      store.formAddProject.results = data.results;
      store.formAddProject.obstacles = data.obstacles;
      store.formAddProject.suggestions = data.suggestions;
      store.formAddProject.project = data.project;
      store.formAddProject.isPassAllocate = data.isPassAllocate;
      store.formAddProject.isPassNoAllocate = data.isPassNoAllocate;
      store.formAddProject.isNoPass = data.isNoPass;
      store.formAddProject.isBudget = data.isBudget;
      store.formAddProject.isOutBudget = data.isOutBudget;

      /** อื่นๆ*/
      store.formAddProject.dateStart = data.dateStart;
      store.formAddProject.dateEnd = data.dateEnd;
      store.formAddProject.totalDate = data.totalDate;
      store.formAddProject.address = data.address;
      store.formAddProject.provinceId = data.provinceId;
      store.formAddProject.budget = data.budget;
      store.formAddProject.accept = data.accept;
      store.formAddProject.receive = data.receive;
      store.formAddProject.approved = data.approved;
      store.formAddProject.budgetPay = data.budgetPay;
      store.formAddProject.issues = data.issues;
      store.formAddProject.chance = data.chance;
      store.formAddProject.effects = data.effects;
      store.formAddProject.riskLevel = data.riskLevel;
      store.formAddProject.riskManagement = data.riskManagement;
      store.formAddProject.expect = data.expect;
      store.formAddProject.topicAcademic = data.topicAcademic;
      store.formAddProject.addressAcademic = data.addressAcademic;
      store.formAddProject.provinceActualId = data.provinceActualId;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      setTimeout(() => {
        hideLoader();
      }, 1000);
    });
}

function onSubmit() {
  if (store.formAddProject.projectName === "" && tab.value !== "BasicInfo") {
    dialogMessageNotify($q, "ชื่อโครงการ/กิจกรรม/หลักสูตร");
    tab.value = "BasicInfo";
  } else {
    dialogConfirm($q, async () => {
      showLoader();
      /** การติดตามผลดารประเมิน*/
      if (store.formAddProject.project === "OFFER") {
        store.formAddProject.isBudget = false;
        store.formAddProject.isOutBudget = false;
      } else {
        store.formAddProject.isPassAllocate = false;
        store.formAddProject.isPassNoAllocate = false;
        store.formAddProject.isNoPass = false;
      }

      /** อื่นๆ*/
      store.formAddProject.totalDate = Number(store.formAddProject.totalDate);
      store.formAddProject.accept =
        typeof store.formAddProject.accept === "string"
          ? Number(store.formAddProject.accept.replace(/,/g, ""))
          : store.formAddProject.accept;
      store.formAddProject.receive =
        typeof store.formAddProject.receive === "string"
          ? Number(store.formAddProject.receive.replace(/,/g, ""))
          : store.formAddProject.receive;
      store.formAddProject.approved =
        typeof store.formAddProject.approved === "string"
          ? Number(store.formAddProject.approved.replace(/,/g, ""))
          : store.formAddProject.approved;
      store.formAddProject.budgetPay =
        typeof store.formAddProject.budgetPay === "string"
          ? Number(store.formAddProject.budgetPay.replace(/,/g, ""))
          : store.formAddProject.budgetPay;

      const url = projectId.value
        ? config.API.developmentMainById(projectId.value)
        : config.API.developmentMain;
      const method = projectId.value ? "put" : "post";
      try {
        const res = await http[method](url, store.formAddProject);
        success($q, "บันทึกข้อมูลสำเร็จ");
        !projectId.value && router.push(`/development/${res.data.result}`);
        projectId.value && fetchDataProject(projectId.value);
      } catch (e) {
        messageError($q, e);
      } finally {
        hideLoader();
      }
    });
  }
}

onMounted(() => {
  projectId.value && fetchDataProject(projectId.value);
});

onUnmounted(() => {
  store.clearFormAddProject();
});
</script>
<template>
  <q-form greedy @submit.prevent @validation-success="onSubmit">
    <div class="toptitle text-dark col-12 row items-center">
      <q-btn
        flat
        round
        dense
        class="q-mr-sm"
        icon="mdi-arrow-left"
        color="primary"
        @click="router.push('/development')"
      />
      {{ `${title}รายการโครงการ/หลักสูตรการฝึกอบรม` }}
      <q-space />
      <q-btn
        dense
        unelevated
        label="บันทึก"
        id="onSubmit"
        type="submit"
        color="public"
        class="q-px-md"
      >
        <q-tooltip>บันทึกข้อมูล</q-tooltip>
      </q-btn>
      <!-- <q-btn unelevated label="บันทึก" color="public" @click="onSubmit">
        <q-tooltip>บันทึกข้อมูล</q-tooltip>
      </q-btn> -->
    </div>

    <q-card flat bordered class="col-12">
      <q-tabs
        v-model="tab"
        dense
        align="left"
        inline-label
        class="rounded-borders"
        indicator-color="primary"
        active-bg-color="teal-1"
        active-class="text-primary"
      >
        <q-tab name="BasicInfo" label="ข้อมูลเบื้องต้น" />
        <q-tab name="Target" label="เป้าหมาย" />
        <q-tab name="ProjectDetail" label="ลักษณะโครงการ" />
        <q-tab name="FollowResult" label="การติดตามการประเมินผล" />
        <q-tab name="Other" label="อื่นๆ" />
      </q-tabs>
      <q-separator />
      <div class="q-pa-sm" style="padding: 0px">
        <q-tab-panels v-model="tab" animated>
          <q-tab-panel style="padding: 0px" name="BasicInfo">
            <BasicInfo />
          </q-tab-panel>
          <q-tab-panel name="Target"> <Target /></q-tab-panel>
          <q-tab-panel name="ProjectDetail"> <ProjectDetail /> </q-tab-panel>
          <q-tab-panel name="FollowResult"> <FollowResult /> </q-tab-panel>
          <q-tab-panel name="Other"> <Other /> </q-tab-panel>
        </q-tab-panels>
      </div>
    </q-card>
  </q-form>
</template>

<style scoped></style>
