<template>
	<uni-navbar-lite :showLeft=false title="首页"></uni-navbar-lite>
    <view class="page-container">
        <!-- 背景图 -->
        <!-- <image class="bg-image" src="/static/images/index/1.png" mode="widthFix"></image> -->

        <!-- <view class="bg-color"></view> -->
        <scroll-view class="page-content">

			<view class="db-view">
				<view class="db-box" @click="navigateToAssignedOrders">
					<view v-if="assignedCount > 0" class="badge"><text class="count">{{ assignedCount }}</text></view>
					<view class="db-block">
						<view class="db-center-1">
							<image class="db-image" src="/static/images/map/1.png"></image>
						</view>
					</view>
					<text class="db-text">待处理工单</text>
				</view>
				<view class="db-box" @click="navigateToScoreOrders">
					<view v-if="selfScoreCount > 0" class="badge"><text class="count">{{ selfScoreCount }}</text></view>
					<view class="db-block">
						<view class="db-center-2">
							<image class="db-image" src="/static/images/map/2.png"></image>
						</view>
					</view>
					<text class="db-text">待评分工单</text>
				</view>
				<view class="db-box" @click="navigateToOverdueOrders">
					<view v-if="overdueCount > 0" class="badge"><text class="count">{{ overdueCount }}</text></view>
					<view class="db-block">
						<view class="db-center-3">
							<image class="db-image" src="/static/images/map/2.png"></image>
						</view>
					</view>
					<text class="db-text">超时工单</text>
				</view>
			</view>

            <!-- 支流出库流量图表 -->
           <!-- <view class="chart-section">
                <text class="section-title">支流出库流量 (m³/s)</text>
                <flow-chart />
            </view> -->

			<!-- <view>
				<button @click="handlePush">通知</button>
			</view> -->

			<!-- 即将超时工单列表 -->
			<!-- <view class="section-title-container" v-if="almostOverdueListData.length > 0">
				<view class="section-header">
					<text class="section-title">即将超时工单</text>
					<text class="view-all" @click="navigateToAlmostOverdueOrders">查看全部</text>
				</view>
			</view>
			<common-list
				v-if="almostOverdueListData.length > 0"
				:dataList="almostOverdueListData.slice(0, 2)"
				:loading="almostOverdueLoading"
				:hasMore="false"
				:refresherEnabled="false"
				:itemKey="'id'"
				@itemClick="handleAlmostOverdueItemClick"
			>
				<template #default="{ item }">
					<view class="list-item">
						<view class="item-container">
							<view class="item-header">
								<text class="item-title">{{ getPcsDeviceName(item) }}-{{ getStationName(item) }}</text>
							</view>
							<view class="info-row">
								<text class="text-gray">工单编码：{{ getWorkOrderProjectNo(item) }}</text>
								<text class="text-gray" :class="getRemarkClass(item)">{{ getRemark(item) }}</text>
							</view>
						</view>
					</view>
				</template>
				<template #loadMore>
					<view></view>
				</template>
			</common-list> -->

			<!-- 超时工单列表 -->
			<view class="section-title-container" v-if="overdueListData.length > 0">
				<view class="section-header">
					<text class="section-title">超时工单</text>
					<text class="view-all" @click="navigateToOverdueOrders">查看全部</text>
				</view>
			</view>
			<common-list
				v-if="overdueListData.length > 0"
				:dataList="overdueListData.slice(0, 2)"
				:loading="overdueLoading"
				:hasMore="false"
				:refresherEnabled="false"
				:itemKey="'id'"
				@itemClick="handleOverdueItemClick"
			>
				<template #default="{ item }">
					<view class="list-item">
						<view class="item-container">
							<view class="item-header">
								<text class="item-title">{{ getPcsDeviceName(item) }}-{{ getStationName(item) }}</text>
								<!-- <text class="status-tag status-suspended">{{ getWorkOrderStatus(item) }}</text> -->
							</view>
							<view class="info-row">
								<text class="text-gray">工单编码：{{ getWorkOrderProjectNo(item) }}</text>
								<!-- <text class="text-gray overdue-title">{{ getRemark(item) }}</text> -->
							</view>
							<view class="info-row">
								<text class="overdue-title">{{ getRemark(item) }}</text>
							</view>
						</view>
					</view>
				</template>
				<template #loadMore>
					<view></view>
				</template>
			</common-list>
        </scroll-view>

        <!-- 底部 TabBar -->
        <custom-tabbar :current="0" />
    </view>
