<template>

  <div class="container">
    <Breadcrumb :items="['校园乐跑', '乐跑记录']" />
    <a-card title="乐跑记录">
      <a-row>
        <a-col :flex="'1000px'">
          <a-form :model="queryData" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }"
            label-align="left">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="name" label="账号名称">
                  <a-input v-model="queryData.name" placeholder="请输入账号名称" allow-clear />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="lepao_account" label="学号">
                  <a-input v-model="queryData.lepao_account" placeholder="请输入学号" allow-clear />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="email" label="通知邮箱">
                  <a-input v-model="queryData.email" placeholder="请输入通知邮箱" allow-clear />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="queryTime" label="乐跑时间">
                  <a-range-picker v-model="queryData.queryTime" show-time format="YYYY-MM-DD HH:mm" value-format="x"
                    @ok="getRecords()" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="1">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search />
              </template>
              搜索
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>

      <a-alert v-if="notice" style="margin-bottom: 15px;">{{ notice }}</a-alert>

      <a-table :data="data" :bordered="false" hoverable class="table" :loading="loading" :pagination="{
        showPageSize: true,
        showJumper: true,
        showTotal: true,
        pageSize: pagination.pagesize,
        current: pagination.current,
        total: pagination.total
      }" @page-change="handlePageChange" @page-size-change="handlePageSizeChange">

        <template #name-filter="{ filterValue, setFilterValue, handleFilterConfirm, handleFilterReset }">
          <div class="custom-filter">
            <a-space direction="vertical">
              <a-input :model-value="filterValue[0]" @input="(value) => setFilterValue([value])" />
              <div class="custom-filter-footer">
                <a-button @click="handleFilterReset">重置</a-button>
                <a-button @click="handleFilterConfirm">确定</a-button>
              </div>
            </a-space>
          </div>
        </template>

        <template #columns>
          <a-table-column :width="80">
            <template #cell="{ record }">
              <div>
                <a-tag color="arcoblue" v-if="record.uuid === user.uuid" size="small">我的记录</a-tag>
                <a-tag color="orangered" size="small" v-else>关联记录</a-tag>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="学号" :width="110" data-index="lepao_account" ellipsis tooltip :filterable="{
            filter: (value, record) => (record.lepao_account ?? '').includes(value),
            slotName: 'name-filter',
            icon: () => h(IconSearch)
          }"></a-table-column>
          <a-table-column title="账号名称" :width="140" :filterable="{
            filter: (value, record) => (record.name ?? '').includes(value),
            slotName: 'name-filter',
            icon: () => h(IconSearch)
          }">
            <template #cell="{ record }">
              <a-avatar :size="30">
                <img :alt="record.name ?? ''"
                  :src="record.user_avatar || 'https://lepao-cloud.xxoo365.top/view.php/25aa126dc406974ff3579a99a2c6501a.png'" />
              </a-avatar>
              {{ record.name }}
            </template>

          </a-table-column>
          <a-table-column title="状态" ellipsis tooltip :width="230">
            <template #cell="{ record }">
              <div class="state">
                <div
                  class="circle"
                  :class="recordDisplay(record).statusLevel"
                ></div>
                {{ recordDisplay(record).statusText }}
                <div class="progress" v-if="record.state === 0 && record.lepao_schedule">
                  <a-progress size="mini" :percent="record.lepao_schedule.current / record.lepao_schedule.total"/>
                </div>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="乐跑跑区" :filterable="{
            filter: (value, record) => (recordDisplay(record).routeRunZoneName ?? '').includes(value),
            slotName: 'name-filter',
            icon: () => h(IconSearch)
          }" :width="160">
            <template #cell="{ record }">
              <a-tag v-if="recordDisplay(record).routeRunZoneName" size="small">
                {{ recordDisplay(record).routeRunZoneName }}
              </a-tag>
              <span v-else>—</span>
            </template>
          </a-table-column>
          <a-table-column title="预计距离" :width="110" ellipsis tooltip>
            <template #cell="{ record }">
              <span v-if="recordDisplay(record).expectedKm != null">
                {{ formatKm(recordDisplay(record).expectedKm) }}
              </span>
              <span v-else>—</span>
            </template>
          </a-table-column>
          <a-table-column title="实际距离" :width="110" ellipsis tooltip>
            <template #cell="{ record }">
              {{ formatKm(recordDisplay(record).distance) }}
            </template>
          </a-table-column>
          <a-table-column title="扣费里程" :width="110" ellipsis tooltip>
            <template #cell="{ record }">
              <span v-if="recordDisplay(record).officialKm != null && Number.isFinite(Number(recordDisplay(record).officialKm))">
                {{ formatKm(recordDisplay(record).officialKm) }}
              </span>
              <span v-else>—</span>
            </template>
          </a-table-column>
          <a-table-column title="跑步时长" :width="100" ellipsis tooltip>
            <template #cell="{ record }">
              {{ formatSecondsToMinSec(recordDisplay(record).timeSec) }}
            </template>
          </a-table-column>
          <a-table-column title="平均配速" :width="90" ellipsis tooltip>
            <template #cell="{ record }">
              {{ formatPace(recordDisplay(record).timeSec, recordDisplay(record).distance) }}
            </template>
          </a-table-column>
          <a-table-column title="乐跑时间" :width="150" ellipsis tooltip>
            <template #cell="{ record }">
              {{ stramptoTime(record.time) }}
            </template>
          </a-table-column>
          <a-table-column title="" :width="100" fixed="right">
            <template #cell="{ record }">
              <a-button @click="$router.push(`/lepao/recordDetail/${record.id}`)">查看详情</a-button>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>
  </div>

