<template>
    <view class="workcase-list-container">
        <!-- 筛选栏 -->
        <view class="filter-bar">
            <picker 
                class="filter-picker" 
                :value="statusIndex" 
                :range="statusOptions" 
                @change="onStatusChange"
            >
                <view class="picker-content">
                    <text class="picker-text">{{statusOptions[statusIndex]}}</text>
                    <text class="picker-arrow">▼</text>
                </view>
            </picker>
            
            <picker 
                class="filter-picker" 
                :value="categoryIndex" 
                :range="categoryOptions" 
                @change="onCategoryChange"
            >
                <view class="picker-content">
                    <text class="picker-text">{{categoryOptions[categoryIndex]}}</text>
                    <text class="picker-arrow">▼</text>
                </view>
            </picker>
        </view>
        
        <!-- 工单列表 -->
        <scroll-view 
            class="workcase-list" 
            scroll-y="true"
            @scrolltolower="loadMore"
            :refresher-enabled="true"
            @refresherrefresh="onRefresh"
            :refresher-triggered="isRefreshing"
        >
            <!-- 统计信息 -->
            <view class="stats-card">
                <view class="stat-item">
                    <text class="stat-number">{{stats.total}}</text>
                    <text class="stat-label">总工单</text>
                </view>
                <view class="stat-item">
                    <text class="stat-number">{{stats.pending}}</text>
                    <text class="stat-label">待处理</text>
                </view>
                <view class="stat-item">
                    <text class="stat-number">{{stats.processing}}</text>
                    <text class="stat-label">处理中</text>
                </view>
                <view class="stat-item">
                    <text class="stat-number">{{stats.completed}}</text>
                    <text class="stat-label">已完成</text>
                </view>
            </view>
            
            <!-- 工单卡片列表 -->
            <view 
                class="workcase-card"
                v-for="workcase in displayList"
                :key="workcase.id"
                @tap="goToDetail(workcase)"
            >
                <view class="card-header">
                    <view class="title-row">
                        <text class="workcase-title">{{workcase.title}}</text>
                        <view class="status-tag" :class="getStatusClass(workcase.status)">
                            <text class="status-text">{{workcase.statusText}}</text>
                        </view>
                    </view>
                    <text class="workcase-id">工单编号：{{workcase.number}}</text>
                </view>
                
                <view class="card-content">
                    <view class="info-row">
                        <text class="info-label">分类：</text>
                        <text class="info-value">{{workcase.category}}</text>
                    </view>
                    <view class="info-row">
                        <text class="info-label">紧急程度：</text>
                        <text class="info-value priority" :class="getPriorityClass(workcase.priority)">
                            {{workcase.priority}}
                        </text>
                    </view>
                    <view class="info-row">
                        <text class="info-label">创建时间：</text>
                        <text class="info-value">{{formatTime(workcase.createTime)}}</text>
                    </view>
                </view>
                
                <view class="card-description">
                    <text class="description-text">{{workcase.description}}</text>
                </view>
                
                <!-- 操作按钮 -->
                <view class="card-actions" v-if="workcase.status !== 'completed'">
                    <button 
                        class="action-btn secondary"
                        v-if="workcase.status === 'pending'"
                        @tap.stop="cancelWorkcase(workcase)"
                    >
                        取消工单
                    </button>
                    <button 
                        class="action-btn primary"
                        v-if="workcase.status === 'processing'"
                        @tap.stop="confirmComplete(workcase)"
                    >
                        确认完成
                    </button>
                    <button 
                        class="action-btn secondary"
                        @tap.stop="contactService(workcase)"
                    >
                        联系客服
                    </button>
                </view>
                
                <!-- 进度条 -->
                <view class="progress-bar" v-if="workcase.status === 'processing'">
                    <view class="progress-fill" :style="'width: ' + workcase.progress + '%'"></view>
                </view>
            </view>
            
            <!-- 空状态 -->
            <view class="empty-state" v-if="displayList.length === 0 && !isLoading">
                <image class="empty-icon" src="/static/empty-workcase.png" mode="aspectFit" />
                <text class="empty-text">暂无工单记录</text>
                <button class="create-btn" @tap="createWorkcase">
                    <text class="create-icon">+</text>
                    <text>创建工单</text>
                </button>
            </view>
            
            <!-- 加载更多 -->
            <view class="load-more" v-if="hasMore">
                <text class="load-text">{{isLoading ? '加载中...' : '上拉加载更多'}}</text>
            </view>
        </scroll-view>
        
        <!-- 悬浮按钮 -->
        <view class="fab" @tap="createWorkcase">
            <text class="fab-icon">+</text>
        </view>
    </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

