<script setup>
import { ref, onMounted, defineProps, inject, watch } from "vue";
import * as yup from "yup";
import "yup-phone-lite";
import useFormErrorMessage from "@/hooks/useFormErrorMessage";
import { postBuildings } from "@/apis/building";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const { openToast } = inject("app_toast");

const props = defineProps({
  formState: Object,
  getData: Function,
  openModal: Function
});

const buildScheme = yup.object({
  full_name: yup.string().required(t("button.required")),
});

const { formErrorMsg, handleSubmit, handleErrorReset, updateScheme } =
  useFormErrorMessage(buildScheme);

const onCancel = () => {
  handleErrorReset();
  build_modal.close();
};

const onOk = async () => {
  const value = await handleSubmit(buildScheme, props.formState);
  const res = await postBuildings(value);
  if (res.isSuccess) {
    props.getData();
    onCancel();
  } else {
    openToast("error", res.msg, "#build_modal");
  }
};
</script>

<template>
   <button class="btn btn-sm btn-add " @click.stop.prevent="props.openModal">
    <font-awesome-icon :icon="['fas', 'plus']" />{{ $t("button.add") }}
  </button>
  <Modal
    id="build_modal"
    :title="props.formState?.building_guid ? t('button.edit') : t('button.add')"
    :onCancel="onCancel"
    :width="400"
  >
    <template #modalContent>
      <form ref="form" class="mt-5 w-full flex flex-wrap justify-between">
        <Input :value="formState" class="my-2" name="full_name">
          <template #topLeft>{{
            $t("assetManagement.building")
          }}</template>
          <template #bottomLeft
            ><span class="text-error text-base">
              {{ formErrorMsg.full_name }}
            </span></template
          ></Input
        >
      </form>
    </template>
    <template #modalAction>
      <button
        type="reset"
        class="btn btn-outline-success mr-2"
        @click.prevent="onCancel"
      >
        {{ $t("button.cancel") }}
      </button>
      <button
        type="submit"
        class="btn btn-outline-success"
        @click.stop.prevent="onOk"
      >
        {{ $t("button.submit") }}
      </button>
    </template>
  </Modal>
</template>

<style lang="scss" scoped></style>
