<template>
    <view class="detail-page">
        <scroll-view class="detail-content" :scroll-y="true">
            <!-- 工单信息 -->
            <view class="info-section">
                <view class="section-title">
                    <text class="section-title-text">工单信息</text>
                </view>
                <view class="info-card">
                    <view class="info-item">
                        <text class="info-label">工单编码</text>
                        <text class="info-value">{{ detailData.workOrderProjectNo ?? '' }}</text>
                    </view>
                    <view class="info-item">
                        <text class="info-label">工单类型</text>
                        <text class="info-value">{{ detailData.orderType == 1 ? '维修工单' : '维保工单' }}</text>
                    </view>
                    <view class="info-item">
                        <text class="info-label">风机编号</text>
                        <text class="info-value">{{ detailData.pcsDeviceName ?? '' }}</text>
                    </view>
                    <view class="info-item">
                        <text class="info-label">场站</text>
                        <text class="info-value">{{ detailData.pcsStationName ?? '' }}</text>
                    </view>
                    <view class="info-item">
                        <text class="info-label">工作负责人</text>
                        <text class="info-value">{{ detailData.teamLeaderName ?? '' }}</text>
                    </view>
                    <view class="info-item">
                        <text class="info-label">工作结束时间</text>
                        <text class="info-value">{{ detailData.realEndTime ?? '' }}</text>
                    </view>
                    <view class="info-item">
                        <text class="info-label">状态</text>
                        <text class="info-value">{{ getScoringStatusText(detailData.scoringStatus) }}</text>
                    </view>
					<view class="info-item" v-if="detailData.orderType == 1 && detailData.maintenanceType != null && detailData.maintenanceType != ''">
					    <text class="info-label">检修类型</text>
					    <text class="info-value">{{ getMaintenanceTypeText(detailData.maintenanceType) }}</text>
					</view>
					<view class="info-item" v-if="detailData.orderType == 2 && detailData.inspectionType != null && detailData.inspectionType != ''">
					    <text class="info-label">维保类型</text>
					    <text class="info-value">{{ getInspectionTypeText(detailData.inspectionType) }}</text>
					</view>
					<!-- <view class="info-item" v-if="detailData.workSummary != null && detailData.workSummary != ''">
					    <text class="info-label">{{ detailData.orderType == 1 ? '维修总结' : '维保总结' }}</text>
					    <text class="info-value">{{ detailData.workSummary ?? '' }}</text>
					</view> -->
                </view>
            </view>

            <!-- 工作总结 -->
           <view class="info-section" v-if="detailData.workSummary != null && detailData.workSummary != ''">
                <view class="section-title">
                    <text class="section-title-text">{{ detailData.orderType == 1 ? '维修总结' : '维保总结' }}</text>
                </view>
                <view class="info-card">
                    <view class="summary-content">
                        <text class="summary-text">{{ detailData.workSummary ?? '' }}</text>
                    </view>
                </view>
            </view>
			
            <!-- 得分明细 -->
            <view class="info-section">
                <view class="section-title">
                    <text class="section-title-text">得分明细</text>
                </view>
                <view class="info-card">
                    <!-- 表格头部 -->
                    <view class="table-header">
                        <text class="table-cell score-col">检修员</text>
                        <text class="table-cell score-col">自评得分</text>
                        <text class="table-cell score-col">复评得分</text>
                        <text class="table-cell score-col">终评得分</text>
                        <!-- <text class="table-cell score-col">确认状态</text> -->
                    </view>
                    
                    <!-- 表格行数据 -->
                    <view class="table-row" v-for="(person, index) in detailData.scorePersonList" :key="index">
                        <text class="table-cell score-col">
                            {{ person.nickName }}
                            <text class="table-cell score-col" v-if="person.isLeader == 1">(负责人)</text>
                        </text>
                        <text class="table-cell score-col">{{ person.selfScore !== null ? formatNumber(person.selfScore) : '-' }}</text>
                        <text class="table-cell score-col">{{ person.reviewScore !== null ? formatNumber(person.reviewScore) : '-' }}</text>
                        <text class="table-cell score-col">{{ person.finalScore !== null ? formatNumber(person.finalScore) : '-' }}</text>
                        <!-- <text class="table-cell score-col">{{ person.confirmStatus !== null ? getConfirmStatusText(person.confirmStatus) : '-' }}</text> -->
                    </view>
                </view>
            </view>
        </scroll-view>

        <!-- 加载中状态 -->
        <view v-if="loading" class="loading-mask">
            <text class="loading-text">加载中...</text>
        </view>
    </view>
