<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 Record from "@/modules/15_development/components/Record.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>(route.params.id.toLocaleString());
const tab = ref<string>("BasicInfo");

const status = ref<string>("ONGOING");
// function fetchDataProject(id: string) {
//   showLoader();
//   http
//     .get(config.API.developmentMainById(id))
//     .then((res) => {
//       const data: ResDataProject = res.data.result;
//       /** ข้อมูลเบื้องต้น*/
//       status.value = data.status ? data.status : "ONGOING";
//       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: any) => ({
//         groupTarget: e.groupTarget,
//         groupTargetSub: e.groupTargetSub,
//         positions: e.plannedGoalPositions.map((v: any) => ({
//           position: v.position,
//           posTypePlannedId: v.posTypePlannedId,
//           posLevelPlannedId: v.posLevelPlannedId,
//         })),
//         type: e.type ? e.type : null,
//         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.projectType = data.projectType;
//       store.formAddProject.projectCharacteristics = data.projectCharacteristics;
//       store.formAddProject.projectDay = data.projectDay;
//       store.formAddProject.projectNigth = data.projectNigth;
//       store.formAddProject.projectTechniques = data.projectTechniques;
//       store.formAddProject.projectModal = data.projectModal;

//       /** การติดตามผลดารประเมิน*/
//       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;

//       const provinces = data.provinces.map((e: any) => e.id);
//       const provincesId = [...provinces];
//       store.formAddProject.provinceIds = provincesId;

//       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 = Number(data.chance);
//       store.formAddProject.effects = Number(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.projectDay = store.formAddProject.projectDay
//         ? Number(store.formAddProject.projectDay)
//         : null;
//       store.formAddProject.projectNigth = store.formAddProject.projectNigth
//         ? Number(store.formAddProject.projectNigth)
//         : null;
//       store.formAddProject.projectModal = store.formAddProject.projectModal
//         ? Number(store.formAddProject.projectModal)
//         : null;

//       /** อื่นๆ*/
//       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();
//       }
//     });
//   }
// }

function getStatus(id: string) {
  showLoader();
  http
    .get(config.API.developmentMainStatus(id)) // change path
    .then((res) => {
      status.value = res.data.result.status;
      store.projectStatus = res.data.result.status;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

function onFinish(id: string) {
  dialogConfirm(
    $q,
    async () => {
      showLoader();
      http
        .get(config.API.developmentMainFinish(id)) // change path
        .then((res) => {
          getStatus(id);
          success($q, "บันทึกข้อมูลสำเร็จ");
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(() => {
          hideLoader();
        });
    },
    "ยืนยันการเสร็จสิ้นโครงการ",
    "ต้องการยืนยันการเสร็จสิ้นโครงการนี้ใช่หรือไม่?"
  );
}

onMounted(() => {
  projectId.value && getStatus(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
      v-if="status === 'ONGOING'"
      unelevated
      label="เสร็จสิ้นโครงการ"
      color="green"
      @click="onFinish(projectId)"
    >
      <q-tooltip>เสร็จสิ้นโครงการ</q-tooltip>
    </q-btn>
    <q-badge v-else outline color="primary" class="q-px-sm q-py-xs"
      >เสร็จสิ้นโครงการ</q-badge
    >
  </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-tab name="Record" 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-panel name="Record"> <Record /> </q-tab-panel>
      </q-tab-panels>
    </div>
  </q-card>
  <!-- </q-form> -->
</template>

<style scoped></style>
