<script setup lang="ts">
import { ref, defineAsyncComponent, watch, onMounted } from "vue";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar } from "quasar";
import { useRoute, useRouter } from "vue-router";
import { useProbationDataStore } from "@/modules/05_placement/storeProbation";
import http from "@/plugins/http";
import config from "@/app.config";
import genReport from "@/plugins/genreport";

const Header = defineAsyncComponent(
  () =>
    import(
      "@/modules/05_placement/components/probation/FormEvaluation/Header.vue"
    )
);
const FormSaveResult = defineAsyncComponent(
  () =>
    import(
      "@/modules/05_placement/components/probation/FormEvaluation/FormSaveResult.vue"
    )
);

const router = useRouter();
const route = useRoute();
const checkRoutePermisson = ref<boolean>(route.name == "probationFormDetail");
const $q = useQuasar();
const probationStore = useProbationDataStore();
const { fecthdataAssign } = probationStore;
const mixin = useCounterMixin();
const { showLoader, hideLoader, messageError } = mixin;
const assignId = ref<string>(route.params.form.toString());
const personalId = ref<string>(route.params.personalId.toString());

const tab = ref<string>("save1");
const dataArrayNumber = ref<number>();
const dataRole = ref<string>("mentor");

/** get ข้อมูล มอบหมาย
 * @param id person id
 */
async function fecthAssign(id: string) {
  showLoader();
  await http
    .get(config.API.formevaluate(id))
    .then(async (res: any) => {
      await fecthdataAssign(res.data.result);
      dataArrayNumber.value = 1;
    })
    .catch((e: any) => {
      // messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * เปลี่ยน tab
 * @param tabVal type
 */
function changeTab(tabVal: string) {
  tab.value = tabVal;
  dataArrayNumber.value = Number(tabVal.charAt(4));
}

/** download file */
async function FileDownload(type: string) {
  let numTab = probationStore.evaluate.find(
    (e: any) => e.no === dataArrayNumber.value
  );
  //ผู้ดูเเล
  if (dataRole.value == "mentor") {
    showLoader();
    await http
      .get(config.API.reportEvaluateRecord1(type, numTab.id))
      .then(async (res) => {
        const data = res.data.result;
        await genReport(
          data,
          `แบบบันทึกผล(ผู้ดูเเล)_${probationStore.person.name}_ครั้งที่${numTab.no}`,
          type
        );
      })
      .catch(async (e) => {
        messageError($q, JSON.parse(await e.response.data.text()));
      })
      .finally(() => {
        hideLoader();
      });
  } else {
    //ผุ้บังคับ
    showLoader();
    await http
      .get(config.API.reportEvaluateRecord1(type, numTab.id))
      .then(async (res) => {
        const data = res.data.result;
        await genReport(
          data,
          `แบบบันทึกผล(ผู้บังคับบัญชา)_${probationStore.person.name}_ครั้งที่${numTab.no}`,
          type
        );
      })
      .catch(async (e) => {
        messageError($q, JSON.parse(await e.response.data.text()));
      })
      .finally(() => {
        hideLoader();
      });
  }
}

/** ไปหน้า page add */
function addData() {
  router.push(
    `/probation/detail/addresult/${personalId.value}/${assignId.value}`
  );
}

onMounted(async () => {
  await fecthAssign(assignId.value);
});
</script>

<template>
  <Header
    v-if="probationStore.tabs.length > 0"
    :change-tab="changeTab"
    :add-data="addData"
    :loop="probationStore.tabs.length"
    :FileDownload="FileDownload"
    :checkPermission="probationStore?.dataPermissions?.tab2?.isEdit as boolean"
    :is-max="probationStore.tabs.length === 3"
  />

  <q-tab-panels
    v-model="tab"
    animated
    swipeable
    vertical
    transition-prev="jump-up"
    transition-next="jump-up"
    v-if="probationStore.tabs.length > 0"
    class="mt"
  >
    <q-tab-panel
      v-for="item in probationStore.evaluate"
      :name="`save${item.no}`"
      :key="item.no"
    >
      <FormSaveResult
        :fecthAssign="fecthAssign"
        :tab="tab"
        :data="probationStore.evaluate.find((x: any) => x.no === dataArrayNumber)"
        action="edit"
      />
    </q-tab-panel>
  </q-tab-panels>

  <div class="q-gutter-md" v-else-if="probationStore.tabs.length == 0">
    <div class="flex justify-center items-center q-my-md q-gutter-md">
      <q-btn
        v-if="!checkRoutePermisson"
        outline
        color="primary"
        label="สร้างแบบบันทึกผล"
        @click="addData"
        :disable="probationStore.dataPermissions?.tab2.isEdit == false"
      />
    </div>
  </div>
</template>
<style lang="scss" scoped>
.mt {
  margin-top: 25px;
}
</style>
