<template>
	<uni-navbar-lite :showLeft=false :show-right=false title="首页"></uni-navbar-lite>
    <view class="page-container">
<!-- 		<view>
			<text class="page-header"> 首页 </text>
		</view> -->
        <!-- 快捷功能卡片 -->
        <view class="quick-cards">
            <view v-for="(item, index) in quickFunctions" :key="index" class="quick-card" @click="handleQuickClick(item)">
                <image class="quick-card-bg" :src="item.bgImage" mode="aspectFill"></image>
                <view class="quick-card-content">
                    <text class="quick-card-title">{{ item.title }}</text>
                </view>
				<view class="management-badge" v-if="item.badge > 0">
				    <text class="badge-text">{{item.badge}}</text>
				</view>
            </view>
        </view>
		<view class="receive-list-container">
			<!-- 待签收 -->
			<view class="section-title-container">
				<view class="section-header">
					<text class="section-title">待签收</text>
					<text class="view-all" @click="navigateToOut" v-if="receiveListData.length > 0">查看全部</text>
				</view>
			</view>
			<scroll-view class="receive-list" scroll-y="true">
				<template v-if="receiveListData.length > 0">
					<view 
						v-for="(item, index) in receiveListData" 
						:key="index" 
						class="list-item"
					>
						<view class="item-container">
							<view class="item-header">
								<text class="item-title">{{ getItemName(item) }}</text>
								<text class="item-type">{{ getItemTypeName(item) }}</text>
							</view>
							<view class="item-info">
								<view class="info-row">
									<view class="info-item">
										<text class="info-label">数量</text>
										<text class="info-value">{{ getQuantity(item) }} {{ getMeasureName(item) }}</text>
									</view>
									<view class="info-item">
										<text class="info-label">状态</text>
										<text class="info-value status-pending">待签收</text>
									</view>
								</view>
							</view>
							<view class="item-footer">
								<button class="receive-btn" @click="handleSignReceive(item)">签收</button>
							</view>
						</view>
					</view>
				</template>
				<template v-else>
				  <view class="empty-tips">
				    <text class="empty-text">暂无待签收物料</text>
				  </view>
				</template>
			</scroll-view>
		</view>
         
        <!-- 底部 TabBar -->
        <custom-tabbar :current="0" />
    </view>
</template>

<script setup lang="uts">
    import { ref, onMounted, onUnmounted } from 'vue'
    import { getUserInfo } from '../../utils/storage'
    import { getPendingReceiveLines, signReceiveLine, getProductSalseList } from '../../api/out/index'
    import { getPendingReceiveApplyCount } from '../../api/apply/index'
    type QuickFunction = {
        id: number
        title: string
        bgImage: string
        icon: string
        path: string
		badge:number
    }
	const receiveListData = ref<UTSJSONObject[]>([])
	const receiveLoading = ref<boolean>(false)
	let currentUserId: string = ''
	let currentUserName: string = ''
	let refreshTimer: number | null = null
	let timerLock = false
	
	// 快捷功能列表
    const quickFunctions = ref<QuickFunction[]>([
        {
            id: 1,
            title: '物料申请',
            bgImage: '/static/images/workbench/3.png',
            icon: '',
            path: '/pages/apply/index',
			badge: 0
        },
        {
            id: 2,
            title: '出库单',
            bgImage: '/static/images/workbench/2.png',
            icon: '',
            path: '/pages/out/index',
			badge: 0
        },
        {
            id: 3,
            title: '系统物料',
            bgImage: '/static/images/workbench/4.png',
            icon: '',
            path: '/pages/item/index',
			badge: 0
        }
    ])
	
	// 快捷功能点击
	const handleQuickClick = (item: QuickFunction): void => {
	    if (item.path.length > 0) {
	        uni.navigateTo({
	            url: item.path,
	            fail: (err: any) => {
	                console.log('导航失败', err)
	            }
	        })
	    } else {
	        uni.showToast({
	            title: item.title,
	            icon: 'none'
	        })
	    }
	}
	// 跳转到申请单列表
	const navigateToApply = (): void => {
		// 跳转到申请单列表
		uni.navigateTo({
		    url: '/pages/apply/index'
		})
	}
	// 加载待签收列表