</template>

<script setup lang="uts">
    import { ref, onMounted } from 'vue'
    import { getUserInfo } from '../../utils/storage'
    import FlowChart from '../../components/index/flow-chart/flow-chart.uvue'
    import { getOrderList, almostOverdueList, overdueList } from '../../api/order/list'
    import { listMobileOrderScores } from '../../api/score/index'
	import type { SysDictData } from '../../types/dict'
	import { getDictDataByType } from '../../api/dict/index'
	// import {startKeepAlive,stopKeepAlive} from '@/uni_modules/ygtx-keepService'
	// import { RequestOption } from '@/uni_modules/ygtx-keepService/utssdk/interface.uts';
	import { getBaseUrl } from '../../utils/request'
	import { KeepLive } from '@/uni_modules/android-keeplive'
	import { getMyNotify } from '../../api/index/index'

	// const handleStartKeepAlive = (userId: string) => {
	// 	let notifyUrl = getBaseUrl() + "/mobile/notify";
	// 	console.log("通知地址：" + notifyUrl)
	// 	const requestOption:RequestOption = {
	// 		requestUrl: notifyUrl, // 你的接口地址（必填）
	// 		requestData: JSON.stringify({ method: "get", data: userId }), // 请求数据（字符串格式，必填）
	// 		task_interval: 10000 // 任务间隔（毫秒，必填）
	// 	  };
	// 	startKeepAlive(requestOption,
	// 	(res:any)=>{
	// 		console.log(res)
	// 	});
	// };

    // 用户名
    const userName = ref<string>('用户')

	// 待接单数量
	const assignedCount = ref<number>(0)

	// 待自评工单数量
	const selfScoreCount = ref<number>(0)

	// 超时工单数量
	const overdueCount = ref<number>(0)

	// 即将超时工单列表
	const almostOverdueListData = ref<any[]>([])
	const almostOverdueLoading = ref<boolean>(false)

	// 超时工单列表
	const overdueListData = ref<any[]>([])
	const overdueLoading = ref<boolean>(false)

	// 维保类型字典列表
	const inspectionTypeList = ref<SysDictData[]>([])
	// 添加字典加载状态
	const dictLoaded = ref<boolean>(false)

	// 获取工单状态字典列表
	const loadStatusDictList = 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.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)
	                }
	            }

	            inspectionTypeList.value = dictData
	            dictLoaded.value = true
	        }
	    } catch (e: any) {
	        console.error('获取工单状态字典失败:', e.message)
	        dictLoaded.value = true
	    }
	}

	// 获取待接单数量
	const loadAssignedCount = async (): Promise<void> => {
	    try {
	        const result = await getOrderList(1, 1, null, 'assigned,to_finish,to_approve,suspended')
	        const resultObj = result as UTSJSONObject

	        if (resultObj['code'] == 200) {
	            const total = resultObj['total'] as number
	            assignedCount.value = total
	        }
	    } catch (e: any) {
	        console.error('获取待接单数量失败:', e.message)
	    }
	}

	// 获取待自评工单数量
	const loadSelfScoreCount = async (): Promise<void> => {
	    try {
	        const params: UTSJSONObject = {
	            pageNum: 1,
	            pageSize: 1,
	            scoringStatus: 'to_self,to_re,to_confirm,to_final'
	        }

	        const result = await listMobileOrderScores(params)
	        const resultObj = result as UTSJSONObject

	        if (resultObj['code'] == 200) {
	            const total = resultObj['total'] as number
	            selfScoreCount.value = total
	        }
	    } catch (e: any) {
	        console.error('获取待自评工单数量失败:', e.message)
	    }
	}

	// 获取超时工单数量
	const loadOverdueCount = async (): Promise<void> => {
	    try {
	        const result = await overdueList(1, 1, '') // 只需要获取总数，不需要具体数据
	        const resultObj = result as UTSJSONObject

	        if (resultObj['code'] == 200) {
	            const total = resultObj['total'] as number
	            overdueCount.value = total
	        }
	    } catch (e: any) {
	        console.error('获取超时工单数量失败:', e.message)
	    }
	}

	// 获取即将超时工单列表
	const loadAlmostOverdueList = async (): Promise<void> => {
		try {
			almostOverdueLoading.value = true
			const result = await almostOverdueList(1, 2, '') // 获取前2条
			const resultObj = result as UTSJSONObject

			if (resultObj['code'] == 200) {
				const rows = resultObj['rows'] as any[]
				almostOverdueListData.value = rows
			}
		} catch (e: any) {
			console.error('获取即将超时工单列表失败:', e.message)
		} finally {
			almostOverdueLoading.value = false
		}
	}

	// 获取超时工单列表
	const loadOverdueList = async (): Promise<void> => {
		try {
			overdueLoading.value = true
			// const result = await getOrderList(1, 2, '','assigned,to_finish,to_approve,suspended')
			const result = await overdueList(1, 2, '') // 获取前2条
			const resultObj = result as UTSJSONObject

			if (resultObj['code'] == 200) {
				const data = resultObj['rows'] as any[]
				overdueListData.value = data
			}
		} catch (e: any) {
			console.error('获取超时工单列表失败:', e.message)
		} finally {
			overdueLoading.value = false
		}
	}

	// 跳转到待接单列表
	const navigateToAssignedOrders = (): void => {
		// 使用 redirectTo 而不是 switchTab，因为工单页面不是 tabBar 页面
		uni.redirectTo({
		    url: '/pages/order/index'
		})

		// 延迟设置状态，确保页面已加载
		// setTimeout(() => {
		// 	uni.$emit('switchOrderStatus', 'assigned')
		// }, 500)
	}

	// 跳转到评分工单列表
	const navigateToScoreOrders = (): void => {
		uni.redirectTo({
		    url: '/pages/score/index'
		})

		// 延迟设置状态，确保页面已加载
		// setTimeout(() => {
		// 	uni.$emit('switchScoreStatus', 'to_self')
		// }, 500)
	}

	// 跳转到超时工单列表
	const navigateToOverdueOrders = (): void => {
		// 跳转到超时工单页面
		uni.navigateTo({
		    url: '/pages/order/overdue'
		})
	}

	// 跳转到即将超时工单列表
	const navigateToAlmostOverdueOrders = (): void => {
		// 跳转到即将超时工单页面
		uni.navigateTo({
		    url: '/pages/order/almostOverdue'
		})
	}

	const getNofiyMes = (): void=>{
		const userInfo = getUserInfo()
		if (userInfo != null) {
		    const userId = userInfo['userId']?.toString()
			if(userId!=null){
				getMyNotify(userId).then((result:any) => {
					const jsonData = JSON.stringify(result)
					const respData = JSON.parse(jsonData) as UTSJSONObject
					if (respData['code'] == 200 &&
						respData.hasOwnProperty('data') && respData['data'] != null) {
						const data = respData['data'] as UTSJSONObject
						const badge = data["num"] as number
						console.log("======" + badge)
						setTimeout(() => {
							uni.setAppBadgeNumber(badge);
							if(data.hasOwnProperty("title") && data["title"] != null
								&& data.hasOwnProperty("desc") && data["desc"] != null){
								const title = data["title"] as string
								const desc = data["desc"] as string
								uni.createPushMessage({
									title: title,
									content: desc,
									when: Date.now() + 10000,
									icon: "/static/login/2.png",
									sound: "system",
									success: (res) => {
										console.log('创建推送消息成功', res);
									},
									fail: (err) => {
										console.error('创建推送消息失败', err);
									}
								});
							}
						}, 0);
					}
				}).catch((error) => {
					console.error('Promise 执行失败:', error)
				});
			}
		}
	}
	
	const handleKeepAlive = ()=>{
		var keep=new KeepLive()
		keep.setTitle("工效通")
		keep.setContent("工效通正在运行")
		// keep.setLargeIcon("icon");
		keep.setSmallIcon("icon"); //图标名字  图标放在 插件下面的 uni_modules\android-keeplive\utssdk\app-android\res 文件夹下
		keep.onAddBackgroundCallback(function(res:boolean){
		    console.log("后台运行 "+res)
		})
		keep.onAddScrrenListenerCallback(function(res:boolean){
		    console.log("屏幕开启状态 "+res)
		})
		keep.setWakeLock(1,"keeptag");// 设置唤醒类型
		keep.setAutoStartEnable(true)
		keep.doStartApplicationWithPackageName("uni.app.UNI1050C07");
	
		if(!keep.checkAppNotification()){
		    keep.onOpenNotificationSetting(function(res:boolean){
		        keep.register();
		        var ignoring=  keep.isIgnoringBatteryOptimizations();
		        if(!ignoring){
		            keep.requestIgnoreBatteryOptimizations();
		        }
		    })
		}else{
		    keep.register();
		    var ignoring=  keep.isIgnoringBatteryOptimizations();
		    if(!ignoring){
		        keep.requestIgnoreBatteryOptimizations();
		    }
		}
	
		// keep.wifilock();
		// 稳定定时器 需要的用户使用（默认定时器1 ）
		keep.onStartCSystemTimer(10,function(){
		    console.log("onStartCSystemTimer ");
			getNofiyMes();
		    keep.acquire(1000);// 唤醒一秒钟
		});
	}
	
	// 辅助函数：从 any 类型提取属性
	const getWorkOrderProjectNo = (item: any | null): string | null => {
		if (item == null) return ''
		const orderInfoItem = item as UTSJSONObject
		return orderInfoItem['workOrderProjectNo'] as string != null ? orderInfoItem['workOrderProjectNo'] as string : ''
	}

	const getPcsDeviceName = (item: any | null): string | null=> {
		if (item == null) return ''
		const orderInfoItem = item as UTSJSONObject
		return orderInfoItem['pcsDeviceName'] as string != null ? orderInfoItem['pcsDeviceName'] as string : ''
	}

	const getStationName = (item: any | null): string | null=> {
		if (item == null) return ''
		const orderInfoItem = item as UTSJSONObject
		return orderInfoItem['pcsStationName'] as string != null ? orderInfoItem['pcsStationName'] as string : ''
	}

	const getCreateTime = (item: any | null): string|null => {
		if (item == null) return null
		const orderInfoItem = item as UTSJSONObject
		return orderInfoItem['createTime'] as string != null ? orderInfoItem['createTime'] as string : ''
	}
	const getRemark = (item: any | null): string|null => {
		if (item == null) return null
		const orderInfoItem = item as UTSJSONObject
		return orderInfoItem['remark'] as string != null ? orderInfoItem['remark'] as string : ''
	}

	// 根据剩余时间获取颜色类名
	const getRemarkClass = (item: any | null): string => {
		if (item == null) return ''
		const orderInfoItem = item as UTSJSONObject
		const remark = orderInfoItem['remark'] as string

		if (remark == null || remark.length === 0) return ''

		// 解析备注中的剩余时间（假设格式为包含数字和小时的字符串）
		// 例如："剩余时间：5小时" 或 "还剩10小时"
		const timeMatch = remark.match(/(\d+(\.\d+)?)\s*(小时|时)/)

		if (timeMatch != null && timeMatch.length > 1 && timeMatch[1] != null) {
			const hours = parseFloat(timeMatch[1] as string)

			if (hours < 6) {
				return 'time-critical' // 红色
			} else if (hours < 12) {
				return 'time-warning' // 橙色
			} else if (hours < 24) {
				return 'time-notice' // 黄色
			}
		}

		return ''
	}

	// 辅助函数：从 any 类型提取属性
	const getOrderType = (item: any | null): string => {
	    if (item == null) return ''
	    const orderInfoItem = item as UTSJSONObject
	    return orderInfoItem['orderType'] == 1?"维修工单":"维保工单";
	}

	const getInspectionType = (item: any | null): string | null => {
	    if (item == null) return ''
	    const orderInfoItem = item as UTSJSONObject
	    const rawStatus = orderInfoItem['inspectionType']

	    if (rawStatus==null) return ''
		// 如果字典尚未加载，返回原始值
		    if (!dictLoaded.value) {
		        return rawStatus
		    }
	    // 查找字典中对应的标签
	    const dictItem = inspectionTypeList.value.find(dict => dict.dictValue == rawStatus)
	    return dictItem!=null ? dictItem.dictLabel : rawStatus
	}

	// 即将超时工单点击事件
	const handleAlmostOverdueItemClick = (item: any, index: number): void => {
		if (item == null) return
		const orderItem = item as UTSJSONObject
		try {
			// 跳转到工单详情页
			uni.navigateTo({
			    url: `/pages/order/detail/index?id=${orderItem['id']}&orderType=${orderItem['orderType']}`
			})
		} catch (e) {
			console.error('处理即将超时工单点击事件失败:', e)
		}
	}

	// 超时工单点击事件
	const handleOverdueItemClick = (item: any, index: number): void => {
		if (item == null) return
		const orderItem = item as UTSJSONObject
		try {
			// 跳转到工单详情页
			uni.navigateTo({
				url: `/pages/order/detail/acceptIndex?id=${orderItem.id}&orderType=${orderItem.orderType}`
			})
		} catch (e) {
			console.error('处理超时工单点击事件失败:', e)
		}
	}

    // 初始化
    onMounted(() => {
        const userInfo = getUserInfo()
        if (userInfo != null) {
            const realName = userInfo['nickName'] as string | null
            userName.value = realName ?? '用户'
			const userId = userInfo['userId']?.toString()
			if(userId!=null){
				console.log("监听："+userId)
				handleKeepAlive()
			}
        }

		// 加载待接单数量
		loadAssignedCount()

		// 加载待自评工单数量
		loadSelfScoreCount()

		// 加载超时工单数量
		loadOverdueCount()

		// 加载即将超时工单列表
		// loadAlmostOverdueList()

		// 加载超时工单列表
		loadOverdueList()

		// 监听工单状态更新事件
		uni.$on('refreshAssignedCount', () => {
			loadAssignedCount()
		})

		// 监听评分工单状态更新事件
		uni.$on('refreshSelfScoreCount', () => {
			loadSelfScoreCount()
		})

		// 监听超时工单状态更新事件
		uni.$on('refreshOverdueCount', () => {
			loadOverdueCount()
		})
		// 监听接单成功的事件，刷新列表
		uni.$on('refreshOrderList', () => {
			loadOverdueList()
		})
    })
