<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";

const { openToast } = inject("app_toast");
const { timesList, 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,
  factor: 1,
  alarm_value: "",
  delay: 0,
  highLimit: null,
  lowLimit: null,
  highDelay: null,
  lowDelay: null,
  notices: [],
});

let scheme = yup.object({
  device_number: yup.string().required("必填"),
  points: yup.string().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 factorNum = ref(1);

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

      if (newValue.factor) {
        onFactorsChange(newValue.factor);
      }
    }
  }
);

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

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();
  factorNum.value = 1;
};
</script>

<template>
  <button class="btn btn-sm btn-success mr-3" @click.stop.prevent="openModal">
    <font-awesome-icon :icon="['fas', 'plus']" />新增
  </button>
  <Modal
    id="outliers_add_table_item"
    title="異常設定"
    :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>設備名稱</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>項目</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>限定條件</template>
        </Select>
        <RadioGroup
          class="my-2"
          name="enable"
          :value="formState"
          :items="[
            {
              key: 1,
              value: 1,
              title: '啟用',
            },
            {
              key: 0,
              value: 0,
              title: '不啟用',
            },
          ]"
          :required="true"
        >
          <template #topLeft>狀態</template>
        </RadioGroup>
        <template v-if="factorNum == 2">
          <div class="flex gap-4 w-full">
            <InputNumber
              :value="formState"
              class=""
              name="highLimit"
              v-if="!isBool"
            >
              <template #topLeft>上限(>=)</template>
            </InputNumber>
            <InputNumber
              :value="formState"
              class=""
              name="lowLimit"
              v-if="!isBool"
            >
              <template #topLeft>下限(&lt;=)</template>
            </InputNumber>
          </div>
          <div class="flex gap-4 w-full">
            <InputNumber
              :value="formState"
              class="my-2"
              name="highDelay"
              v-if="!isBool"
            >
              <template #topLeft>上限持續秒數</template>
            </InputNumber>
            <InputNumber
              :value="formState"
              class="my-2"
              name="lowDelay"
              v-if="!isBool"
            >
              <template #topLeft>下限持續秒數</template>
            </InputNumber>
          </div>
        </template>
        <template v-if="factorNum == 1">
          <Input :value="formState" class="my-2" name="alarm_value">
            <template #topLeft>警示值</template>
          </Input>
        </template>

        <div class="w-full mt-5">
          <p class="text-light text-lg ml-1">警示方式</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"
      >
        取消
      </button>
      <button
        type="submit"
        class="btn btn-outline-success"
        @click.prevent="onOk"
      >
        確定
      </button>
    </template>
  </Modal>
</template>

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