// 接口定义
interface Workcase {
    id: number
    number: string
    title: string
    description: string
    category: string
    priority: string
    status: 'pending' | 'processing' | 'completed' | 'cancelled'
    statusText: string
    progress: number
    createTime: Date
    updateTime: Date
}

interface Stats {
    total: number
    pending: number
    processing: number
    completed: number
}

// 响应式数据
const workcaseList = ref<Workcase[]>([])
const displayList = ref<Workcase[]>([])
const statusOptions = ref<string[]>(['全部状态', '待处理', '处理中', '已完成', '已取消'])
const statusIndex = ref<number>(0)
const categoryOptions = ref<string[]>(['全部分类', '设施报修', '环境卫生', '交通问题', '安全隐患', '其他问题'])
const categoryIndex = ref<number>(0)
const stats = ref<Stats>({
    total: 0,
    pending: 0,
    processing: 0,
    completed: 0
})
const isLoading = ref<boolean>(false)
const isRefreshing = ref<boolean>(false)
const hasMore = ref<boolean>(true)
const page = ref<number>(1)

// 生命周期
onMounted(() => {
    loadData()
})

// 方法定义
// 加载数据
async function loadData() {
    isLoading.value = true
    
    try {
        // 模拟数据
        const mockData = generateMockData()
        workcaseList.value = mockData
        updateDisplayList()
        updateStats()
    } catch (error) {
        uni.showToast({
            title: '加载失败',
            icon: 'error'
        })
    } finally {
        isLoading.value = false
        isRefreshing.value = false
    }
}

// 生成模拟数据
function generateMockData(): Workcase[] {
            const categories = ['设施报修', '环境卫生', '交通问题', '安全隐患', '其他问题']
            const priorities = ['一般', '紧急', '非常紧急']
            const statuses: ('pending' | 'processing' | 'completed' | 'cancelled')[] = ['pending', 'processing', 'completed', 'cancelled']
            const statusTexts = {
                pending: '待处理',
                processing: '处理中', 
                completed: '已完成',
                cancelled: '已取消'
            }
            
            const mockList: Workcase[] = []
            for (let i = 1; i <= 15; i++) {
                const status = statuses[Math.floor(Math.random() * statuses.length)]
                mockList.push({
                    id: i,
                    number: `WC${new Date().getFullYear()}${String(i).padStart(4, '0')}`,
                    title: `测试工单${i}`,
                    description: `这是一个测试工单的描述内容，描述了具体的问题情况...`,
                    category: categories[Math.floor(Math.random() * categories.length)],
                    priority: priorities[Math.floor(Math.random() * priorities.length)],
                    status: status,
                    statusText: statusTexts[status],
                    progress: status === 'processing' ? Math.floor(Math.random() * 80) + 10 : 0,
                    createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000),
                    updateTime: new Date()
                })
            }
            return mockList
        }

// 更新显示列表
function updateDisplayList() {
    let filtered = [...workcaseList.value]
    
    // 状态筛选
    if (statusIndex.value > 0) {
        const statusMap: Record<number, string> = {
            1: 'pending',
            2: 'processing', 
            3: 'completed',
            4: 'cancelled'
        }
        filtered = filtered.filter(item => item.status === statusMap[statusIndex.value])
    }
    
    // 分类筛选
    if (categoryIndex.value > 0) {
        const category = categoryOptions.value[categoryIndex.value]
        filtered = filtered.filter(item => item.category === category)
    }
    
    displayList.value = filtered
}

