<script setup lang="ts">
import { useRequest } from "vue-request";
import { myRequest } from "@/requests/request.ts";
import { columns, sysLog } from "@/pages/sys-log/store.ts";
import { userinfo } from "@/store/store.ts";
import { ref, watch } from "vue";
import YlLine from "@/components/charts/yl-line.vue";

const { data, loading } = useRequest<{
  data: { ip: string; location: string }[];
}>(() => myRequest(`/admin/logs/detail?date=${sysLog.date}`, userinfo.token), {
  refreshDeps: () => sysLog.date,
});
const detailLine = ref<
  { name: string; value: number; detail: { ip: string; location: string }[] }[]
>([]);
const ipIndex = ref(-1);
const modal = ref(false);
const page = ref(1);
const setIp = (index: number) => {
  ipIndex.value = index;
  modal.value = true;
};
watch(data, () => {
  if (data.value) {
    detailLine.value = Array.from(
      new Set(data.value.data.map((e) => e.ip)),
    ).map((e) => ({
      name: e,
      value: data.value?.data.filter((item) => item.ip === e).length || 0,
      detail: data.value?.data.filter((item) => item.ip === e) || [],
    }));
  }
});
watch(modal, () => {
  page.value = 1;
});
</script>

<template>
  <div class="select-date">详情日期：{{ sysLog.date }}</div>
  <div class="date-view" v-if="detailLine && data" v-loading="loading">
    <yl-line
      :x-data="detailLine.map((e) => e.name)"
      :y-data="[{ name: '', value: detailLine.map((e) => e.value) }]"
      :set-index="setIp"
      clickable
      default-index
      smooth
    />
  </div>
  <el-dialog v-model="modal" style="width: 1300px" append-to-body>
    <div class="title">
      <label>IP地址：{{ detailLine[ipIndex].name }}</label>
      <div class="inline-space"></div>
      <label>地址：{{ detailLine[ipIndex].detail[0].location }}</label>
    </div>
    <div class="flex around">
      <el-pagination
        hide-on-single-page
        layout="prev, pager, next"
        :total="detailLine[ipIndex].detail.length || 0"
        :current-page="page"
        @update:current-page="(p: number) => (page = p)"
      />
    </div>
    <el-table
      :data="
        detailLine[ipIndex].detail.filter(
          (_, i) => i >= (page - 1) * 10 && i < page * 10,
        )
      "
    >
      <el-table-column
        v-for="item in columns"
        :prop="item.dataIndex"
        :label="item.title"
        :width="item.width"
        align="center"
        :show-overflow-tooltip="item.overflow"
      />
    </el-table>
  </el-dialog>
</template>

<style scoped>
.select-date {
  text-align: center;
  font-weight: bolder;
  color: #f0c237;
}

.title {
  text-align: center;
  padding: 10px;
}

.inline-space {
  width: 25px;
  display: inline-block;
}

.date-view {
  padding: 10px 20px;
  height: 300px;
}
</style>