</template>

<script setup lang="uts">
    import { ref, reactive } from 'vue'
    import { getOrderScoreDetail } from '../../../api/score/index'
    import { getDictDataByType } from '@/api/dict/index'
    import type { SysDictData } from '@/types/dict'

    // 人员得分对象
    type ScorePersonItem = {
        nickName: string | null
        selfScore: number | null
        reviewScore: number | null
        finalScore: number | null
        confirmStatus: number | null
        isLeader: number | null
    }

    // 详情数据
    type DetailDataType = {
        orderType: Number
        id: Number
        workOrderProjectNo: string | null
        pcsDeviceName: string | null
        pcsStationName: string | null
        teamLeaderName: string | null
        realEndTime: string | null
        scoringStatus: string | null
        workSummary: string | null
        maintenanceType: string | null
        inspectionType: string | null
        itemCompletionFactor: number | null
        itemCompletionFactorSum: number | null
        scorePersonList: ScorePersonItem[]
    }
    
    const detailData = reactive<DetailDataType>({
        orderType: 0 as Number,
        id: 0 as Number,
        workOrderProjectNo: null,
        pcsDeviceName: null,
        pcsStationName: null,
        teamLeaderName: null,
        realEndTime: null,
        scoringStatus: null,
        workSummary: null,
        maintenanceType: null,
        inspectionType: null,
        itemCompletionFactor: null,
        itemCompletionFactorSum: null,
        scorePersonList: []
    })

    const loading = ref<boolean>(false) 
    
    // 字典数据
    const scoringStatusDictList = ref<SysDictData[]>([])
    const maintenanceTypeDictList = ref<SysDictData[]>([])
    const inspectionTypeDictList = ref<SysDictData[]>([])

    // 获取工单评分状态字典
    const loadScoringStatusDictList = async (): Promise<void> => {
        try {
            const result = await getDictDataByType('gxt_scoring_status')
            const resultObj = result as UTSJSONObject
            
            if (resultObj['code'] == 200) {
                const data = resultObj['data'] as any[]
                const dictData: SysDictData[] = []
                
                if (data != null && data.length > 0) {
                    for (let i = 0; i < data.length; i++) {
                        const item = data[i] as UTSJSONObject
                        const dictItem: SysDictData = {
                            dictValue: item['dictValue'] as string | null,
                            dictLabel: item['dictLabel'] as string | null,
                            dictCode: null,
                            dictSort: null,
                            dictType: null,
                            cssClass: null,
                            listClass: null,
                            isDefault: null,
                            status: null,
                            default: null,
                            createTime: null,
                            remark: null
                        }
                        dictData.push(dictItem)
                    }
                }
                
                scoringStatusDictList.value = dictData
            }
        } catch (e: any) {
            console.error('获取工单评分状态字典失败:', e.message)
        }
    }
    
    // 获取检修类型字典
    const loadMaintenanceTypeDictList = async (): Promise<void> => {
        try {
            const result = await getDictDataByType('gxt_maintenance_type')
            const resultObj = result as UTSJSONObject
            
            if (resultObj['code'] == 200) {
                const data = resultObj['data'] as any[]
                const dictData: SysDictData[] = []
                
                if (data != null && data.length > 0) {
                    for (let i = 0; i < data.length; i++) {
                        const item = data[i] as UTSJSONObject
                        const dictItem: SysDictData = {
                            dictValue: item['dictValue'] as string | null,
                            dictLabel: item['dictLabel'] as string | null,
                            dictCode: null,
                            dictSort: null,
                            dictType: null,
                            cssClass: null,
                            listClass: null,
                            isDefault: null,
                            status: null,
                            default: null,
                            createTime: null,
                            remark: null
                        }
                        dictData.push(dictItem)
                    }
                }
                
                maintenanceTypeDictList.value = dictData
            }
        } catch (e: any) {
            console.error('获取检修类型字典失败:', e.message)
        }
    }
    
    // 获取维保类型字典
    const loadInspectionTypeDictList = async (): Promise<void> => {
        try {
            const result = await getDictDataByType('gxt_inspection_type')
            const resultObj = result as UTSJSONObject
            
            if (resultObj['code'] == 200) {
                const data = resultObj['data'] as any[]
                const dictData: SysDictData[] = []
                
                if (data != null && data.length > 0) {
                    for (let i = 0; i < data.length; i++) {
                        const item = data[i] as UTSJSONObject
                        const dictItem: SysDictData = {
                            dictValue: item['dictValue'] as string | null,
                            dictLabel: item['dictLabel'] as string | null,
                            dictCode: null,
                            dictSort: null,
                            dictType: null,
                            cssClass: null,
                            listClass: null,
                            isDefault: null,
                            status: null,
                            default: null,
                            createTime: null,
                            remark: null
                        }
                        dictData.push(dictItem)
                    }
                }
                
                inspectionTypeDictList.value = dictData
            }
        } catch (e: any) {
            console.error('获取维保类型字典失败:', e.message)
        }
    }

    // 获取工单评分状态文本
    const getScoringStatusText = (status: string | null): string => {
        if (status == null || status == '') return ''
        
        const dictItem = scoringStatusDictList.value.find(dict => dict.dictValue == status)
        return dictItem != null ? (dictItem.dictLabel ?? status) : status
    }
    
    // 获取检修类型文本
    const getMaintenanceTypeText = (type: string | null): string => {
        if (type == null || type == '') return ''
        
        const dictItem = maintenanceTypeDictList.value.find(dict => dict.dictValue == type)
        return dictItem != null ? (dictItem.dictLabel ?? type) : type
    }
    
    // 获取维保类型文本
    const getInspectionTypeText = (type: string | null): string => {
        if (type == null || type == '') return ''
        
        const dictItem = inspectionTypeDictList.value.find(dict => dict.dictValue == type)
        return dictItem != null ? (dictItem.dictLabel ?? type) : type
    }
    
    // 获取确认状态文本
    const getConfirmStatusText = (status: number | null): string => {
        if (status == null) return '未知'
        
        switch (status) {
            case 0: return '未确认'
            case 1: return '已确认'
            case 2: return '已反馈'
            default: return '未知状态'
        }
    }

    // Format number to fixed 2 decimal places
    const formatNumber = (value: number | string | null): string => {
        if (value == null) return '0.00'
        // Convert value to string properly to avoid ClassCastException
        const stringValue = value.toString()
        const num = parseFloat(stringValue)
        if (isNaN(num)) return '0.00'
        return num.toFixed(2)
    }

    // 加载详情数据
    const loadDetail = async (id: string, orderType: string): Promise<void> => {
        try {
            loading.value = true
            
            const result = await getOrderScoreDetail(orderType, id)
            
            // 提取响应数据
            const resultObj = result as UTSJSONObject
            const code = resultObj.get('code') as number
            const data = resultObj.get('data') as UTSJSONObject | null

            if (code == 200 && data != null) {
                // 填充基本数据
                const orderTypeValue = data.get('orderType')
                detailData.orderType = (orderTypeValue != null ? (orderTypeValue as number) : 0) as Number
                const idValue = data.get('id')
                detailData.id = (idValue != null ? (idValue as number) : 0) as Number
                detailData.workOrderProjectNo = data.get('workOrderProjectNo') as string | null
                detailData.pcsDeviceName = data.get('pcsDeviceName') as string | null
                detailData.pcsStationName = data.get('pcsStationName') as string | null
                detailData.teamLeaderName = data.get('teamLeaderName') as string | null
                detailData.realEndTime = data.get('realEndTime') as string | null
                detailData.scoringStatus = data.get('scoringStatus') as string | null
                
                // 根据工单类型设置总结内容
                detailData.workSummary = (detailData.orderType == 1 ? 
                    data.get('content') : 
                    data.get('realContent')) as string | null
                
                // 类型信息
                detailData.maintenanceType = data.get('maintenanceType') as string | null
                detailData.inspectionType = data.get('inspectionType') as string | null
                const itemCompletionFactorValue = data.get('itemCompletionFactor')
                detailData.itemCompletionFactor = itemCompletionFactorValue != null ? 
                    (itemCompletionFactorValue as number).toDouble() : null
                const itemCompletionFactorSumValue = data.get('itemCompletionFactorSum')
                detailData.itemCompletionFactorSum = itemCompletionFactorSumValue != null ? 
                    (itemCompletionFactorSumValue as number).toDouble() : null
                
                // 人员得分列表
                const scorePersonList = (detailData.orderType == 1 ? 
                    data.get('repairOrderPersonList') : 
                    data.get('workOrderPersonList')) as UTSJSONObject[] | null
                
                if (scorePersonList != null) {
                    const processedList: ScorePersonItem[] = []
                    for (let i = 0; i < scorePersonList.length; i++) {
                        const person = scorePersonList[i]
                        const item: ScorePersonItem = {
                            nickName: person.get('nickName') as string | null,
                            selfScore: (person.get('selfScore') != null ? person.get('selfScore') as number : null),
                            reviewScore: (person.get('reviewScore') != null ? person.get('reviewScore') as number : null),
                            finalScore: (person.get('finalScore') != null ? person.get('finalScore') as number : null),
                            confirmStatus: (person.get('confirmStatus') != null ? person.get('confirmStatus') as number : null),
                            isLeader: (person.get('isLeader') != null ? person.get('isLeader') as number : null)
                        }
                        processedList.push(item)
                    }
                    detailData.scorePersonList = processedList
                } else {
                    detailData.scorePersonList = []
                }
            } else {
                const msg = (resultObj.get('msg') as string | null) ?? '加载失败'
                uni.showToast({
                    title: msg,
                    icon: 'none'
                })
            }
        } catch (e: any) {
            uni.showToast({
                title: e.message ?? '加载失败',
                icon: 'none'
            })
        } finally {
            loading.value = false
        }
    }

    // 页面加载
    onLoad((options: any) => {
        const params = options as UTSJSONObject
        const id = params.get('id') as string | null
        const orderType = params.get('orderType') as string | null
        if (id != null && orderType != null) {
            loadScoringStatusDictList()
            loadMaintenanceTypeDictList()
            loadInspectionTypeDictList()
            loadDetail(id, orderType)
        }
    })