// 更新统计信息
function updateStats() {
    stats.value = {
        total: workcaseList.value.length,
        pending: workcaseList.value.filter(item => item.status === 'pending').length,
        processing: workcaseList.value.filter(item => item.status === 'processing').length,
        completed: workcaseList.value.filter(item => item.status === 'completed').length
    }
}

// 状态筛选改变
function onStatusChange(e: any) {
    statusIndex.value = e.detail.value
    updateDisplayList()
}

// 分类筛选改变
function onCategoryChange(e: any) {
    categoryIndex.value = e.detail.value
    updateDisplayList()
}

// 下拉刷新
function onRefresh() {
    isRefreshing.value = true
    page.value = 1
    loadData()
}

// 加载更多
function loadMore() {
    if (!hasMore.value || isLoading.value) return
    
    page.value++
    // 模拟加载更多
    setTimeout(() => {
        if (page.value > 3) {
            hasMore.value = false
        }
    }, 1000)
}

// 跳转到详情页
function goToDetail(workcase: Workcase) {
    uni.navigateTo({
        url: `/pages/workcase/detail?id=${workcase.id}`
    })
}

// 获取状态样式
function getStatusClass(status: string) {
    return {
        'status-pending': status === 'pending',
        'status-processing': status === 'processing',
        'status-completed': status === 'completed',
        'status-cancelled': status === 'cancelled'
    }
}

// 获取优先级样式
function getPriorityClass(priority: string) {
    return {
        'priority-normal': priority === '一般',
        'priority-urgent': priority === '紧急',
        'priority-emergency': priority === '非常紧急'
    }
}

// 格式化时间
function formatTime(date: Date) {
    const now = new Date()
    const diff = now.getTime() - new Date(date).getTime()
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))
    
    if (days === 0) {
        const hours = Math.floor(diff / (1000 * 60 * 60))
        if (hours === 0) {
            const minutes = Math.floor(diff / (1000 * 60))
            return `${minutes}分钟前`
        }
        return `${hours}小时前`
    } else if (days === 1) {
        return '昨天'
    } else if (days < 7) {
        return `${days}天前`
    } else {
        return new Date(date).toLocaleDateString()
    }
}

// 取消工单
function cancelWorkcase(workcase: Workcase) {
    uni.showModal({
        title: '确认取消',
        content: `确定要取消工单"${workcase.title}"吗？`,
        success: (res) => {
            if (res.confirm) {
                workcase.status = 'cancelled'
                workcase.statusText = '已取消'
                updateStats()
                updateDisplayList()
                
                uni.showToast({
                    title: '工单已取消',
                    icon: 'success'
                })
            }
        }
    })
}

// 确认完成
function confirmComplete(workcase: Workcase) {
    uni.showModal({
        title: '确认完成',
        content: `确认工单"${workcase.title}"已处理完成？`,
        success: (res) => {
            if (res.confirm) {
                workcase.status = 'completed'
                workcase.statusText = '已完成'
                workcase.progress = 100
                updateStats()
                updateDisplayList()
                
                uni.showToast({
                    title: '工单已完成',
                    icon: 'success'
                })
            }
        }
    })
}

// 联系客服
function contactService(workcase: Workcase) {
    uni.showActionSheet({
        itemList: ['拨打电话', '在线客服', '查看进度'],
        success: (res) => {
            switch (res.tapIndex) {
                case 0:
                    uni.makePhoneCall({
                        phoneNumber: '400-123-4567'
                    })
                    break
                case 1:
                    uni.navigateTo({
                        url: '/pages/index/index'
                    })
                    break
                case 2:
                    goToDetail(workcase)
                    break
            }
        }
    })
}

// 创建工单
function createWorkcase() {
    uni.switchTab({
        url: '/pages/index/index'
    })
}
</script>

<style lang="scss" scoped>
@import './list.scss';
</style>
