<script setup>
import { inject, defineProps, watch, ref } from "vue";
import useFormErrorMessage from "@/hooks/useFormErrorMessage";
import AlertNoticesTable from "./AlertNoticesTable.vue";
import { postAlertMember } from "@/apis/alert";
import * as yup from "yup";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const { openToast } = inject("app_toast");
const { noticeList } = inject("notify_table");
const props = defineProps({
  openModal: Function,
  onCancel: Function,
  editRecord: Object,
  fetchTableData: Function,
});

let scheme = yup.object({
  name: yup.string().required(t("button.required")),
  phone: yup
    .string()
    .phone("TW", t("button.phone_format"))
    .required(t("button.required")),
  email: yup
    .string()
    .email(t("button.email_format"))
    .required(t("button.required")),
});

const form = ref(null);
const formState = ref({
  id: null,
  name: "",
  phone: "",
  email: "",
  notices: [],
});

const SaveCheckAuth = ref([]);

const { formErrorMsg, handleSubmit, handleErrorReset } = useFormErrorMessage(
  scheme.value
);

watch(
  () => props.editRecord,
  (newValue) => {
    if (newValue) {
      formState.value = {
        ...newValue,
      };
      SaveCheckAuth.value = newValue.notices ? [...newValue.notices] : [];
    }
  }
);

const onChange = (value, checked) => {
  if (checked) {
    if (SaveCheckAuth.value.length === 1 && SaveCheckAuth.value[0] === "") {
      SaveCheckAuth.value = [];
    }
    SaveCheckAuth.value = [...SaveCheckAuth.value, value];
  } else {
    SaveCheckAuth.value = SaveCheckAuth.value.filter((v) => v !== value);
  }
};

const onOk = async () => {
  const values = await handleSubmit(scheme, formState.value);

  const res = await postAlertMember({
    ...values,
    notices: SaveCheckAuth.value ? SaveCheckAuth.value : [],
  });
  if (res.isSuccess) {
    props.fetchTableData();
    closeModal();
  } else {
    openToast("error", res.msg, "#notify_add_table_item");
  }
};

const closeModal = () => {
  SaveCheckAuth.value = [];
  handleErrorReset();
  props.onCancel();
};
</script>

<template>
  <button class="btn btn-sm btn-add mr-3" @click.stop.prevent="openModal">
    <font-awesome-icon :icon="['fas', 'plus']" />{{ $t("button.add") }}
  </button>
  <Modal
    id="notify_add_table_item"
    :title="t('alert.notify_list')"
    :open="open"
    :onCancel="closeModal"
    width="300"
  >
    <template #modalContent>
      <form ref="form" class="mt-5 flex flex-col items-center">
        <Input :value="formState" class="w-full" name="name">
          <template #topLeft>{{ $t("alert.notify_name") }}</template>
          <template #bottomLeft>
            <span class="text-error text-base">
              {{ formErrorMsg.name }}
            </span>
          </template>
        </Input>
        <Input class="w-full" :value="formState" name="phone">
          <template #topLeft>{{ $t("alert.notify_phone") }}</template>
          <template #bottomLeft>
            <span class="text-error text-base">
              {{ formErrorMsg.phone }}
            </span>
          </template>
        </Input>
        <Input class="w-full" :value="formState" name="email">
          <template #topLeft>{{ $t("alert.notify_email") }}</template>
          <template #bottomLeft>
            <span class="text-error text-base">
              {{ formErrorMsg.email }}
            </span>
          </template>
        </Input>
        <div class="w-5/6 mt-5">
          <p class="text-light text-base">{{ $t("alert.notify_items") }}</p>
          <AlertNoticesTable
            :SaveCheckAuth="SaveCheckAuth"
            :NoticeData="[noticeList[2]]"
            :onChange="onChange"
          />
          <span class="text-error text-base">
            {{ formErrorMsg.notices }}
          </span>
        </div>
      </form>
    </template>
    <template #modalAction>
      <button
        type="reset"
        class="btn btn-outline-success mr-2"
        @click.prevent="closeModal"
      >
        {{ $t("button.cancel") }}
      </button>
      <button
        type="submit"
        class="btn btn-outline-success"
        @click.prevent="onOk"
      >
        {{ $t("button.submit") }}
      </button>
    </template>
  </Modal>
</template>

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