</script>

<style lang="scss">
    .detail-page {
        flex: 1;
        background-color: #e8f0f9;
    }

    .detail-content {
        flex: 1;
        padding: 20rpx 0;
    }

    .info-section {
        margin: 0 30rpx 24rpx;

        .section-title {
            position: relative;
            padding-left: 20rpx;
            margin-bottom: 20rpx;

            &::before {
                position: absolute;
                left: 0;
                top: 50%;
                transform: translateY(-50%);
                width: 8rpx;
                height: 32rpx;
                background-color: #007aff;
                border-radius: 4rpx;
            }

            &-text {
                font-size: 32rpx;
                font-weight: bold;
                color: #333333;
            }
        }

        .info-card {
            background-color: #ffffff;
            border-radius: 16rpx;
            padding: 30rpx;

            .info-item {
                flex-direction: row;
                padding: 20rpx 0;
                border-bottom: 1rpx solid #f0f0f0;

                &:last-child {
                    border-bottom: none;
                }

                .info-label {
                    width: 240rpx;
                    font-size: 28rpx;
                    color: #666666;
                    white-space: nowrap;
                }

                .info-value {
                    flex: 1;
                    font-size: 28rpx;
                    color: #333333;
                    text-align: right;
                }
            }

            .summary-content {
                .summary-text {
                    font-size: 28rpx;
                    color: #333333;
                    line-height: 44rpx;
                }
            }

            /* 表格样式 */
            .table-header, .table-row {
                flex-direction: row;
                padding: 20rpx 0;
                border-bottom: 1rpx solid #f0f0f0;
                
                &:last-child {
                    border-bottom: none;
                }
            }
            
            .table-header {
                background-color: #f8f8f8;
                font-weight: bold;
            }
            
            .table-cell {
                font-size: 26rpx;
                color: #333;
                text-align: center;
                
                &.name-col {
                    flex: 2;
                    text-align: left;
                }
                
                &.score-col {
                    flex: 1;
                }
                
                &.status-col {
                    flex: 1;
                }
            }
        }
    }

    .loading-mask {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        justify-content: center;
        align-items: center;
        background-color: rgba(0, 0, 0, 0.3);

        .loading-text {
            padding: 30rpx 60rpx;
            background-color: rgba(0, 0, 0, 0.7);
            color: #ffffff;
            font-size: 28rpx;
            border-radius: 12rpx;
        }
    }
</style>