</script>

<style lang="scss">
    .page-container {
        position: relative;
        flex: 1;
        padding-top: env(safe-area-inset-top);
		background-color: #e8f0f9;
    }

    .bg-image {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 0;
    }

    .bg-color {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: -1;
        background: #71a6e4;
    }

    .page-content {
        position: relative;
        flex: 1;
        margin-bottom: 150rpx;
        padding: 20rpx;
        z-index: 10;
    }

    .header {
		flex-direction: row;
		height: 40px;

        &-title {
            font-size: 40rpx;
            color: #ffffff;
            font-weight: bold;
            margin-bottom: 15rpx;
        }

        &-greeting {
            font-size: 28rpx;
            color: rgba(255, 255, 255, 0.9);
        }
    }

    .section-title {
        font-size: 32rpx;
        color: #333333;
        font-weight: bold;
        // margin-bottom: 20rpx;
    }

	.section-title-container {
		padding: 20rpx 30rpx 10rpx 30rpx;
	}

	.section-header {
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}

	.view-all {
		font-size: 28rpx;
		color: #165dff;
	}

    /* 图表区域 */
    .chart-section {
        padding: 30rpx;
        margin-bottom: 20rpx;
        background: linear-gradient(180deg, rgba(255, 255, 255, 0.7) 0%, rgba(255, 255, 255, 0.9) 100%);
        box-shadow: 0 0 16rpx 0 rgba(0, 0, 0, 0.1);
        border-radius: 16rpx;
    }

	.db-view{
		flex-direction: row;
		justify-content: space-between;
		margin-bottom: 10rpx;

		.db-box{
			background-color: #fff;
			width:200rpx;
			height: 200rpx;
			justify-content: center;
			align-items: center;
			margin-left: 3px;
			border-radius: 5px;
			.db-text{
				margin-top: 10rpx;
				font-size:10px;
			}
			.db-center-1{
				justify-content: center;
				align-items: center;
				background-color: #DBEAFE;
				border-radius: 200px;
				width:100rpx;
				height:100rpx;
				position: relative;
			}
			.db-center-2{
				justify-content: center;
				align-items: center;
				background-color: #DCFCE7;
				border-radius: 200px;
				width:100rpx;
				height:100rpx;
				position: relative;
			}
			.db-center-3{
				justify-content: center;
				align-items: center;
				background-color: #F3E8FF;
				border-radius: 200px;
				width:100rpx;
				height:100rpx;
			}
		}
		.db-image{
			width:20px;
			height:20px;
		}
	}

	.badge {
		z-index: 999;
		position: absolute;
		top: 35rpx;
		right: 35rpx;
		background-color: #ff4d4f;
		border-radius: 20rpx;
		width: 40rpx;
		height: 40rpx;

	}
	.count {
		line-height: 40rpx;
		font-size: 26rpx;
		text-align: center;
		color: #ffffff;
	}

	.list-item {
		margin: 0 30rpx 24rpx 30rpx;
		background-color: #ffffff;
		border-radius: 16rpx;
	}

	.item-container {
		padding: 30rpx;
	}

	.item-header {
		flex-direction: row;
		align-items: center;
		margin-bottom: 16rpx;

		.item-title {
			flex: 1;
			font-size: 32rpx;
			color: #333333;
			font-weight: bold;
		}

		.detail-link {
			font-size: 28rpx;
			color: #999999;
		}
	}

	.btn-primary {
		font-size: 14px;
		background-color: #165DFF;
		color: #ffffff;
	}

	.info-row {
		flex-direction: row;
		justify-content: space-between;
		align-items: center;

		.info-label {
			font-size: 26rpx;
			color: #666;
		}

		.info-value {
			font-size: 26rpx;
		}
	}

	.text-gray{
		font-size: 26rpx;
		color: #666;
	}

	/* 剩余时间颜色样式 */
	.time-critical {
		color: #ff4d4f; /* 红色 */
	}

	.time-warning {
		color: #fa8c16; /* 橙色 */
	}

	.time-notice {
		color: #faad14; /* 黄色 */
	}

	.status-tag {
		padding: 8rpx 20rpx;
		border-radius: 20rpx;
		font-size: 24rpx;
		white-space: nowrap;
		margin-left: 20rpx;
		border: 1rpx solid;
	}

	/* 已超时工单标题红色样式 */
	.overdue-title {
		margin-top: 16rpx;
		font-size: 26rpx;
		color: #ff4d4f;
	}

	/* 待接单 */
	.status-assigned {
		background-color: #ebf5ff;
		color: #409eff;
		border-color: #d8ebff;
	}

	/* 已挂起 */
	.status-suspended {
		background-color: #fff2f0;
		color: #ff4d4f;
		border-color: #ffccc7;
	}
</style>
