<template>
    <div class="container">
        <Breadcrumb :items="['乐跑记录', '记录详情']" />
        <a-card title="记录详情">
            <a-skeleton animation :loading="loading">
                <a-space direction="vertical" :style="{ width: '100%' }" size="large">
                    <a-skeleton-shape size="large" />
                    <a-skeleton-line :rows="5" />
                </a-space>
            </a-skeleton>
            <a-descriptions :data="info" :column="2" />
            <MapContainer
                v-if="showMap && pathForMap.length > 0"
                :point_list="pointListForMap"
                :log_list="logListForMap"
                :pathData="pathForMap"
                threeD
                style="margin-top: 10px;"
            />
        </a-card>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { GetRecordDetail } from '@/api/lepao'
import { Notification } from '@arco-design/web-vue'
import { useRoute } from 'vue-router'
import MapContainer from '@/components/Map/MapContainer.vue'
import {
    buildRecordDetailInfo,
    parseLepaoRecordRow,
    normalizePointData
} from '@/utils/lepaoRecord'
import { useUserStore } from '@/store/modules/user'

const route = useRoute()

const loading = ref(false)
const showMap = ref(false)
const data = ref({})
const info = ref([])
const isAdmin = ref(false)

const pathForMap = computed(() => {
    const poly = data.value.path_polyline
    if (Array.isArray(poly) && poly.length > 0) return poly
    return []
})

const pointListForMap = computed(() => {
    const row = parseLepaoRecordRow({
        result: data.value.result,
        jkes_record: data.value.jkes_record,
        run_zone_name: data.value.run_zone_name,
        path_run_zone_name: data.value.path_run_zone_name,
        path_distance: data.value.path_distance
    })
    return row.pointList || []
})

const logListForMap = computed(() => normalizePointData(data.value.point_data))

const getRecordDetail = async (id) => {
    try {
        loading.value = true
        showMap.value = false
        const res = await GetRecordDetail({ id })
        if (!res || res.code !== 0)
            return Notification.error({
                title: '获取路径数据失败！',
                content: res?.msg ?? '请稍后再试'
            })

        data.value = res.data
        showMap.value = true
        info.value = buildRecordDetailInfo(res.data, { isAdmin: isAdmin.value })
    } catch (error) {
        Notification.error({
            title: '获取路径数据失败！',
            content: error.message || '请稍后再试'
        })
    } finally {
        loading.value = false
    }
}

onMounted(async () => {
    const userStore = useUserStore()
    const userInfo = await userStore.getInfo()
    isAdmin.value = Array.isArray(userInfo?.roles) && userInfo.roles.includes('admin')
    getRecordDetail(route.params.id)
})
</script>

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