<script setup>
import { onMounted, ref, watch, inject, computed } from "vue";
import {
  getOutliersList,
  getOutliersDevList,
  getOutliersPoints,
  getFactors,
  delOutliersSetting,
  postMQTTRefresh,
} from "@/apis/alert";
import useSearchParam from "@/hooks/useSearchParam";
import AlertOutliersTableAddModal from "./AlertOutliersTableAddModal.vue";

import { useI18n } from "vue-i18n";
const { t } = useI18n();
const { noticeList, timesList } = inject("notify_table");
const { openToast, cancelToastOpen } = inject("app_toast");
const { searchParams, changeParams } = useSearchParam();

const tableData = ref([]);
const dev_data = ref({
  devList: [],
  alarmPoints: [],
  alarmFactors: [],
});
const editRecord = ref(null);

const columns = computed(() => [
  {
    title: t("alert.device_number"),
    key: "device_number",
    class: "break-all",
  },
  {
    title: t("alert.device_name"),
    key: "device_name",
  },
  {
    title: t("alert.item"),
    key: "points_name",
  },
  {
    title: t("alert.enable"),
    key: "enable",
  },
  {
    title: t("alert.qualifications"),
    key: "factor_name",
  },
  // {
  //   title: `${t("alert.upper_limit")} (>=)`,
  //   key: "highLimit",
  // },
  // {
  //   title: `${t("alert.lower_limit")} (<=)`,
  //   key: "lowLimit",
  // },
  // {
  //   title: t("alert.highDelay"),
  //   key: "highDelay",
  // },
  // {
  //   title: t("alert.lowDelay"),
  //   key: "lowDelay",
  // },
  {
    title: t("alert.warning_method"),
    key: "warning_method",
  },
  // {
  //   title: t("alert.warning_time"),
  //   key: "warning_time",
  //   width: 150,
  // },
  {
    title: t("alert.operation"),
    key: "operation",
    width: 300,
  },
]);

const getDevList = async () => {
  const res = await getOutliersDevList({
    device_name_tag: searchParams.value?.subSys_id,
  });
  return res.data.map((d) => ({
    ...d,
    key: d.device_number,
  }));
};

const getAlarmPoints = async () => {
  const res = await getOutliersPoints({
    device_name_tag: searchParams.value?.subSys_id,
  });
  return res.data.map((d) => ({
    ...d,
    key: d.points,
  }));
};

const getFactor = async () => {
  const res = await getFactors();
  return res.data.map((d) => ({
    ...d,
    key: d.id,
  }));
};

const getOutliersData = async () => {
  const res = await getOutliersList({
    device_name_tag: searchParams.value?.subSys_id,
  });
  if (res.isSuccess) {
    tableData.value = res.data.map((item) => {
      const matchedDevice = dev_data.value.devList.find(
        (dev) => dev.device_number === item.device_number
      );
      const matchedPoints = dev_data.value.alarmPoints.find(
        (p) => p.points === item.points
      );
      const matchedFactor = dev_data.value.alarmFactors.find(
        (p) => p.id === item.factor
      );
      const matchedTime = timesList.value.find(
        (t) => t.id === item.schedule_id
      );
      const warningMethodKeys = item.notices
        ?.map((noticeValue) => {
          const matchedNotice = noticeList.value.find(
            (n) => n.system_value === noticeValue
          );
          return matchedNotice ? matchedNotice.system_key : "";
        })
        .filter((key) => key !== "")
        .join("\n");

      return {
        ...item,
        device_name: matchedDevice ? matchedDevice.device_name : "",
        points_name: matchedPoints ? matchedPoints.full_name : "",
        factor_name: matchedFactor ? matchedFactor.full_name : "",
        warning_method: warningMethodKeys,
        // warning_time: matchedTime ? matchedTime.schedule_name : "",
      };
    });
  }
};

const getAllOptions = async () => {
  const [devices, points, factors] = await Promise.all([
    getDevList(),
    getAlarmPoints(),
    getFactor(),
  ]);
  dev_data.value.devList = devices;
  dev_data.value.alarmPoints = points;
  dev_data.value.alarmFactors = factors;
};

watch(
  () => searchParams.value,
  async (newValue) => {
    if (newValue) {
      await getAllOptions();
      getOutliersData();
    }
  },
  { deep: true }
);

const openModal = (record) => {
  if (record) {
    editRecord.value = record;
  } else {
    editRecord.value = null;
  }
  outliers_add_table_item.showModal();
};

const refreshMQTT = async () => {
  const res = await postMQTTRefresh();
  if (res.isSuccess) {
    openToast("success", t("msg.mqtt_refresh"));
  } else {
    openToast("error", res.msg, "#outliers_add_table_item");
  }
};

const remove = async (Id) => {
  openToast("warning", t("msg.sure_to_delete"), "body", async () => {
    await cancelToastOpen();
    const res = await delOutliersSetting(Id);
    if (res.isSuccess) {
      getOutliersData();
      openToast("success", t("msg.delete_success"));
    } else {
      openToast("error", res.msg);
    }
  });
};

const onCancel = () => {
  editRecord.value = null;
  outliers_add_table_item.close();
};
</script>

<template>
  <div class="flex items-center justify-between mt-10">
    <div class="flex">
      <h3 class="text-xl mr-5">{{ $t("alert.alarm_settings") }}</h3>
      <AlertOutliersTableAddModal
        :openModal="openModal"
        :onCancel="onCancel"
        :editRecord="editRecord"
        :getData="getOutliersData"
        :OptionsData="dev_data"
      />
    </div>
    <button class="btn btn-sm btn-add" @click.prevent="refreshMQTT">
      <font-awesome-icon :icon="['fas', 'cog']" />{{ $t("alert.reorganization") }}
    </button>
  </div>
  <Table :columns="columns" :dataSource="tableData" class="mt-3">
    <template #bodyCell="{ record, column, index }">
      <template v-if="column.key === 'operation'">
        <button
          class="btn btn-sm btn-success text-white mr-2"
          @click.stop.prevent="() => openModal(record)"
        >
          {{ $t("button.edit") }}
        </button>
        <button
          class="btn btn-sm btn-error text-white"
          @click.stop.prevent="() => remove(record.id)"
        >
          {{ $t("button.delete") }}
        </button>
      </template>
      <template v-else-if="column.key === 'enable'">
        {{ record.enable === 1 ? t("alert.yes") : t("alert.no") }}
      </template>
      <template v-else-if="column.key === 'warning_method'">
        <span class="whitespace-pre">{{ record.warning_method }}</span>
      </template>
      <!-- <template v-else-if="column.key === 'warning_time'">
        <span class="whitespace-pre">{{ record.warning_time }}</span>
      </template> -->
      <template v-else>
        {{ record[column.key] }}
      </template>
    </template>
  </Table>
</template>

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