<template>

  <div class="store-page">
    <Breadcrumb />
    <a-card title="乐跑记录">
      <AppQueryFilter>
      <a-row class="query-row">
        <a-col :flex="'1000px'" class="query-main">
          <a-form class="queryForm app-query-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="create_user" label="创建用户">
                  <a-input v-model="queryData.create_user" placeholder="请输入创建用户" allow-clear />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="lepao_account" label="学号">
                  <a-input-number v-model="queryData.lepao_account" placeholder="请输入学号" :step="1" :precision="0"
                    allow-clear />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="email" label="通知邮箱">
                  <EmailAutoComplete 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 class="query-divider" style="height: 84px" direction="vertical" />
        <a-col :flex="1" class="app-query-actions">
          <a-space class="query-actions-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>
      </AppQueryFilter>

      <a-table :data="data" :bordered="false" hoverable class="table" :loading="loading" :scroll="{ x: 1650 }" :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 title="所属用户" :width="160">
            <template #cell="{ record }">
              <a-avatar :size="30">
                <img :alt="record.username ?? ''"
                  :src="record.avatar || 'https://lepao-cloud.xxoo365.top/view.php/25aa126dc406974ff3579a99a2c6501a.png'" />
              </a-avatar>
              {{ record.username }}
            </template>
          </a-table-column>
          <a-table-column title="账号名称" :filterable="{
            filter: (value, record) => (record.name ?? '').includes(value),
            slotName: 'name-filter',
            icon: () => h(IconSearch)
          }" :width="140">
            <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="学号" :width="120" 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="120" ellipsis tooltip>
            <template #cell="{ record }">
              <a-tag :color="record.run_mode === 'manual' ? 'orangered' : 'arcoblue'">
                {{ record.run_mode === 'manual' ? '手动乐跑' : '自动乐跑' }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="状态" ellipsis tooltip :width="230">
            <template #cell="{ record }">
              <div class="state">
                <div class="circle one" v-if="record.result.record_failed_reason === '自动确认有效'"></div>
                <div class="circle else" v-else></div>
                {{ record.result.record_failed_reason }}
              </div>
            </template>
          </a-table-column>
          <a-table-column title="跑区" :filterable="{
            filter: (value, record) => (record.result.pass_tit ?? '').includes(value),
            slotName: 'name-filter',
            icon: () => h(IconSearch)
          }" :width="220">
            <template #cell="{ record }">
              {{ record.result.pass_tit }}
            </template>
          </a-table-column>
          <a-table-column title="乐跑距离" :width="120" ellipsis tooltip>
            <template #cell="{ record }">
              {{ record.result.distance }} Km
            </template>
          </a-table-column>
          <a-table-column title="跑步时长" :width="120" ellipsis tooltip>
            <template #cell="{ record }">
              {{ formatSecondsToMinSec(record.result.time) }}
            </template>
          </a-table-column>
          <a-table-column title="平均配速" :width="120" ellipsis tooltip>
            <template #cell="{ record }">
              {{ calculatePace(record.result.time, record.result.distance) }}
            </template>
          </a-table-column>
          <a-table-column title="乐跑时间" :width="175" ellipsis tooltip>
            <template #cell="{ record }">
              {{ stramptoTime(record.time) }}
            </template>
          </a-table-column>
          <a-table-column title="" :width="100" :fixed="tableFixed('right')">
            <template #cell="{ record }">
              <a-button @click="openDetail(record)">查看详情</a-button>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>
  </div>

</template>

<script setup>
import { ref, reactive, onMounted, h } from 'vue'
import { useRouter } from 'vue-router'
import { adminLepaoRecords } from '@/api/lepao'
import { Notification, Message } from '@arco-design/web-vue'
import { IconSearch } from '@arco-design/web-vue/es/icon'
import { getSemesterTimestamps } from '@/utils/util'
import { useResponsiveTable } from '@/hooks/useResponsiveTable'

const { tableFixed } = useResponsiveTable()

const data = ref([])
const loading = ref(false)
const router = useRouter()

const openDetail = (record) => {
  const key = record.public_id || record.id
  if (!key) {
    return Message.warning('该记录缺少可用标识，无法打开详情')
  }
  return router.push(`/admin/lepaoRecords/${encodeURIComponent(String(key))}`)
}

const queryData = reactive({
  name: '',
  lepao_account: '',
  email: '',
  create_user: '',
  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.create_user = ''
  queryData.queryTime = getSemesterTimestamps()
  getRecords()
}

const getRecords = async () => {
  try {
    loading.value = true
    const reqData = {
      ...queryData,
      pagesize: pagination.pagesize,
      current: pagination.current
    }
    const res = await adminLepaoRecords(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 || '请稍后再试'
    })
  } finally {
    loading.value = false
  }
}

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

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

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

function calculatePace(seconds, kilometers) {
  const paceInSeconds = seconds / kilometers;
  const minutes = Math.floor(paceInSeconds / 60);
  const remainingSeconds = Math.round(paceInSeconds % 60);

  return `${minutes}'${remainingSeconds.toString().padStart(2, '0')}''`;
}

function formatSecondsToMinSec(totalSeconds) {
  const minutes = Math.floor(totalSeconds / 60);
  const seconds = totalSeconds % 60;

  return `${minutes}分${seconds.toString().padStart(2, '0')}秒`;
}

onMounted(() => {
  queryData.queryTime = getSemesterTimestamps()
  getRecords()
})
</script>

<style scoped lang="less">
.query-row {
  margin-bottom: 10px;
}

.query-main {
  min-width: 0;
}

.query-actions-space {
  width: 100%;
}

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

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

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

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

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

    .else {
      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;
}

@media (max-width: 768px) {
  .query-row {
    display: block;
  }

  .query-divider {
    display: none;
  }

  .query-actions-space {
    margin-top: 4px;
    flex-direction: row !important;
    gap: 10px !important;
  }

  .query-actions-space :deep(.arco-btn) {
    flex: 1;
  }
}
</style>