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

const { noticeList, timesList } = inject("notify_table");
const { searchParams, changeParams } = useSearchParam();
const { openToast, cancelToastOpen } = inject("app_toast");

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

const columns = [
  {
    title: "設備編號",
    key: "device_number",
    class: "break-all",
  },
  {
    title: "設備名稱",
    key: "device_name",
    class: "break-all",
  },
  {
    title: "項目",
    key: "points",
  },
  {
    title: "啟用",
    key: "enable",
  },
  {
    title: "限定條件",
    key: "factor_name",
  },
  {
    title: "警示方式",
    key: "warning_method",
  },
  {
    title: "功能",
    key: "operation",
    width: 200,
  },
];

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,
  });
  loading.value = true;
  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 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,
      };
    });
    loading.value = false;
  }
};

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 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 justify-start items-center mt-10">
    <h3 class="text-xl mr-5">異常設定</h3>
    <AlertOutliersTableAddModal
      :openModal="openModal"
      :onCancel="onCancel"
      :editRecord="editRecord"
      :getData="getOutliersData"
      :OptionsData="dev_data"
    />
  </div>
  <Table
    :loading="loading"
    :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)"
        >
          修改
        </button>
        <button
          class="btn btn-sm btn-error text-white"
          @click.stop.prevent="() => remove(record.id)"
        >
          刪除
        </button>
      </template>
      <template v-else-if="column.key === 'enable'">
        {{ record.enable === 1 ? "是" : "否" }}
      </template>
      <template v-else-if="column.key === 'warning_method'">
        <span class="whitespace-pre">{{ record.warning_method }}</span>
      </template>
      <template v-else>
        {{ record[column.key] }}
      </template>
    </template>
  </Table>
</template>

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