const loadReceiveList = (): void => {
	if (currentUserId.length === 0) return
	receiveLoading.value = true
	// 查询待签收物料，最多显示10条
	getPendingReceiveLines(1, 10, currentUserId).then((res: any) => {
		const result = res as UTSJSONObject
		const rows = result['rows']
		if (rows != null) {
			const data = rows as UTSJSONObject[]
			receiveListData.value = data
		} else {
			receiveListData.value = []
		}
		receiveLoading.value = false
	}).catch((e) => {
		console.error('加载待签收列表失败:', e)
		receiveListData.value = []
		receiveLoading.value = false
	})
}

	// 获取物料名称
	const getItemName = (item: any): string => {
		if (item == null) return ''
		const jsonItem = item as UTSJSONObject
		const val = jsonItem['itemName']
		return val != null ? val.toString() : ''
	}

	// 获取物料分类
	const getItemTypeName = (item: any): string => {
		if (item == null) return ''
		const jsonItem = item as UTSJSONObject
		const val = jsonItem['itemTypeName']
		return val != null ? val.toString() : ''
	}

	// 获取数量
	const getQuantity = (item: any): string => {
		if (item == null) return '0'
		const jsonItem = item as UTSJSONObject
		const val = jsonItem['quantitySalse']
		return val != null ? val.toString() : '0'
	}

	// 获取单位
	const getMeasureName = (item: any): string => {
		if (item == null) return ''
		const jsonItem = item as UTSJSONObject
		const val = jsonItem['measureName']
		return val != null ? val.toString() : ''
	}

	// 处理签收
	const handleSignReceive = (item: any): void => {
		if (item == null) return
		const jsonItem = item as UTSJSONObject
		const lineId = jsonItem['lineId']
		if (lineId == null) {
			uni.showToast({ title: '明细ID不存在', icon: 'none' })
			return
		}
		uni.showModal({
			title: '提示',
			content: '确认签收该物料？',
			success: (res) => {
				if (res.confirm) {
					signReceiveLine(lineId.toString()).then(() => {
						uni.showToast({ title: '签收成功', icon: 'success' })
						// 重新加载待签收列表
						loadReceiveList()
					}).catch((e) => {
						const error = e as UTSError
						const errMsg = error?.message
						uni.showToast({ title: errMsg.toString(), icon: 'none' })
					})
				}
			}
		})
	}

	// 跳转到出库单列表
	const navigateToOut = (): void => {
		uni.navigateTo({
			url: '/pages/out/index'
		})
	}

    // 用户名
    const userName = ref<string>('用户')
    // 停止定时刷新
    const stopRefreshTimer = (): void => {
        if (timerLock && refreshTimer != null) {
            clearInterval(refreshTimer as number)
            refreshTimer = null
            timerLock = false
        }
    }

	// 加载出库单 badge 数量
	const loadOutstockBadge = (): void => {
		if (currentUserId.length === 0) return
		// 查询待签收的出库单
		getProductSalseList(1, 1000, '', currentUserId, 'PENDING').then((res: any) => {
			const result = res as UTSJSONObject
			const rows = result['rows']
			if (rows != null) {
				const data = rows as UTSJSONObject[]
				// 统计待签收数量大于0的出库单个数
				const pendingCount = data.filter((item: UTSJSONObject) => {
					const unsignedCount = item['unsignedCount']
					return unsignedCount != null && parseInt(unsignedCount.toString()) > 0
				}).length
				// 更新快捷功能中的出库单 badge
				quickFunctions.value.forEach((functionItem) => {
					if (functionItem.id === 2) {
						functionItem.badge = pendingCount
					}
				})
			}
		}).catch((e) => {
			console.error('加载出库单 badge 失败:', e)
		})
	}
	
	// 加载物料申请待领取 badge 数量
	const loadApplyBadge = (): void => {
		if (currentUserId.length === 0) return
		// 查询物料申请待领取数量
		getPendingReceiveApplyCount(currentUserId).then((res: any) => {
			const result = res as UTSJSONObject
			const count = result['data']
			// 更新快捷功能中的物料申请 badge
			quickFunctions.value.forEach((functionItem) => {
				if (functionItem.id === 1) {
					functionItem.badge = count != null ? parseInt(count.toString()) : 0
				}
			})
		}).catch((e) => {
			console.error('加载物料申请 badge 失败:', e)
		})
	}
	// 启动定时刷新
	const startRefreshTimer = (): void => {
	    stopRefreshTimer() // 先清除已有的定时器
	    timerLock = true
	    refreshTimer = setInterval(() => {
			console.log("当前登录：" + currentUserName)
			const userInfo = getUserInfo();
	        if (userInfo != null) {
				loadReceiveList()
				loadOutstockBadge()
				loadApplyBadge()
			}else{
				console.log("停止定时器")
				stopRefreshTimer()
			}
		}, 5000) // 5秒刷新一次
	}
    // 初始化
    onMounted(() => {
        const userInfo = getUserInfo()
        if (userInfo != null) {
            const realName = userInfo['nickName'] as string | null
            userName.value = realName ?? '用户'
            const userId = userInfo['userId']
            const userNameVal = userInfo['userName']
            currentUserId = userId != null ? userId.toString() : ''
            currentUserName = userNameVal != null ? userNameVal.toString() : ''
            // 加载待签收列表
            loadReceiveList()
            // 加载出库单 badge 数量
            loadOutstockBadge()
            // 加载物料申请 badge 数量
            loadApplyBadge()
            // 启动定时刷新，每5秒刷新一次
            startRefreshTimer()
        }
    })
    // 组件卸载时清除定时器
    onUnmounted(() => {
        stopRefreshTimer()
    })