</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, h } from 'vue'
import { lepaoRecords } from '@/api/lepao'
import {
  parseLepaoRecordRow,
  formatSecondsToMinSec,
  formatPace,
  formatKm
} from '@/utils/lepaoRecord'
import { Notification } from '@arco-design/web-vue'
import { IconSearch } from '@arco-design/web-vue/es/icon'
import { useUserStore } from '@/store/modules/user'
import { useRoute } from 'vue-router'
import { getNotice, getSemesterTimestamps } from '@/utils/util'

const notice = ref('')

const GetNotice = async () => {
  const { path } = useRoute()
  const res = await getNotice(path)
  notice.value = res
}

const data = ref([])
const loading = ref(false)
const user = ref('')
const getuser = async () => {
  const userStore = useUserStore()
  let userInfo = await userStore.getInfo()
  user.value = userInfo
}

getuser()

const queryData = reactive({
  name: '',
  lepao_account: '',
  email: '',
  queryTime: []
})

const pagination = reactive({
  total: 0,
  current: 1,
  pagesize: 20
})

const search = () => {
  pagination.current = 1
  getRecords()
}

const reset = () => {
  pagination.current = 1
  queryData.name = ''
  queryData.lepao_account = ''
  queryData.email = ''
  queryData.area = ''
  queryData.queryTime = getSemesterTimestamps()
  getRecordsAsync()
}

const getRecords = async () => {
  try {
    const reqData = {
      ...queryData,
      pagesize: pagination.pagesize,
      current: pagination.current
    }
    const res = await lepaoRecords(reqData)
    if (!res || res.code !== 0)
      return Notification.error({
        title: '获取乐跑记录失败！',
        content: res?.msg ?? '请稍后再试'
      })
    data.value = res.data
    pagination.total = res.pagination.total
  } catch (error) {
    Notification.error({
      title: '获取乐跑记录失败！',
      content: error.message || '请稍后再试'
    })
  }
}

const getRecordsAsync = async () => {
  loading.value = true
  try {
    await getRecords()
  } finally {
    loading.value = false
  }
}

// 分页 - 页码变化
const handlePageChange = (page) => {
  pagination.current = page
  getRecordsAsync()
}

// 分页 - 每页条数变化
const handlePageSizeChange = (size) => {
  pagination.pagesize = size
  pagination.current = 1 // 页大小变化后回到第一页
  getRecordsAsync()
}

const stramptoTime = (time) => {
  return new Date(time).toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
}

const recordDisplay = (record) => parseLepaoRecordRow(record)

let timer = null

// 轮询
const startPolling = () => {
  if (!timer) {
    timer = setInterval(async () => {
      await getRecords()
    }, 5000)
  }
}

// 停止轮询
const stopPolling = () => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
}

onMounted(() => {
  queryData.queryTime = getSemesterTimestamps()
  getRecordsAsync()
  GetNotice()
  startPolling()
})

onUnmounted(() => {
  stopPolling()
})
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}

.table {
  margin-top: 15px;
  font-family: -apple-system, BlinkMacSystemFont;

  .state {
    display: flex;
    align-items: center;

    .progress {
      margin-left: 5px;
    }

    .circle {
      border-radius: 50%;
      height: 8px;
      min-height: 8px;
      width: 8px;
      min-width: 8px;
      margin-right: 5px;
    }

    .running {
      background-color: rgb(var(--orange-6));
    }

    .success {
      background-color: rgb(var(--green-6));
    }

    .sync {
      background-color: rgb(var(--blue-6));
    }

    .fail {
      background-color: rgb(var(--red-6));
    }
  }
}

.custom-filter {
  padding: 20px;
  background: var(--color-bg-5);
  border: 1px solid var(--color-neutral-3);
  border-radius: var(--border-radius-medium);
  box-shadow: 0 2px 5px rgb(0 0 0 / 10%);
}

.custom-filter-footer {
  display: flex;
  justify-content: space-between;
}
</style>