<template>
    <view class="common-page" style="padding: 0;padding-bottom: 130rpx;">
        <InfoCard :detail="detail" type="mall" />

        <TrackRecord v-if="records.length > 0" :records="records" class="mt-20" />

        <view class="fixed-bottom" v-if="showButtons">
            <u-button v-if="canEdit" type="warning" size="large" @click="onEdit">编辑</u-button>
            <u-button v-if="canVoid" type="error" size="large" @click="onVoid">作废</u-button>
            <u-button v-if="canFinish" type="primary" size="large" @click="onFinish">完成</u-button>
            <u-button v-if="canReopen" type="primary" size="large" @click="onReopen">重开</u-button>
        </view>
    </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import InfoCard from '@/pages/order/components/info-card.vue'
import TrackRecord from '@/pages/order/components/track-record.vue'

const detail = ref({})
const records = ref([])
const workOrderId = ref('')

// 获取当前用户信息
const currentUserId = ref(uni.getStorageSync('userInfo')?.userId || '')

// 计算按钮显示逻辑
const canEdit = computed(() => {
    const status = detail.value.status
    const isCreator = currentUserId.value === detail.value.createUserId
    const isAssignee = detail.value.handleUsers?.some(user => user.userId === currentUserId.value)
    
    if (isCreator) {
        return status === 1 || status === 2 || status === 3 // 待处理、处理中、仓库处理
    } else if (isAssignee) {
        return status === 1 || status === 2 || status === 3 // 待处理、处理中、仓库处理
    }
    return false
})

const canVoid = computed(() => {
    const status = detail.value.status
    const isCreator = currentUserId.value === detail.value.createUserId
    return isCreator && (status === 1 || status === 2 || status === 3) // 待处理、处理中、仓库处理
})

const canFinish = computed(() => {
    const status = detail.value.status
    const isCreator = currentUserId.value === detail.value.createUserId
    const isAssignee = detail.value.handleUsers?.some(user => user.userId === currentUserId.value)
    return (isCreator || isAssignee) && (status === 1 || status === 2 || status === 3) // 待处理、处理中、仓库处理
})

const canReopen = computed(() => {
    const status = detail.value.status
    const isCreator = currentUserId.value === detail.value.createUserId
    return isCreator && (status === 4 || status === 5) // 已完成、已作废
})

const showButtons = computed(() => {
    return canEdit.value || canVoid.value || canFinish.value || canReopen.value
})

const getDetail = async (id) => {
    try {
        const res = await uni.$u.http.get(`/app/workOrder/getWorkOrderDetail`, {
            params: { workOrderId: id }
        })
        if (res?.code === 200 && res?.data) {
            const data = res.data;
            detail.value = {
                ...data,
                waybillCode: data.waybillCode || '',
                taskTypeName: data.taskTypeName || '',
                verifyStatusName: data.inspectionStatusName || '', // 验货状态
                taskDetail: data.deatil || data.taskDetail || '',
                createUser: data.createUserName || '',
                createUserId: data.createUserId || '',
                createTime: data.createTime || '',
                imageUrl: (data.imgInfo && data.imgInfo.imgUrlList && data.imgInfo.imgUrlList[0]) || data.imageUrl || '/static/img/book.png',
                imageUrls: (data.imgInfo && data.imgInfo.imgUrlList) || [],
                status: data.status,
                handleUsers: data.handleUsers || []
            }
            records.value = data.changeRecords || []
            return
        }
    } catch (e) {
        console.error(e)
    }
}

const onEdit = () => {
    uni.navigateTo({
        url: `/pages/order/mall/created?workOrderId=${workOrderId.value}&mode=edit&waybillCode=${detail.value.waybillCode}&readonly=1`
    })
}

const onVoid = () => {
    uni.showModal({
        title: '提示',
        content: '确定要作废该工单吗？',
        success: async (res) => {
            if (res.confirm) {
                try {
                    const result = await uni.$u.http.post('/app/workOrder/cancel', { id: workOrderId.value })
                    if (result.code === 200) {
                        uni.$u.toast('已作废')
                        setTimeout(() => {
                            uni.navigateBack()
                        }, 1000)
                    } else {
                        uni.$u.toast(result.msg || '操作失败')
                    }
                } catch (e) {
                    console.error(e)
                }
            }
        }
    })
}

const onFinish = () => {
    uni.showModal({
        title: '提示',
        content: '确定要完成该工单吗？',
        success: async (res) => {
            if (res.confirm) {
                try {
                    const result = await uni.$u.http.post('/app/workOrder/finish', { ids: [workOrderId.value] })
                    if (result.code === 200) {
                        uni.$u.toast('已完成')
                        setTimeout(() => {
                            uni.navigateBack()
                        }, 1000)
                    } else {
                        uni.$u.toast(result.msg || '操作失败')
                    }
                } catch (e) {
                    console.error(e)
                }
            }
        }
    })
}

const onReopen = () => {
    uni.showModal({
        title: '提示',
        content: '确定要重开该工单吗？',
        success: async (res) => {
            if (res.confirm) {
                try {
                    // 这里需要调用重开工单的接口
                    // 假设接口是 /app/workOrder/reopen
                    const result = await uni.$u.http.post('/app/workOrder/reopen', { id: workOrderId.value })
                    if (result.code === 200) {
                        uni.$u.toast('已重开')
                        setTimeout(() => {
                            uni.navigateBack()
                        }, 1000)
                    } else {
                        uni.$u.toast(result.msg || '操作失败')
                    }
                } catch (e) {
                    console.error(e)
                }
            }
        }
    })
}

onLoad((options) => {
    workOrderId.value = options.id
    getDetail(options.id)
})
</script>

<style lang="scss" scoped>
.mt-20 {
    margin-top: 20rpx;
}
</style>
