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

import HeaderTop from "@/modules/05_placement/components/PersonalDetail/Information/top.vue";

import http from "@/plugins/http";
import config from "@/app.config";

import type { PropType } from "vue";
import type { Property } from "@/modules/05_placement/interface/index/Main";

const $q = useQuasar();
const mixin = useCounterMixin();
const route = useRoute();
const { showLoader, hideLoader, messageError, success } = mixin;

const props = defineProps({
  statusEdit: {
    type: Boolean,
    required: true,
  },
  data: {
    type: Array as PropType<Property[]>,
    default: [],
  },
  fetch: {
    type: Function,
    default: () => console.log("not function"),
  },
});
const emit = defineEmits(["update:statusEdit", "update:data"]);

const edit = ref<boolean>(false);

onMounted(() => {
  emit("update:statusEdit", false);
});

const saveData = async () => {
  showLoader();
  await http
    .put(
      config.API.placementPropertyId(route.params.personalId.toString()),
      props.data
    )
    .then((res: any) => {
      success($q, "แก้ไขข้อมูลสำเร็จ");
    })
    .catch((e: any) => {
      messageError($q, e);
    })
    .finally(async () => {
      await props.fetch();
      edit.value = false;
      hideLoader();
      changeBtn();
    });
};

const changeBtn = async () => {
  if (edit.value == true) {
    if (props.statusEdit === true) {
      edit.value = false;
    } else {
      emit("update:statusEdit", true);
    }
  } else {
    emit("update:statusEdit", false);
  }
};

const onCancel = async () => {
  await props.fetch();
};
</script>
<template>
  <div class="row col-12 q-px-lg q-pt-lg q-pb-sm no-border">
    <HeaderTop
      v-model:edit="edit"
      header="การคัดกรองคุณสมบัติ"
      icon="mdi-account-search"
      :save="saveData"
      :history="false"
      :changeBtn="changeBtn"
      :disable="statusEdit"
      :cancel="onCancel"
    />
  </div>
  <div class="row q-px-lg">
    <div v-for="item of props.data" :key="item.name" class="col-12 q-pt-sm">
      <q-checkbox
        size="xs"
        v-model="item.value"
        :label="item.name"
        keep-color
        color="gray-5"
        :disable="!statusEdit"
      />
      <q-separator />
    </div>
  </div>
</template>
