<template>
    <view class="common-page" style="padding: 0;">
        <view class="header">
            <u-navbar title="历史工单" :border="false" fixed safe-area-inset-top>
                <template #left>
                    <u-icon name="arrow-left" color="#333333" size="20" @click="goBack"></u-icon>
                </template>
            </u-navbar>
        </view>

        <view class="content" v-if="workOrderDetail">
            <!-- 工单信息 -->
            <view class="info-section">
                <view class="info-row">
                    <text class="label">快递单号：</text>
                    <text class="value">{{ workOrderDetail.waybillCode }}</text>
                </view>
                <view class="info-row" v-if="workOrderDetail.orderId">
                    <text class="label">订单编号：</text>
                    <text class="value link-text" @click="goToOrderDetail">{{ workOrderDetail.orderId }}</text>
                </view>
                <view class="info-row">
                    <text class="label">任务类型：</text>
                    <text class="value">{{ workOrderDetail.taskTypeName || '-' }}</text>
                </view>
                <view class="info-row">
                    <text class="label">验货状态：</text>
                    <text class="value">{{ workOrderDetail.inspectionStatusName || '-' }}</text>
                </view>
                <view class="info-row">
                    <text class="label">任务详情：</text>
                    <text class="value">{{ workOrderDetail.deatil || '-' }}</text>
                </view>
                <view class="info-row">
                    <text class="label">创建人：</text>
                    <text class="value">{{ workOrderDetail.createUserName || '-' }}</text>
                </view>
                <view class="info-row">
                    <text class="label">创建时间：</text>
                    <text class="value">{{ formatTime(workOrderDetail.createTime) }}</text>
                </view>
                <view class="info-row">
                    <text class="label">任务状态：</text>
                    <text class="value status-text" :class="'status-' + workOrderDetail.status">{{ getStatusText(workOrderDetail.status) }}</text>
                </view>

                <view class="info-row">
                    <text class="label">指派人：</text>
                    <text class="value">{{  workOrderDetail.handleUsers.map(item => item.userName).join(',') || '-' }}</text>
                </view>
                
                <!-- 图片展示 -->
                <view class="image-list" v-if="workOrderDetail.imgInfo && workOrderDetail.imgInfo.imgUrlList.length > 0">
                    <image 
                        v-for="(img, index) in workOrderDetail.imgInfo.imgUrlList" 
                        :key="index"
                        :src="img" 
                        mode="aspectFill"
                        class="work-order-image"
                        @click="previewImage(index)"
                    ></image>
                </view>
            </view>
        </view>

        <!-- 底部操作按钮 -->
        <view class="fixed-bottom" v-if="showButtons">
            <template v-if="isCreator">
                <!-- 创建人按钮 -->
                <template v-if="workOrderDetail.status === 1 || workOrderDetail.status === 2 || workOrderDetail.status === 3">
                    <!-- 待处理、处理中、仓库处理状态 -->
                    <u-button type="warning" size="large" text="编辑" @click="handleEdit"></u-button>
                    <u-button type="primary" size="large" text="完成" @click="handleFinish"></u-button>
                    <u-button type="error" size="large" text="作废" @click="handleCancel"></u-button>
                </template>
                <template v-else-if="workOrderDetail.status === 4 || workOrderDetail.status === 5">
                    <!-- 已完成、已作废状态 -->
                    <u-button type="primary" size="large" text="重开" @click="handleReopen"></u-button>
                </template>
            </template>
            
            <template v-else>
                <!-- 被指派人按钮 -->
                <template v-if="workOrderDetail.status === 1 || workOrderDetail.status === 2 || workOrderDetail.status === 3">
                    <!-- 未处理、处理中、仓库处理状态 -->
                    <u-button type="warning" size="large" text="编辑" @click="handleEdit"></u-button>
                    <u-button type="primary" size="large" text="完成" @click="handleFinish"></u-button>
                </template>
                <!-- 已完成、已作废状态无操作按钮 -->
            </template>
        </view>
    </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

const workOrderId = ref('')
const orderType = ref('') // 1-卖书 2-回收
const waybillCode = ref('')
const orderId = ref('')
const workOrderDetail = ref(null)
const currentUserId = ref(null)

// 判断是否为创建人
const isCreator = computed(() => {
    if (!workOrderDetail.value || !currentUserId.value) return false
    return workOrderDetail.value.createUserId === currentUserId.value
})

// 是否显示按钮
const showButtons = computed(() => {
    if (!workOrderDetail.value) return false
    const status = workOrderDetail.value.status
    // 状态：1-待处理 2-处理中 3-仓库处理 4-完成 5-作废
    return [1, 2, 3, 4, 5].includes(status)
})

// 获取状态文本
const getStatusText = (status) => {
    const statusMap = {
        1: '待处理',
        2: '处理中',
        3: '仓库处理',
        4: '已完成',
        5: '已作废'
    }
    return statusMap[status] || '未知状态'
}

// 格式化时间
const formatTime = (time) => {
    if (!time) return '-'
    return time.replace('T', ' ').substring(0, 19)
}

// 获取工单详情
const getWorkOrderDetail = async () => {
    try {
        uni.showLoading({ title: '加载中...' })
        const res = await uni.$u.http.get('/app/workOrder/getWorkOrderDetail', {
            params: { workOrderId: workOrderId.value }
        })
        
        if (res.code === 200 && res.data) {
            workOrderDetail.value = res.data
        } else {
            uni.$u.toast(res.msg || '获取工单详情失败')
        }
    } catch (error) {
        console.error(error)
        uni.$u.toast('网络错误')
    } finally {
        uni.hideLoading()
    }
}

