<script setup>
import { inject, defineProps, watch, ref } from "vue";
import useSearchParam from "@/hooks/useSearchParam";
import useFormErrorMessage from "@/hooks/useFormErrorMessage";
import AlertNoticesTable from "./AlertNoticesTable.vue";
import { postOutliersSetting } from "@/apis/alert";
import * as yup from "yup";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const { openToast } = inject("app_toast");
const { timesList, noticeList } = inject("notify_table");
const { searchParams } = useSearchParam();

const props = defineProps({
  openModal: Function,
  onCancel: Function,
  getData: Function,
  editRecord: Object,
  OptionsData: Object,
});

// ---- 初始表單狀態（統一使用此物件重置） ----
const initialFormState = () => ({
  id: 0,
  device_number: "",
  device_name_tag: searchParams.value?.subSys_id,
  points: "",
  enable: 0,
  factor: 1,
  alarm_value: "",
  delay: null,
  highLimit: null,
  lowLimit: null,
  highDelay: null,
  lowDelay: null,
  notices: [],
});

const form = ref(null);
const formState = ref(initialFormState());

/** 將數字欄位統一做「可空值」轉換：空字串/undefined/null -> null，其餘轉 number */
const numNullable = () =>
  yup
    .number()
    .transform((value, originalValue) =>
      originalValue === "" || originalValue === undefined || originalValue === null
        ? null
        : value
    )
    .nullable();

// ---- 驗證規則：上下限/延遲一律非必填 ----
const scheme = yup.object({
  device_number: yup.string().required(t("button.required")),
  points: yup.string().required(t("button.required")),
  factor: numNullable(),
  enable: numNullable().required(),
  delay: numNullable(),
  highLimit: numNullable(),
  lowLimit: numNullable(),
  highDelay: numNullable(),
  lowDelay: numNullable(),
  // alarm_value 如不需驗證可不放 schema；若要限制型別可在此補上
});

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

const SaveCheckAuth = ref([]);
const factorNum = ref(1);

watch(
  () => props.editRecord,
  (newValue) => {
    if (newValue) {
      // 將不存在或空字串的數字欄位正規化為 null，避免編輯時被當作「必填」
      const normalize = (v) =>
        v === "" || v === undefined ? null : v;

      formState.value = {
        ...initialFormState(),
        ...newValue,
        delay: normalize(newValue.delay),
        highLimit: normalize(newValue.highLimit),
        lowLimit: normalize(newValue.lowLimit),
        highDelay: normalize(newValue.highDelay),
        lowDelay: normalize(newValue.lowDelay),
      };

      SaveCheckAuth.value = Array.isArray(newValue.notices)
        ? [...newValue.notices]
        : newValue.notices
        ? [newValue.notices]
        : [];

      if (newValue.factor) {
        onFactorsChange(newValue.factor);
      } else {
        factorNum.value = 1;
      }
    }
  }
);

const onFactorsChange = (selectedFactor) => {
  factorNum.value = selectedFactor;
};

