<script setup>
import { inject, defineProps, watch, ref, provide } 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 { noticeList } = inject("notify_table");
const { searchParams, changeParams } = useSearchParam();

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

const form = ref(null);
const formState = ref({
  id: 0,
  device_number: "",
  device_name_tag: searchParams.value?.subSys_id,
  points: "",
  enable: 0,
  is_bool: 1,
  factor: null,
  highLimit: null,
  lowLimit: null,
  highDelay: null,
  lowDelay: null,
  notices: [],
});

let scheme = yup.object({
  device_number: yup.string().required(t("button.required")),
  points: yup.string().required(t("button.required")),
  factor: yup.number().nullable(),
  enable: yup.number().required(),
  highLimit: yup.number().nullable(),
  lowLimit: yup.number().nullable(),
  highDelay: yup.number().nullable(),
  lowDelay: yup.number().nullable(),
});

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

const SaveCheckAuth = ref([]);
const isBool = ref(1);
const factorData = ref([]);

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

      if (newValue.points) {
        onPointsChange(newValue.points);
      }
    }
  }
);

const onPointsChange = (selectedPoint) => {
  const pointData = props.OptionsData.alarmPoints.find(
    (p) => p.points === selectedPoint
  );
  if (pointData) {
    isBool.value = pointData.is_bool;
    formState.value.is_bool = pointData.is_bool;
    if (pointData.factor && Array.isArray(pointData.factor)) {
      factorData.value = pointData.factor.map((d) => ({
        ...d,
        key: d.id,
      }));
    } else {
      factorData.value = [];
      formState.value.factor = 0;
    }
  }
};

const onNoticesChange = (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 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 = {};
  handleErrorReset();
  props.onCancel();
  factorData.value = [];
  isBool.value = 1;
};
</script>

<template>
  <button class="btn btn-sm btn-success 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"
          :onChange="onPointsChange"
        >
          <template #topLeft>{{ $t("alert.item") }}</template>
          <template #bottomLeft
            ><span class="text-error text-base">
              {{ formErrorMsg.points }}
            </span></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>
        <Select
          :value="formState"
          class="my-2"
          selectClass="border-info focus-within:border-info"
          name="factor"
          Attribute="full_name"
          :options="factorData"
          v-if="factorData.length !== 0"
        >
          <template #topLeft>{{ $t("alert.qualifications") }}</template>
        </Select>
        <InputNumber
          :value="formState"
          class="my-2"
          name="highLimit"
          v-if="!isBool"
        >
          <template #topLeft>{{ $t("alert.upper_limit") }}(>=)</template>
        </InputNumber>
        <InputNumber
          :value="formState"
          class="my-2"
          name="lowLimit"
          v-if="!isBool"
        >
          <template #topLeft>{{ $t("alert.lower_limit") }}(&lt;=)</template>
        </InputNumber>
        <InputNumber
          :value="formState"
          class="my-2"
          name="highDelay"
          v-if="!isBool"
        >
          <template #topLeft>{{ $t("alert.highDelay") }}</template>
        </InputNumber>
        <InputNumber
          :value="formState"
          class="my-2"
          name="lowDelay"
          v-if="!isBool"
        >
          <template #topLeft>{{ $t("alert.lowDelay") }}</template>
        </InputNumber>
        <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("buttton.submit") }}
      </button>
    </template>
  </Modal>
</template>

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