</script>

<style lang="scss">
    .page-container {
        position: relative;
        flex: 1;
        padding-top: calc(env(safe-area-inset-top) + 20rpx);
        padding-bottom: 140rpx; /* 为底部标签栏留出更多空间 */
        padding-left: 20rpx;
        padding-right: 20rpx;
		background-color: #e8f0f9;
        display: flex;
        flex-direction: column;
        box-sizing: border-box;
    }

    .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;
    }
	.page-header{
		font-size: 32rpx;
		color: #333333;
		font-weight: bold;
		padding-top:20px;
		padding-bottom: 10px;
	}
	
	.quick-cards {
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;
    margin-bottom: 10rpx;
	padding-top: 40rpx;

    .quick-card {
        position: relative;
        width: 212rpx;
        height: 120rpx;
        margin-bottom: 20rpx;
        overflow: hidden;
        border-radius: 16rpx;

        &-bg {
            position: absolute;
            top: 0;
            left: 0;
            width: 226rpx;
            height: 140rpx;
            z-index: 0;
        }

        &-content {
            position: relative;
            z-index: 1;
            padding: 20rpx;
            height: 140rpx;
            justify-content: flex-start;
        }

        &-title {
            font-size: 28rpx;
            color: #333333;
            font-weight: bold;
        }
		.management-badge {
		    position: absolute;
		    top: 20rpx;
		    right: 20rpx;
		    width: 32rpx;
		    height: 32rpx;
		    background-color: #ff3b30;
		    border-radius: 16rpx;
		    justify-content: center;
		    align-items: center;

		    .badge-text {
		        font-size: 20rpx;
		        color: #ffffff;
		        line-height: 20rpx;
		    }
		}
    }
}

.receive-list-container {
    flex: 1;
    margin-bottom: 20rpx;
    display: flex;
    flex-direction: column;
}

.section-title-container {
    // margin-top: 20rpx;
    padding: 20rpx 30rpx;
    .section-header {
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        .section-title {
            font-size: 32rpx;
            color: #333333;
            font-weight: bold;
            // margin-bottom: 20rpx;
        }
        .view-all {
            font-size: 28rpx;
            color: #165dff;
        }
    }
}

.receive-list {
    flex: 1;
    margin: 0 30rpx;
    border-radius: 16rpx;
    background-color: #ffffff;
    padding: 10rpx;
    box-sizing: border-box;
    
    /* 隐藏滚动条但保留滚动功能 */
    &::-webkit-scrollbar {
        width: 0;
        height: 0;
    }
    
    /* 为了兼容性，添加一些额外样式 */
    scrollbar-width: none;
    -ms-overflow-style: none;
}

.list-item {
    margin-bottom: 16rpx;
    background-color: #ffffff;
    border-radius: 12rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
    .item-container {
        padding: 20rpx;
    }
    
    .item-header {
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 12rpx;

        .location-icon {
            width: 24rpx;
            height: 24rpx;
            margin-right: 6rpx;
        }

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

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

        .item-type {
            font-size: 22rpx;
            color: #007aff;
            background-color: #e6f7ff;
            padding: 6rpx 12rpx;
            border-radius: 6rpx;
            white-space: nowrap;
        }
    }
    
    .item-address {
        font-size: 24rpx;
        color: #999999;
        margin-bottom: 12rpx;
        line-height: 36rpx;
    }
    
    .item-info {
        padding: 16rpx;
        background-color: #f8f9fa;
        border-radius: 6rpx;

        .info-row {
            flex-direction: row;
            margin-bottom: 12rpx;

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

            .info-item {
                flex: 1;
                flex-direction: row;
                align-items: center;

                .info-label {
                    font-size: 28rpx;
                    color: #666666;
                    margin-right: 6rpx;
                    white-space: nowrap;
                }

                .info-value {
                    flex: 1;
                    font-size: 28rpx;
                    color: #333333;
                    
                    &.status-pending {
                        color: #faad14;
                    }
                }
            }
        }
    }

    .item-footer {
        margin-top: 12rpx;
        display: flex;
        justify-content: flex-end;
    }

    .receive-btn {
        padding: 0rpx 20rpx;
        background-color: #007aff;
        color: #ffffff;
        font-size: 28rpx;
        border-radius: 6rpx;
        border: none;
    }
}

.empty-tips {
    padding: 30rpx;
    justify-content: center;
    align-items: center;

    .empty-text {
        font-size: 26rpx;
        color: #999999;
    }
}
</style>
