<script setup lang="ts">
import NavHomeSelect from '@/assets/images/nav-home.select.png?url';

import type { LoggerModel } from '@/request/model/manage.model';
import dayjs from 'dayjs';
import { usePagination } from 'alova/client';
import { listLoggers } from '@/request/api/manage';
import { useRouteMeta } from '@/router/hooks/useRouteMeta';
import { useFloatPanel } from '@/composables/FloatPanel';
import LoggerPreview  from '@/modules/system/logger.preview.vue';

const title = useRouteMeta('title', '日志管理', { priority: 'query' });
const now = dayjs();

const form = ref({ beginTime: '', endTime: '' });
const reset = () => {
  form.value = { beginTime: '', endTime: '' };
  reload();
};
const { loading, data, isLastPage, page, reload, refresh } = usePagination((...args) => listLoggers(...args, form.value), {
  initialData: { total: 0, data: [] },
  initialPage: 1,
  initialPageSize: 20,
  append: true,
  immediate: true,
}).onComplete(() => (sending.value = false));
const sending = ref(true);
const onLoad = () => {
  if (sending.value) return;
  sending.value = true;
  page.value += 1;
};

const [PreviewFloatPanel, preview] = useFloatPanel<LoggerModel, LoggerModel>(LoggerPreview);
const onPreview = (item: LoggerModel, index: number) => {
  preview.open(item);
};

const showDatePicker = ref(false);
const displayDate = computed(() => {
  const start = form.value.beginTime?.split(' ')[0] ?? '';
  const end = form.value.beginTime?.split(' ')[0] ?? '';
  if (!start && !end) return '';
  return `${start} ~ ${end}`;
});
const editStartDate = ref<string[]>([]);
const editEditDate = ref<string[]>([]);
const openDatePicker = () => {
  editStartDate.value = (form.value.beginTime ? dayjs(form.value.beginTime) : now.startOf('month')).format('YYYY-MM-DD').split('-');
  editEditDate.value = (form.value.beginTime ? dayjs(form.value.endTime) : now).format('YYYY-MM-DD').split('-');
  showDatePicker.value = true;
};
const closeDatePicker = (event?: { selectedValues: string[] }[]) => {
  showDatePicker.value = false;
  if (!Array.isArray(event) || event.length < 2) return;
  let start = dayjs(event[0].selectedValues.join('-'));
  let end = dayjs(event[1].selectedValues.join('-'));
  if (start.isAfter(end)) [start, end] = [end, start];
  form.value.beginTime = start.startOf('day').format('YYYY-MM-DD');
  form.value.endTime = end.endOf('day').format('YYYY-MM-DD');
  reload();
};
</script>

<template>
  <div class="page-container">
    <div class="page-header flex py-4 px-4 overflow-hidden">
      <div class="grow shrink-0 h-full min-w-16"></div>
      <div class="grow-[3] shrink mx-2 flex flex-col justify-center overflow-hidden">
        <div class="font-bold text-3xl text-nowrap text-center tracking-wide overflow-ellipsis overflow-hidden">{{ title }}</div>
      </div>
      <div class="grow shrink-0 h-full min-w-16 flex items-center justify-end overflow-hidden">
        <router-link :to="{ path: '/screen' }" replace>
          <img class="size-8 object-scale-down" :src="NavHomeSelect" alt="返回首页" />
        </router-link>
      </div>
    </div>
    <div class="page-content flex flex-col overflow-hidden">
      <div class="flex-none">
        <van-form label-width="4em" @submit="reload()" @reset="reset()">
          <van-cell-group inset class="grid grid-cols-2 gap-2">
            <van-field :border="false" name="rolename" v-model="displayDate" label="日期" placeholder="请选择开始 - 结束日期" readonly @click="openDatePicker()" />
            <div class="flex items-center justify-end gap-6">
              <div class="flex gap-4">
                <van-button plain size="small" native-type="reset">重置</van-button>
                <van-button plain size="small" type="success" native-type="submit">搜索</van-button>
              </div>
            </div>
          </van-cell-group>
        </van-form>
        <van-divider style="border-color: hsl(var(--primary-hover) / 0.5)" />
      </div>
      <div class="flex-auto overflow-y-scroll list-content-container">
        <van-pull-refresh :modelValue="loading && page === 1" class="min-h-full" @refresh="reload()">
          <van-list :loading="loading || sending" :finished="isLastPage" finished-text="没有更多了" @load="onLoad()">
            <van-cell v-for="(item, index) in data" :key="item.uid" size="large" center>
              <template #title>{{ item.title }}</template>
              <template #label>
                <van-tag plain type="primary">{{ item.operator }}</van-tag>
                <span class="ml-2">{{ item.date }}</span>
              </template>
              <template #value>
                <van-button square type="primary" text="查看" @click="onPreview(item, index)" />
              </template>
            </van-cell>
          </van-list>
        </van-pull-refresh>
      </div>
    </div>
    <PreviewFloatPanel auto-height full closable />
    <van-popup v-model:show="showDatePicker" position="top">
      <van-picker-group title="日期" :tabs="['开始日期', '结束日期']" next-step-text="下一步" @confirm="closeDatePicker" @cancel="closeDatePicker()">
        <van-date-picker v-model="editStartDate" :max-date="now.toDate()" />
        <van-date-picker v-model="editEditDate" :max-date="now.toDate()" />
      </van-picker-group>
    </van-popup>
  </div>
</template>

<style scoped lang="scss">
.list-content-container {
  :deep(.van-cell__title) {
    flex: auto;
  }
  :deep(.van-cell__value) {
    flex: none;
  }
}
</style>
