<script lang="ts" setup>
import { inject, onMounted, Ref, ref } from "vue"
import { LoggerKey } from "../ts/class/Logger"

const logger = inject(LoggerKey)
const loading = ref(true)
const doFetch = () => fetch("https://www.torn.com/page.php", {
  "headers": {
    "accept": "*/*",
    "sec-ch-ua-mobile": "?0",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
    "x-requested-with": "XMLHttpRequest"
  },
  "referrer": "https://www.torn.com/page.php?sid=events",
  "referrerPolicy": "strict-origin-when-cross-origin",
  "body": (() => {
    const data = new FormData();
    data.append('sid', 'eventsData');
    return data;
  })(),
  "method": "POST",
  "mode": "cors",
  "credentials": "include"
});
const events: Ref<{ ID: string, message: string, time: string, date: string, isNew: boolean, ts: number }[]> = ref([]);
const DateTimeFormatter = (ts: number) => {
  let date = new Date(ts);
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
};
const loadData = async () => {
  loading.value = true;
  events.value = [];
  let res;
  try {
    res = await (await doFetch()).json();
    if (res.success) {
      events.value = res.list;
      let newEventsAmount = res['newEventsAmount']
      for (let i = 0; i < res.list.length; i++) {
        if (i < newEventsAmount) {
          events.value[i].isNew = true
        }
        let date = new Date(0)
        try {
          let dateResponseSplit = events.value[i].date.split('/')
          let timeResponseSplit = events.value[i].time.split(':')
          date.setUTCDate(parseInt(dateResponseSplit[0]))
          date.setUTCMonth(parseInt(dateResponseSplit[1]) - 1)
          date.setUTCFullYear(2000 + parseInt(dateResponseSplit[2]))
          date.setUTCHours(parseInt(timeResponseSplit[0]))
          date.setUTCMinutes(parseInt(timeResponseSplit[1]))
          date.setUTCSeconds(parseInt(timeResponseSplit[2]))
        } catch (e) {
          logger.error('未能解析时间', e)
        }
        events.value[i].ts = date.getTime()
      }
      loading.value = false;
    }
  } catch (e) {
    logger.error(e.stack);
  }
};

onMounted(loadData);
</script>

<template>
  <el-button @click="loadData">刷新</el-button>
  <el-divider/>
  <el-timeline v-if="!loading">
    <el-timeline-item v-for="ev in events" :color="ev.isNew?'#0bbd87':''"
                      :timestamp="DateTimeFormatter(ev.ts)">
      <span v-html="ev.message"></span>
    </el-timeline-item>
  </el-timeline>
  <el-skeleton v-if="loading" :rows="10" animated/>
</template>

<style scoped></style>