<template>
	<uni-navbar-lite @rightClick="handleRight" title="申请单"></uni-navbar-lite>
    <view class="list-page">
        <!-- 搜索栏和状态标签 -->
        <view class="search-block">
            <view class="search-bar">
                <view class="search-box">
                    <image class="search-icon" src="/static/images/workbench/list/1.png" mode="aspectFit"></image>
                    <input class="search-input" type="text" placeholder="请输入申请单号查询" v-model="keyword" @confirm="handleSearch" />
                    <view v-if="keyword.length > 0" class="clear-btn" @tap="clearKeyword">
                    	<text class="clear-btn-text">×</text>
                    </view>
                    <view class="search-btn" @tap="handleSearch">
                    	<text class="search-btn-text">搜索</text>
                    </view>
                </view>
            </view>

            <!-- 状态标签 -->
            <view class="status-tabs">
                <view 
                    class="status-tab" 
                    :class="{ 'active': currentStatus === '' }" 
                    @tap="handleStatusChange('')"
                >
                    <text class="status-tab-text" :class="{ 'active-text': currentStatus === '' }">全部</text>
                </view>
                <view 
                    class="status-tab" 
                    :class="{ 'active': currentStatus === 'PREPARE' }" 
                    @tap="handleStatusChange('PREPARE')"
                >
                    <text class="status-tab-text" :class="{ 'active-text': currentStatus === 'PREPARE' }">待确认</text>
                </view>
                <view 
                    class="status-tab" 
                    :class="{ 'active': currentStatus === 'CONFIRMED' }" 
                    @tap="handleStatusChange('CONFIRMED')"
                >
                    <text class="status-tab-text" :class="{ 'active-text': currentStatus === 'CONFIRMED' }">已确认</text>
                </view>
                <view 
                    class="status-tab" 
                    :class="{ 'active': currentStatus === 'APPROVING' }" 
                    @tap="handleStatusChange('APPROVING')"
                >
                    <text class="status-tab-text" :class="{ 'active-text': currentStatus === 'APPROVING' }">审批中</text>
                </view>
                <view 
                    class="status-tab" 
                    :class="{ 'active': currentStatus === 'APPROVED' }" 
                    @tap="handleStatusChange('APPROVED')"
                >
                    <text class="status-tab-text" :class="{ 'active-text': currentStatus === 'APPROVED' }">已审批</text>
                </view>
            </view>
        </view>

        <!-- 列表内容 -->
        <common-list 
            :dataList="dataList" 
            :loading="loading" 
            :refreshing="refreshing" 
            :hasMore="hasMore" 
            @refresh="handleRefresh" 
            @loadMore="loadMore" 
            @itemClick="handleItemClick"
        >
            <template #default="{ item, index }">
                <view class="list-item">
                    <view class="item-container">
                        <view class="item-header">
                            <text class="item-title">{{ getApplyCode(item) }}</text>
                            <text class="item-status" :class="'status-' + getStatus(item)">{{ getStatusText(item) }}</text>
                        </view>
                        <view class="item-info">
                            <view class="info-row">
                                <view class="info-item">
                                    <text class="info-label">申请时间</text>
                                    <text class="info-value">{{ getCreateTime(item) }}</text>
                                </view>
                                <view class="info-item">
                                    <text class="info-label">申请人</text>
                                    <text class="info-value">{{ getNickName(item) }}</text>
                                </view>
                            </view>
                            <view class="info-row">
                                <view class="info-item">
                                    <text class="info-label">已完成</text>
                                    <text class="info-value success">{{ getFinishedCount(item) }}</text>
                                </view>
                                <view class="info-item">
                                    <text class="info-label">未完成</text>
                                    <text class="info-value warning">{{ getUnfinishedCount(item) }}</text>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </template>
        </common-list>
    </view>
</template>

