<template>
    <div class="main_container custom_container">
        <div class="page_item top_header">
             <el-button  class="button_default_background" @click="router.go(-1)">
                <el-icon class="img"><ArrowLeftBold /></el-icon>
                返回
            </el-button>

            <div class="people_info">
                <div>
                    <span class="label">学校：</span>
                    <span class="value">{{ detailParams.schoolName }}</span>
                </div>
                <div>
                    <span class="label">账户：</span>
                    <span class="value">{{ detailParams.userAccount }}</span>
                </div>
                <div><span class="label">姓名：</span>
                    <span class="value">{{ detailParams.userName }}</span>
                </div>
            </div>

            <div class="page_search" >
                <div class="search_content">
                    <div class="content_left">
                        <FormSearchGroup :searchList="peopleLogSearchList" @searchChange="handleSearchChange"></FormSearchGroup>
                    </div>
                    <div class="content_right">
                        <div class="desc">
                            默认展示最近3天操作记录
                        </div>
                    </div>
                </div>
            </div>
        </div>


        <div class="page_jg_20"></div>

        <div class="page_item end_item">
            <HonorTimeLine :honorList="peopleLogList"></HonorTimeLine>
        </div>
    </div>
</template>  

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ArrowLeftBold } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import FormSearchGroup from '@/baseComponents/FormSearchGroup.vue';
import { peopleLogSearchList } from './formSearchGroup';
import HonorTimeLine from '@/baseComponents/HonorTimeLine.vue';
import { getLogDetailApi } from '@/api/logMonitor';

const route = useRoute()
const router = useRouter()

const detailParams = reactive({
    schoolId: 0,
    userId: 0,
    accountTypeCode: 0,
    moduleCode: 0,
    schoolName: '',
    userAccount: '',
    userName: '',
})

// 详情搜索参数
const detailSearchParams = reactive({
    startTime: '',
    endTime: '',
})

const peopleLogList = ref<any[]>([])

// 获取日志详情
const getLogDetailData = async () => {
    try {
        const params = {
            schoolId: detailParams.schoolId,
            userId: detailParams.userId,
            accountTypeCode: detailParams.accountTypeCode,
            moduleCode: detailParams.moduleCode,
            startTime: detailSearchParams.startTime,
            endTime: detailSearchParams.endTime,
        }
        const res = await getLogDetailApi(params)
        const data = res.data || res
        
        peopleLogList.value = (data || []).map((item: any, index: number) => ({
            id: String(index),
            awardDatetime: item.createTime || '',
            certPicUrl: '',
            honorTypeName: '',
            honorName: item.operation || '',
            teacherName: item.ip || '',
            radioData: [],
            inputData: [],
            createdAt: item.createTime || '',
            reviewStatus: '',
        }))
    } catch (err) {
        console.error('getLogDetailApi 请求失败:', err)
    }
}

// 处理搜索变化
const handleSearchChange = (data: Record<string, any>, key: string) => {
    if (key === 'dateRange') {
        const range = data.dateRange
        if (Array.isArray(range) && range.length === 2 && range[0] && range[1]) {
            const start = new Date(range[0])
            const end = new Date(range[1])
            const diffDays = Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24))
            if (diffDays > 30) {
                ElMessage.warning('日志选择最大范围30天')
                return
            }
            detailSearchParams.startTime = formatDateTime(start, true)
            detailSearchParams.endTime = formatDateTime(end, false)
        } else {
            detailSearchParams.startTime = ''
            detailSearchParams.endTime = ''
        }
    }
    getLogDetailData()
}

// 格式化日期时间，isStart为true时返回 00:00:00，为false时返回 23:59:59
const formatDateTime = (date: Date, isStart: boolean) => {
    if (!date) return ''
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const time = isStart ? '00:00:00' : '23:59:59'
    return `${year}-${month}-${day} ${time}`
}

// 获取默认日期范围（最近3天）
const getDefaultDateRange = () => {
    const end = new Date()
    const start = new Date()
    start.setDate(start.getDate() - 2)
    return [start, end]
}

// 初始化
onMounted(() => {
    detailParams.schoolId = Number(route.query.schoolId) || 0
    detailParams.userId = Number(route.query.userId) || 0
    detailParams.accountTypeCode = Number(route.query.accountTypeCode) || 0
    detailParams.moduleCode = Number(route.query.moduleCode) || 0
    detailParams.schoolName = (route.query.schoolName as string) || ''
    detailParams.userAccount = (route.query.userAccount as string) || ''
    detailParams.userName = (route.query.userName as string) || ''

    // 默认最近3天
    const defaultRange = getDefaultDateRange()
    peopleLogSearchList.value[0].defaultValue = defaultRange
    detailSearchParams.startTime = formatDateTime(defaultRange[0], true)
    detailSearchParams.endTime = formatDateTime(defaultRange[1], false)

    getLogDetailData()
})
</script>




<style lang="scss" scoped>

.top_header{
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap:20px;
    padding:10px 20px;

    .people_info{
        flex-shrink: 0;
        display: flex;
        gap:20px;
        font-size: 14px;
        .label{
            color:#333;
            font-weight: 600;
        }
        .value{
            color: #999;
        }
    }

    .page_search{
        .search_content{
            justify-content: flex-end;
            gap:20px;
            .content_right{
                .desc{
                    font-size: 14px;
                }
            }
        }
    }
}
</style>