const onNoticesChange = (value, checked) => {
  if (checked) {
    if (SaveCheckAuth.value.length === 1 && SaveCheckAuth.value[0] === "") {
      SaveCheckAuth.value = [];
    }
    if (!SaveCheckAuth.value.includes(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 postOutliersSetting({
    ...values,
    id: formState.value.id ? formState.value.id : 0,
    device_name_tag: searchParams.value?.subSys_id,
    notices: SaveCheckAuth.value ? SaveCheckAuth.value : [],
  });

  if (res.isSuccess) {
    props.getData();
    closeModal();
  } else {
    openToast("error", res.msg, "#outliers_add_table_item");
  }
};

const closeModal = () => {
  formState.value = initialFormState();
  SaveCheckAuth.value = [];
  factorNum.value = 1;
  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="outliers_add_table_item"
    :title="t('alert.alarm_settings')"
    :open="open"
    :onCancel="closeModal"
    width="710"
  >
    <template #modalContent>
      <form ref="form" class="mt-5 w-full flex flex-wrap justify-between">
        <Select
          :value="formState"
          class="my-2"
          selectClass="border-info focus-within:border-info"
          name="device_number"
          Attribute="device_name"
          :options="OptionsData.devList"
        >
          <template #topLeft>{{ $t("alert.device_name") }}</template>
          <template #bottomLeft>
            <span class="text-error text-base">{{ formErrorMsg.device_number }}</span>
          </template>
        </Select>

        <Select
          :value="formState"
          class="my-2"
          selectClass="border-info focus-within:border-info"
          name="points"
          Attribute="full_name"
          :options="OptionsData.alarmPoints"
        >
          <template #topLeft>{{ $t("alert.item") }}</template>
          <template #bottomLeft>
            <span class="text-error text-base">{{ formErrorMsg.points }}</span>
          </template>
        </Select>

        <Select
          :value="formState"
          class="my-2"
          selectClass="border-info focus-within:border-info"
          name="factor"
          Attribute="full_name"
          :options="OptionsData.alarmFactors"
          :onChange="onFactorsChange"
        >
          <template #topLeft>{{ $t("alert.qualifications") }}</template>
        </Select>

        <RadioGroup
          class="my-2"
          name="enable"
          :value="formState"
          :items="[
            { key: 1, value: 1, title: $t('alert.enable') },
            { key: 0, value: 0, title: $t('alert.not_enabled') },
          ]"
          :required="true"
        >
          <template #topLeft>{{ $t('alert.status') }}</template>
        </RadioGroup>

        <template v-if="factorNum == 1">
          <InputNumber :value="formState" class="my-2" name="delay">
            <template #topLeft>{{ $t('alert.delay') }}</template>
          </InputNumber>
          <span class="text-error text-base ml-1">{{ formErrorMsg.delay }}</span>
        </template>

        <template v-if="factorNum == 2">
          <div class="flex gap-4 w-full">
            <InputNumber :value="formState" class="my-2" name="highLimit">
              <template #topLeft>{{ $t('alert.upper_limit') }}(>=)</template>
            </InputNumber>
            <InputNumber :value="formState" class="my-2" name="lowLimit">
              <template #topLeft>{{ $t('alert.lower_limit') }}(&lt;=)</template>
            </InputNumber>
          </div>
          <div class="flex gap-4 w-full -mt-2">
            <span class="text-error text-base flex-1 ml-1">{{ formErrorMsg.highLimit }}</span>
            <span class="text-error text-base flex-1 ml-1">{{ formErrorMsg.lowLimit }}</span>
          </div>

          <div class="flex gap-4 w-full">
            <InputNumber :value="formState" class="my-2" name="highDelay">
              <template #topLeft>{{ $t('alert.highDelay') }}</template>
            </InputNumber>
            <InputNumber :value="formState" class="my-2" name="lowDelay">
              <template #topLeft>{{ $t('alert.lowDelay') }}</template>
            </InputNumber>
          </div>
          <div class="flex gap-4 w-full -mt-2">
            <span class="text-error text-base flex-1 ml-1">{{ formErrorMsg.highDelay }}</span>
            <span class="text-error text-base flex-1 ml-1">{{ formErrorMsg.lowDelay }}</span>
          </div>
        </template>

        <template v-if="factorNum == 3">
          <Input :value="formState" class="my-2" name="alarm_value">
            <template #topLeft>{{ $t('alert.warning_value') }}</template>
          </Input>
        </template>

        <div class="w-full mt-5">
          <p class="text-light text-lg ml-1">{{ $t('alert.warning_method') }}</p>
          <AlertNoticesTable
            :SaveCheckAuth="SaveCheckAuth"
            :NoticeData="noticeList"
            :onChange="onNoticesChange"
          />
        </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>
