<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">
                        <tui-xechars ref="chartRef" style="width: 315rpx; height: 300rpx;" @initFinished="onInitFinished"></tui-xechars>
                        <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) }}小时</text>
                                </view>
                            </view>
                        </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'
    import { TuiCharts } from '@/uni_modules/tui-xechars'

    // 详情数据
    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
    } as orderInfo)

    const loading = ref<boolean>(false)
    const chartData = ref<UTSJSONObject[]>([])
    const chartRef = ref<TuiCharts | null>(null)
    // 保存图表实例
    const chartInstance = ref<TuiCharts | null>(null)

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

    // 颜色配置
    const chartColors = ['#5B9BF3', '#4DD4C0', '#FF9966', '#FF6B96', '#9B7FE8', '#FFD700', '#8A2BE2']

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

    // 绘制图表
    const drawChart = (charts: TuiCharts): void => {
        console.log('准备绘制图表，数据:', chartData.value)
        try {
            // 检查数据是否有效
            if (chartData.value == null || chartData.value.length == 0) {
                console.log('图表数据为空，无法绘制')
                return
            }

            console.log('图表实例状态:', charts)

            // 清除之前的图表
            if (charts.chartsMap != null) {
                charts.chartsMap.clear()
            }

            // 创建饼图配置 - 使用环形图配置以匹配 flow-chart 组件
            const pieOption = {
                type: 'ring',
                dataLabel: false,
                legend: {
                    show: false
                },
                series: chartData.value.map((item: UTSJSONObject, index: number) => {
                    return {
                        name: item.get('name'),
                        legendText: item.get('name'),
                        data: [{
                            name: item.get('name'),
                            value: item.get('value')
                        }],
                        color: chartColors[index % chartColors.length]
                    }
                }),
                extra: {
                    ring: {
                        type: 'ring',
                        width: 8,
                        activeOpacity: 0.5,
                        activeRadius: 0,
                        offsetAngle: 0,
                        labelWidth: 15,
                        ringWidth: 8,
                        customRadius: 60,
                        border: false,
                        borderWidth: 0,
                        borderColor: '#FFFFFF',
                        centerColor: '#FFFFFF',
                        linearType: 'custom',
                        // 添加背景色以匹配 flow-chart 组件
                        backgroundColor: '#C4D7E9'
                    }
                }
            } as UTSJSONObject

            console.log('图表配置:', pieOption)

            console.log('准备创建图表对象')
            const pieChart = charts.add(0, pieOption)
            console.log('创建图表对象完成:', pieChart)
            console.log('准备绘制图表')
            pieChart.draw()
            console.log('图表绘制完成')
        } catch (error) {
            console.error('图表绘制出错:', error)
        }
    }

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

        // 添加各项工时数据
        if (data.issueHour != null) {
            const item = {
				name: '下发时长',
				value: data.issueHour
			} as UTSJSONObject
            chartItems.push(item)
            legendItems.push({
                name: '下发时长',
                value: data.issueHour,
                color: chartColors[legendItems.length % chartColors.length]
            } as ChartLegendItem)
        }

        if (data.acceptHour != null) {
            const item = {name: '接单时长', value: data.acceptHour} as UTSJSONObject
            chartItems.push(item)
            legendItems.push({
                name: '接单时长',
                value: data.acceptHour,
                color: chartColors[legendItems.length % chartColors.length]
            } as ChartLegendItem)
        }

        if (data.prepareHour != null) {
            const item = {name: '准备时长', value: data.prepareHour} as UTSJSONObject
            chartItems.push(item)
            legendItems.push({
                name: '准备时长',
                value: data.prepareHour,
                color: chartColors[legendItems.length % chartColors.length]
            } as ChartLegendItem)
        }

        if (data.workHour != null) {
            const item = {name: '作业时长', value: data.workHour} as UTSJSONObject
            chartItems.push(item)
            legendItems.push({
                name: '作业时长',
                value: data.workHour,
                color: chartColors[legendItems.length % chartColors.length]
            } as ChartLegendItem)
        }

        if (data.restartHour != null) {
            const item = {name: '复运时长', value: data.restartHour} as UTSJSONObject
            chartItems.push(item)
            legendItems.push({
                name: '复运时长',
                value: data.restartHour,
                color: chartColors[legendItems.length % chartColors.length]
            } 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.suspendHour != null) {
            const item = {name: '挂起时长', value: data.suspendHour} as UTSJSONObject
            chartItems.push(item)
            legendItems.push({
                name: '挂起时长',
                value: data.suspendHour,
                color: chartColors[legendItems.length % chartColors.length]
            } as ChartLegendItem)
        }

        chartData.value = chartItems
        chartLegendData.value = legendItems
        console.log('更新chartData:', chartItems)
        console.log('更新chartLegendData:', legendItems)

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

    // 加载详情数据
    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
                } 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 onInitFinished = (charts: TuiCharts): void => {
        console.log('图表初始化完成')
        chartInstance.value = charts
        console.log('当前chartData:', chartData.value)
        // 如果数据已经加载完成，则立即绘制图表
        if (chartData.value != null && chartData.value.length > 0) {
            drawChart(charts)
        } else {
            console.log('等待数据加载完成')
        }
    }

    // 返回上一页
    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: 20rpx 0;
            }

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

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

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

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

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

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

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

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

            .no-data {
                text-align: center;
                padding: 40rpx 0;
                font-size: 28rpx;
                color: #999999;
            }
        }
    }

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