<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 { postDepartmentList } from "@/apis/asset";
import { useI18n } from "vue-i18n";
import useBuildingStore from "@/stores/useBuildingStore";

const storeBuild = useBuildingStore();
const { t } = useI18n();
const { openToast } = inject("app_toast");

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

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

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

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

const onOk = async () => {
  const value = await handleSubmit(deptScheme, props.formState);
  const res = await postDepartmentList(value);
  if (res.isSuccess) {
    storeBuild.fetchDepartmentList();
    onCancel();
  } else {
    openToast("error", res.msg, "#dept_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="dept_modal"
    :title="props.formState?.id ? 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="name">
          <template #topLeft>{{
            $t("assetManagement.department_name")
          }}</template>
          <template #bottomLeft
            ><span class="text-error text-base">
              {{ formErrorMsg.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>