// 预览图片
const previewImage = (index) => {
    if (workOrderDetail.value?.imgInfo) {
        const urls = Array.isArray(workOrderDetail.value.imgInfo) ? workOrderDetail.value.imgInfo : workOrderDetail.value.imgInfo.split(',')
        if (urls.length > 0) {
            uni.previewImage({
                urls: urls,
                current: index
            })
        }
    }
}

// 返回上一页
const goBack = () => {
    uni.navigateBack()
}

// 跳转到订单详情
const goToOrderDetail = () => {
    if (!workOrderDetail.value?.orderId) return
    uni.navigateTo({
        url: `/pages/index/detail/index?id=${workOrderDetail.value.orderId}`
    })
}

// 编辑工单
const handleEdit = () => {
    uni.navigateTo({
        url: `/pages/order/${orderType.value == 1 ? 'mall' : 'recycle'}/created?waybillCode=${waybillCode.value}&orderId=${orderId.value}&workOrderId=${workOrderId.value}&mode=edit`
    })
}

// 完成工单
const handleFinish = async () => {
    uni.showModal({
        title: '提示',
        content: '确定要完成该工单吗？',
        success: async (res) => {
            if (res.confirm) {
                try {
                    uni.showLoading({ title: '提交中...' })
                    const result = await uni.$u.http.post('/app/workOrder/finish', {
                        ids: [workOrderId.value]
                    })
                    
                    if (result.code === 200) {
                        uni.$u.ttsModule.speak('提交成功')
                        uni.$u.toast('操作成功')
                        getWorkOrderDetail()
                    } else {
                        uni.$u.toast(result.msg || '操作失败')
                    }
                } catch (error) {
                    console.error(error)
                    uni.$u.toast('网络错误')
                } finally {
                    uni.hideLoading()
                }
            }
        }
    })
}

// 作废工单
const handleCancel = async () => {
    uni.showModal({
        title: '提示',
        content: '确定要作废该工单吗？',
        success: async (res) => {
            if (res.confirm) {
                try {
                    uni.showLoading({ title: '提交中...' })
                    const result = await uni.$u.http.post('/app/workOrder/cancel', {
                        id: workOrderId.value
                    })
                    
                    if (result.code === 200) {
                        uni.$u.ttsModule.speak('操作成功')
                        uni.$u.toast('操作成功')
                        getWorkOrderDetail()
                    } else {
                        uni.$u.toast(result.msg || '操作失败')
                    }
                } catch (error) {
                    console.error(error)
                    uni.$u.toast('网络错误')
                } finally {
                    uni.hideLoading()
                }
            }
        }
    })
}

// 重开工单（重新打开已完成的工单）
const handleReopen = async () => {
    uni.showModal({
        title: '提示',
        content: '确定要重开该工单吗？',
        success: async (res) => {
            if (res.confirm) {
                try {
                    uni.showLoading({ title: '提交中...' })
                    const result = await uni.$u.http.post('/app/workOrder/reopen', {
                        id: workOrderId.value
                    })
                    
                    if (result.code === 200) {
                        uni.$u.ttsModule.speak('操作成功')
                        uni.$u.toast('操作成功')
                        getWorkOrderDetail()
                    } else {
                        uni.$u.toast(result.msg || '操作失败')
                    }
                } catch (error) {
                    console.error(error)
                    uni.$u.toast('网络错误')
                } finally {
                    uni.hideLoading()
                }
            }
        }
    })
}

onLoad((options) => {
    workOrderId.value = options.workOrderId
    orderType.value = options.type
    waybillCode.value = options.waybillCode || ''
    orderId.value = options.orderId || ''
    
    // 获取当前用户ID（这里需要从用户信息中获取，暂时使用固定值或从缓存读取）
    const userInfo = uni.getStorageSync('userInfo') || {}
    currentUserId.value = userInfo.userId || null
    
    // 加载工单详情
    getWorkOrderDetail()
})
</script>

<style lang="scss" scoped>
.content {
    padding-top: 12px;
    border-radius: 0;
    /* #ifdef APP-PLUS */
    padding-top: 100px;
    /* #endif */
}

.info-section {
    background-color: #ffffff;
    padding: 20px;
    margin-bottom: 12px;
}

.info-row {
    display: flex;
    align-items: flex-start;
    margin-bottom: 16px;
    line-height: 1.5;

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

.label {
    color: #666;
    font-size: 28rpx;
    width: 160rpx;
    flex-shrink: 0;
}

.value {
    color: #333;
    font-size: 28rpx;
    flex: 1;
    word-break: break-all;
}

.link-text {
    color: #2979ff;
    cursor: pointer;
    
    &:active {
        opacity: 0.7;
    }
}

.status-text {
    &.status-1 {
        color: #e6a23c; // 待处理 - 橙色
    }

    &.status-2 {
        color: #409eff; // 处理中 - 蓝色
    }

    &.status-3 {
        color: #909399; // 仓库处理 - 灰色
    }

    &.status-4 {
        color: #67c23a; // 已完成 - 绿色
    }

    &.status-5 {
        color: #f56c6c; // 已作废 - 红色
    }
}

.image-list {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
    margin-top: 20rpx;
}

.work-order-image {
    width: 180rpx;
    height: 180rpx;
    border-radius: 8rpx;
}
</style>