<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.brand ?? '') + ' ' + (detailData.model ?? '') }}</text>
                    </view>
                    <!-- <view class="info-item">
                        <text class="info-label">创建时间</text>
                        <text class="info-value">{{ detailData.createTime ?? '' }}</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="chart-container">
                        <view style="width: 365rpx; height: 365rpx;">
                            <l-echart ref="chartRef" @finished="init"></l-echart>
                        </view>
                        <view class="chart-legend">
                            <view v-for="(item, index) in chartLegendData" :key="index" class="legend-item">
                                <view class="legend-left">
                                    <view class="legend-color" :style="{ backgroundColor: item.color }"></view>
                                    <text class="legend-name">{{ item.name }}</text>
                                </view>
                                <view class="legend-right">
                                    <text class="legend-value">{{ formatHours(item.value) }}h</text>
                                </view>
                            </view>
                        </view>
                    </view>
                    <view v-if="showCombinedLabel" class="combined-legend">
                        <view class="legend-left">
                            <view class="legend-color" :style="{ backgroundColor: colorMap.get('下发时长+准备时长') }"></view>
                            <text class="legend-name">下发时长+准备时长</text>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 工时明细 -->
            <!-- <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">{{ formatHours(detailData.issueHour) }}小时</text>
                    </view>
                    <view class="info-item">
                        <text class="info-label">接单时长</text>
                        <text class="info-value">{{ formatHours(detailData.acceptHour) }}小时</text>
                    </view>
                    <view class="info-item">
                        <text class="info-label">准备时长</text>
                        <text class="info-value">{{ formatHours(detailData.prepareHour) }}小时</text>
                    </view>
                    <view class="info-item">
                        <text class="info-label">作业时长</text>
                        <text class="info-value">{{ formatHours(detailData.workHour) }}小时</text>
                    </view>
                    <view class="info-item">
                        <text class="info-label">复运时长</text>
                        <text class="info-value">{{ formatHours(detailData.restartHour) }}小时</text>
                    </view>
                    <view class="info-item">
                        <text class="info-label">处理时长</text>
                        <text class="info-value">{{ formatHours(detailData.handleHour) }}小时</text>
                    </view>
                    <view class="info-item">
                        <text class="info-label">挂起时长</text>
                        <text class="info-value">{{ formatHours(detailData.suspendHour) }}小时</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 } from 'vue'
    import { getOrderHourDetail } from '../../../api/worktime/index'
    import type { orderInfo } from '../../../types/order'
    // #ifdef MP
    // 引入小程序依赖包，require只能是当前文件的相对路径
    const echarts = require('../../../../static/echarts.min.js')
    // #endif
    // #ifndef MP
    // 非小程序不需要引入
    const echarts = null
    // #endif
    
    // 详情数据
    const detailData = ref<orderInfo>({
        orderType: 0 as Number,
        id: 0 as Number,
        teamLeaderName: null,
        acceptUserName: null,
        acceptTime: null,
        assignTime:  null,
        assignUserName: null,
        status: 0 as Number,
        workOrderProjectNo: null,
        workOrderStatus: null,
        gxtCenterId: 0 as Number,
        gxtCenter: null,
        pcsStationId:  0 as Number,
        pcsStationName: null,
        pcsDeviceId: 0 as Number,
        pcsDeviceName: null,
        brand: null,
        model: null,
        createTime: null,
        workOrderFlowList: null,
        // 工时相关字段
        issueHour: 0 as Number,
        acceptHour: 0 as Number,
        prepareHour: 0 as Number,
        workHour: 0 as Number,
        restartHour: 0 as Number,
                    handleHour: 0 as Number,
                    suspendHour: 0 as Number,
					downtimeHour: 0 as Number,
    } as orderInfo)

    const loading = ref<boolean>(false)
    const chartData = ref<UTSJSONObject[]>([])
    const chartRef = ref<LEchartComponentPublicInstance | null>(null)
    const showCombinedLabel = ref<boolean>(false)

    // 图例数据类型
    type ChartLegendItem = {
        name: string
        value: number
        color: string
    }
    const chartLegendData = ref<ChartLegendItem[]>([])

    // 颜色配置
    //const chartColors = ['#5B9BF3', '#4DD4C0', '#FF9966', '#FF6B96', '#9B7FE8', '#FFD700', '#8A2BE2']
	const chartColors = ['#5B9BF3', '#4DD4C0', '#FF9966', '#FF6B96', '#9B7FE8', '#FFD700']
    // 固定颜色映射
    const colorMap = new Map<string, string>([
        ['下发时长', '#5B9BF3'],
        ['接单时长', '#4DD4C0'],
        ['准备时长', '#FF9966'],
        ['挂起时长', '#FF6B96'],
        ['作业时长', '#9B7FE8'],
        ['复运时长', '#FFD700'],
        ['下发时长+准备时长', '#ff0000']
    ])

    // 格式化小时数
    const formatHours = (hourValue: number | null): string => {
        if (hourValue == null) return '0.0'
        return (hourValue as number).toFixed(1)
    }

    const init = async () => {
        if(chartRef.value == null) return
        const chart = await chartRef.value!.init(echarts)
        
        // 检查数据是否有效
        if (chartData.value == null || chartData.value.length == 0) {
            return
        }

        // 计算总值用于百分比计算，只累加正值以确保百分比计算准确
        const total = chartData.value.reduce((sum, currentItem) => {
            const value = currentItem.get('value') as number;
            return sum + (value > 0 ? value : 0);
        }, 0);
        
        // 构建图表数据数组
        const seriesData = chartData.value.map((item: UTSJSONObject, index: number) => {
            const value = item.get('value') as number;
            const percent = total > 0 ? (value / total * 100) : 0;
            const name = item.get('name') as string;
            
            return {
                name: name,
                value: item.get('value'),
                label: {
                    // 如果百分比小于10%，不显示标签
                    show: percent >= 5
                },
				itemStyle: {
					color: colorMap.get(name) != null ? colorMap.get(name) : chartColors[index % chartColors.length]
				}
            }
        })

        // 构建完整的图表选项对象
        const option = {
            legend: {
                show: false
            },
            series: [{
                type: 'pie', 
                radius: ['30%', '90%'],
                center: ['50%', '50%'],
                label: {
                    show: true,
                    formatter: '{d}%',
                    position: 'inside',
                    color: '#fff',
                    fontSize: 12,
                    fontWeight: 'bold',
                    textShadow: '0 1px 3px rgba(0,0,0,0.5)'
                },
                data: seriesData
            }]
        } as UTSJSONObject

        // 使用正确的API调用来设置图表选项
        chart.setOption(option)
    }

    // 准备图表数据
    const prepareChartData = (data: orderInfo): void => {
        const chartItems = [] as UTSJSONObject[]
        const legendItems = [] as ChartLegendItem[]

        // 添加各项工时数据
        if (data.issueHour != null) {
			if (data.prepareHour != null && data.prepareHour < 0) {
				const item = {
					name: '下发时长+准备时长',
					value: data.issueHour + data.prepareHour
				} as UTSJSONObject
				chartItems.push(item)
				if((data.issueHour + data.prepareHour) > 0){
					showCombinedLabel.value = true
				}else{
					showCombinedLabel.value = false
				}
			}else{
				const item = {
				    name: '下发时长',
				    value: data.issueHour
				} as UTSJSONObject
				chartItems.push(item)
				showCombinedLabel.value = false
			} 
            const color = colorMap.get('下发时长')
            legendItems.push({
                name: '下发时长',
                value: data.issueHour,
                color: color != null ? color : '#5B9BF3'
            } as ChartLegendItem)
        }

        if (data.acceptHour != null) {
            const item = {name: '接单时长', value: data.acceptHour} as UTSJSONObject
            chartItems.push(item)
            const color = colorMap.get('接单时长')
            legendItems.push({
                name: '接单时长',
                value: data.acceptHour,
                color: color != null ? color : '#4DD4C0'
            } as ChartLegendItem)
        }

        if (data.prepareHour != null) {
			if (data.prepareHour >= 0) {
				const item = {name: '准备时长', value: data.prepareHour} as UTSJSONObject
				chartItems.push(item)
			}
            const color = colorMap.get('准备时长')
            legendItems.push({
                name: '准备时长',
                value: data.prepareHour,
                color: color != null ? color : '#FF9966'
            } as ChartLegendItem)
        }

		if (data.suspendHour != null) {
            const item = {name: '挂起时长', value: data.suspendHour} as UTSJSONObject
            chartItems.push(item)
            const color = colorMap.get('挂起时长')
            legendItems.push({
                name: '挂起时长',
                value: data.suspendHour,
                color: color != null ? color : '#FF6B96'
            } as ChartLegendItem)
        }

        if (data.workHour != null) {
            const item = {name: '作业时长', value: data.workHour} as UTSJSONObject
            chartItems.push(item)
            const color = colorMap.get('作业时长')
            legendItems.push({
                name: '作业时长',
                value: data.workHour,
                color: color != null ? color : '#9B7FE8'
            } as ChartLegendItem)
        }

        if (data.restartHour != null) {
            const item = {name: '复运时长', value: data.restartHour} as UTSJSONObject
            chartItems.push(item)
            const color = colorMap.get('复运时长')
            legendItems.push({
                name: '复运时长',
                value: data.restartHour,
                color: color != null ? color : '#FFD700'
            } as ChartLegendItem)
        }

        /* if (data.handleHour != null) {
            const item = {name: '处理时长', value: data.handleHour} as UTSJSONObject
            chartItems.push(item)
            legendItems.push({
                name: '处理时长',
                value: data.handleHour,
                color: chartColors[legendItems.length % chartColors.length]
            } as ChartLegendItem)
        } */

        
		if (data.downtimeHour != null) {
            /* const item = {name: '停运时长', value: data.downtimeHour} as UTSJSONObject
            chartItems.push(item) */
            legendItems.push({
                name: '停运时长',
                value: data.downtimeHour,
                //color: chartColors[legendItems.length % chartColors.length]
				color: '#ffffff'
            } as ChartLegendItem)
        }
        chartData.value = chartItems
        chartLegendData.value = legendItems

        // 如果图表已经初始化，则直接绘制
        if (chartRef.value != null && chartItems.length > 0) {
            init()
        }
    }

    // 加载详情数据
    const loadDetail = async (id: string, orderType: string): Promise<void> => {
        try {
            loading.value = true

            const result = await getOrderHourDetail(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 orderDetail: orderInfo = {
                    orderType: data.get('orderType') as Number,
                    id: data.get('id') as Number,
                    teamLeaderName: data.get('teamLeaderName') as string | null,
                    acceptUserName: data.get('acceptUserName') as string | null,
                    acceptTime: data.get('acceptTime') as string | null,
                    assignTime: data.get('assignTime') as string | null,
                    assignUserName: data.get('assignUserName') as string | null,
                    status: (data.get('status') == null) ? (0 as Number) : (data.get('status') as Number),
                    workOrderProjectNo: data.get('workOrderProjectNo') as string | null,
                    workOrderStatus: data.get('workOrderStatus') as string | null,
                    gxtCenterId: (data.get('gxtCenterId') ?? 0) as Number,
                    gxtCenter: data.get('gxtCenter') as string | null,
                    pcsStationId: (data.get('pcsStationId') ?? 0) as Number,
                    pcsStationName: data.get('pcsStationName') as string | null,
                    pcsDeviceId: (data.get('pcsDeviceId') ?? 0) as Number,
                    pcsDeviceName: data.get('pcsDeviceName') as string | null,
                    brand: data.get('brand') as string | null,
                    model: data.get('model') as string | null,
                    createTime: data.get('createTime') as string | null,
                    workOrderFlowList: null,
                    // 工时相关字段
                    issueHour: (data.get('issueHour') as number | null) ?? 0,
                    acceptHour: (data.get('acceptHour') as number | null) ?? 0,
                    prepareHour: (data.get('prepareHour') as number | null) ?? 0,
                    workHour: (data.get('workHour') as number | null) ?? 0,
                    restartHour: (data.get('restartHour') as number | null) ?? 0,
                    handleHour: (data.get('handleHour') as number | null) ?? 0,
                    suspendHour: (data.get('suspendHour') as number | null) ?? 0,
					downtimeHour: (data.get('downtimeHour') as number | null) ?? 0,
                } as orderInfo

                detailData.value = orderDetail

                // 准备图表数据
                prepareChartData(orderDetail)
            } 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
        }
    }

    // 返回上一页
    const goBack = (): void => {
        uni.navigateBack()
    }

    // 页面加载
    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) {
            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;
                }

                &.full-width {
                    flex-direction: column;

                    .info-label {
                        margin-bottom: 12rpx;
                    }

                    .info-value {
                        line-height: 44rpx;
                    }
                }

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

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

                    &.highlight {
                        color: #007aff;
                        font-weight: bold;
                    }
                }
            }

            .chart-container {
                flex-direction: row;
                align-items: center;
                justify-content: space-between;
                margin: 5rpx 0;
                padding: 5rpx 0;
            }

            .chart-legend {
                flex: 1;
                padding-left: 30rpx;
            }

            .legend-item {
                flex-direction: row;
                align-items: center;
                justify-content: space-between;
                margin-bottom: 8rpx;

                &:last-child {
                    margin-bottom: 0;
                }

                .legend-left {
                    flex-direction: row;
                    align-items: center;
                }

                .legend-right {
                    flex-direction: row;
                    align-items: center;
                }
            }

            .legend-color {
                width: 20rpx;
                height: 20rpx;
                border-radius: 4rpx;
                margin-right: 12rpx;
            }

            .legend-name {
                font-size: 24rpx;
                color: #333333;
                margin-right: 8rpx;
            }

            .legend-value {
                font-size: 24rpx;
                color: #666666;
                font-weight: bold;
            }

            .no-data {
                text-align: center;
                padding: 40rpx 0;
                font-size: 28rpx;
                color: #999999;
            }
            
            .combined-legend {
                flex-direction: row;
                align-items: center;
                margin-top: 20rpx;
                padding-top: 20rpx;
                border-top: 1rpx dashed #eee;
                
                .legend-left {
                    flex-direction: row;
                    align-items: center;
                }
            }
        }
    }

    .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>