<script setup lang="uts">
    import { ref, onShow } from 'vue'
    import { getPurchaseApplyList } from '../../api/apply/index'

    // 列表数据
    const dataList = ref<any[]>([])
    const keyword = ref<string>("")
    const currentStatus = ref<string>("")
    const page = ref<number>(1)
    const pageSize: number = 10
    const hasMore = ref<boolean>(true)
    const loading = ref<boolean>(false)
    const refreshing = ref<boolean>(false)

    // 获取申请单号
    const getApplyCode = (item: any | null): string => {
        if (item == null) return ''
        const jsonItem = item as UTSJSONObject
        const val = jsonItem['applyCode']
        return val != null ? val.toString() : ''
    }

    // 获取状态
    const getStatus = (item: any | null): string => {
        if (item == null) return ''
        const jsonItem = item as UTSJSONObject
        const val = jsonItem['status']
        return val != null ? val.toString() : ''
    }

    // 获取状态文本
    const getStatusText = (item: any | null): string => {
        if (item == null) return ''
        const jsonItem = item as UTSJSONObject
        const val = jsonItem['status']
        const status = val != null ? val.toString() : ''
        switch (status) {
            case 'PREPARE': return '草稿'
            case 'CONFIRMED': return '已确认'
            case 'FINISHED': return '已完成'
            case 'CANCEL': return '已取消'
			case 'APPROVED': return '已审批'
			case 'APPROVING': return '审批中'
            default: return status
        }
    }

    // 获取创建时间
    const getCreateTime = (item: any | null): string => {
        if (item == null) return ''
        const jsonItem = item as UTSJSONObject
        const val = jsonItem['createTime']
        return val != null ? val.toString() : ''
    }

    // 获取申请人
    const getNickName = (item: any | null): string => {
        if (item == null) return ''
        const jsonItem = item as UTSJSONObject
        const val = jsonItem['nickName']
        return val != null ? val.toString() : ''
    }

    // 获取已完成数量
    const getFinishedCount = (item: any | null): string => {
        if (item == null) return '0'
        const jsonItem = item as UTSJSONObject
        const val = jsonItem['finishedCount']
        return val != null ? val.toString() : '0'
    }

    // 获取未完成数量
    const getUnfinishedCount = (item: any | null): string => {
        if (item == null) return '0'
        const jsonItem = item as UTSJSONObject
        const val = jsonItem['unfinishedCount']
        return val != null ? val.toString() : '0'
    }

    // 加载列表数据
    const loadData = async (isRefresh: boolean): Promise<void> => {
        if (loading.value) return

        try {
            loading.value = true

            if (isRefresh) {
                page.value = 1
            }

            const searchKeyword = keyword.value != null ? keyword.value : ''
            const statusParam = currentStatus.value != null ? currentStatus.value : ''
            const result = await getPurchaseApplyList(page.value, pageSize, searchKeyword, statusParam)
            const resultObj = result as UTSJSONObject
            const rows = resultObj['rows']
            const total = resultObj['total'] as number

            if (rows != null) {
                const newData = rows as any[]
                if (isRefresh) {
                    dataList.value = newData
                } else {
                    dataList.value = [...dataList.value, ...newData]
                }
                hasMore.value = dataList.value.length < total
            } else {
                if (isRefresh) {
                    dataList.value = []
                }
                hasMore.value = false
            }

        } catch (e) {
            console.error('加载失败:', e)
        } finally {
            loading.value = false
            refreshing.value = false
        }
    }

    // 下拉刷新
    const handleRefresh = (): void => {
        refreshing.value = true
        loadData(true)
    }

    // 加载更多
    const loadMore = (): void => {
        if (!hasMore.value || loading.value) return
        page.value++
        loadData(false)
    }

    // 搜索
    const handleSearch = (): void => {
        const searchKeyword = keyword.value != null ? keyword.value : ''
        loadData(true)
    }

    // 清空搜索关键字
    const clearKeyword = (): void => {
        keyword.value = ''
        loadData(true)
    }

    // 切换状态
    const handleStatusChange = (status: string): void => {
        currentStatus.value = status
        loadData(true)
    }

	const handleRight = ():void=>{
		uni.navigateTo({
		    url: `/pages/apply/applyNew?from=index`
		})
	}
	
    // 点击列表项
    const handleItemClick = (item: any | null, index: number): void => {
        if (item == null) return
        const jsonItem = item as UTSJSONObject
        const applyId = jsonItem['applyId']
        uni.navigateTo({
            url: `/pages/apply/applyInfo?id=${applyId}`
        })
    }

    // 初始化
    loadData(true)

    // 页面显示时刷新列表
    onShow(() => {
        loadData(true)
    })
