<script setup>
import { ref, inject, onMounted } from "vue";
import { deleteAlarmSchedule } from "@/apis/alert";
import AlertTimeTableAddModal from "./AlertTimeTableAddModal.vue";

const { openToast, cancelToastOpen } = inject("app_toast");
const tableData = ref([]);
const editRecord = ref(null);
const { timesList,timesListData } = inject("notify_table");
const weekDate = ref({
  1: "星期日",
  2: "星期一",
  3: "星期二",
  4: "星期三",
  5: "星期四",
  6: "星期五",
  7: "星期六",
});

onMounted(() => {
  timesListData();
});

const columns = [
  {
    title: "時段名稱",
    key: "schedule_name",
  },
  {
    title: "時段內容",
    key: "schedule_content",
  },
  {
    title: "功能",
    key: "operation",
    width: 200,
  },
];

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

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

const remove = async (id) => {
  openToast("warning", "是否確認刪除該項目?", "body", async () => {
    await cancelToastOpen();
    const res = await deleteAlarmSchedule(id);
    if (res.isSuccess) {
      timesListData();
      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>
    <AlertTimeTableAddModal :openModal="openModal" :onCancel="onCancel" :editRecord="editRecord" :weekDate="weekDate" />
  </div>
  <Table :columns="columns" :dataSource="timesList" class="w-3/4 mt-3">
    <template #bodyCell="{ record, column, index }">
      <template v-if="column.key === 'schedule_content'">
        <ul class="text-left">
          <li v-for="(item, index) in record.schedule_array" :key="index">
            <strong v-if="item.time.length">
              <span>{{ weekDate[item.day] }}: </span>
              <span v-for="(time, timeIndex) in item.time" :key="timeIndex">
                {{ time }}
                <span v-if="timeIndex < item.time.length - 1">, </span>
              </span>
            </strong>
          </li>
        </ul>
      </template>
      <template v-else-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>
