<script setup>
import { ref, inject, watch } from "vue";
import { getAlarmMemberList, deleteAlarmMember } from "@/apis/alert";
import AlertNotifyTableAddModal from "./AlertNotifyTableAddModal.vue";

const { openToast, cancelToastOpen } = inject("app_toast");
const tableData = ref([]);
const editRecord = ref(null);
const { noticeList } = inject("notify_table");

const fetchTableData = async () => {

  const noticeMap = noticeList.value.reduce((acc, notice) => {
    acc[notice.system_value] = notice.system_key;
    return acc;
  }, {});

  const res = await getAlarmMemberList();
  tableData.value = res.data.map(member => ({
    ...member,
    notify_items: member.notices
      .filter(n => noticeMap[n])
      .map(n => noticeMap[n])
      .join('\n') || '無通知',
  }));
};

watch(noticeList, (newVal) => {
  if (newVal) {
    fetchTableData();
  }
}, { immediate: true });

const columns = [
  {
    title: "姓名",
    key: "name",
  },
  {
    title: "手機號碼",
    key: "phone",
  },
  {
    title: "email",
    key: "email",
  },
  {
    title: "通知項目",
    key: "notify_items",
  },
  {
    title: "功能",
    key: "operation",
    width: 200,
  },
];


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

const onCancel = () => {
  editRecord.value = null;
  notify_add_table_item.close();
};

const remove = async (id) => {
  openToast("warning", "是否確認刪除該項目?", "body", async () => {
    await cancelToastOpen();
    const res = await deleteAlarmMember(id);
    if (res.isSuccess) {
      fetchTableData();
      openToast("success", "刪除成功");
    } else {
      openToast("error", res.msg);
    }
  });
};

</script>

<template>
  <div class="flex justify-start items-center mt-10">
    <h3 class="text-xl mr-5">通知名單</h3>
    <AlertNotifyTableAddModal :openModal="openModal" :onCancel="onCancel" :editRecord="editRecord"
      :fetchTableData="fetchTableData" />
  </div>
  <Table :columns="columns" :dataSource="tableData" class="w-3/4 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>
        <pre>{{ record[column.key] }}</pre>
      </template>
    </template>
  </Table>
</template>

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