</script>

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

    .search-block {
        background-color: #ffffff;
    }

    .search-bar {
        padding: 20rpx 30rpx;
    }

    .status-tabs {
        display: flex;
        flex-direction: row;
        padding: 0rpx 30rpx 20rpx;
        background-color: #ffffff;
    }

    .status-tab {
        flex: 1;
        padding: 16rpx 0;
        text-align: center;
        margin-right: 16rpx;
        border-radius: 8rpx;
        background-color: #f5f5f5;
        justify-content: center;
        align-items: center;

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

        &.active {
            background-color: #007aff;
        }

        .status-tab-text {
            font-size: 26rpx;
            color: #666666;
            text-align: center;

            &.active-text {
                color: #ffffff;
                font-weight: bold;
            }
        }
    }

    .search-box {
        flex-direction: row;
        align-items: center;
        height: 72rpx;
        padding: 0 24rpx;
        background-color: #f5f5f5;
        border-radius: 36rpx;

        .search-icon {
            width: 32rpx;
            height: 32rpx;
            margin-right: 12rpx;
        }

        .search-input {
            flex: 1;
            font-size: 28rpx;
            color: #333333;
        }

        .search-btn {
            padding: 10rpx 20rpx;
            background-color: #007aff;
            border-radius: 8rpx;
            margin-left: 10rpx;
        }

        .search-btn-text {
            color: #ffffff;
            font-size: 24rpx;
        }

        .clear-btn {
            width: 36rpx;
            height: 36rpx;
            border-radius: 18rpx;
            background-color: #cccccc;
            align-items: center;
            justify-content: center;
            margin-left: 10rpx;
        }

        .clear-btn-text {
            color: #ffffff;
            font-size: 24rpx;
            font-weight: bold;
        }
    }

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

    .item-container {
        padding: 30rpx;
    }

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

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

        .item-status {
            font-size: 26rpx;
            padding: 6rpx 16rpx;
            border-radius: 6rpx;
            
            &.status-PREPARE {
                background-color: #f0f0f0;
                color: #666666;
            }
            &.status-CONFIRMED {
                background-color: #e6f7ff;
                color: #1890ff;
            }
            &.status-FINISHED {
                background-color: #f6ffed;
                color: #52c41a;
            }
            &.status-CANCEL {
                background-color: #fff1f0;
                color: #ff4d4f;
            }
			&.status-APPROVING {
			    background-color: #d1f5f8;
			    color: #ff007f;
			}
			&.status-APPROVED {
			    background-color: #ebfffd;
			    color: #55ff00;
			}
        }
    }

    .item-info {
        padding: 20rpx;
        background-color: #f8f9fa;
        border-radius: 8rpx;

        .info-row {
            flex-direction: row;
            justify-content: space-between;
            margin-bottom: 16rpx;

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

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

                &:last-child {
                    flex: 1;
                    justify-content: flex-end;
                }

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

                .info-value {
                    font-size: 26rpx;
                    color: #333333;
                    flex: 1;
                    
                    &.success {
                        color: #52c41a;
                    }
                    &.warning {
                        color: #faad14;
                    }
                }
            }
        }
    }
</style>
