<template>
    <view class="task-upload">
        <!-- 任务状态提示 -->
        <view class="status-box" v-if="taskInfo.status != 0">
            <!-- 驳回状态 -->
            <view class="reject-box" v-if="taskInfo.status == 3">
                <view class="reject-icon">⚠</view>
                <view class="reject-content">
                    <view class="reject-title">拒绝原因:{{taskInfo.rejectTxt}}</view>
                </view>
            </view>
            <!-- 审核中状态 -->
            <view class="reviewing-box" v-if="taskInfo.status == 1">
                <view class="reviewing-icon">⏳</view>
                <view class="reviewing-content">
                    <view class="reviewing-title">任务审核中，请耐心等待审核结果</view>
                </view>
            </view>
            <!-- 已通过状态 -->
            <view class="approved-box" v-if="taskInfo.status == 2">
                <view class="approved-icon">✅</view>
                <view class="approved-content">
                    <view class="approved-title">任务已审核通过</view>
                </view>
            </view>
        </view>

        <!-- 上传表单 -->
        <view class="upload-form">
            <!-- 链接输入 -->
            <view class="form-item">
                <view class="form-label">笔记链接</view>
                <view class="form-input">
                    <u-textarea v-model="formData.proveTxt" 
                    :border="false"
                    height="300rpx"
                    :disabled="taskInfo.status == 1 || taskInfo.status == 2"
                    placeholder="请输入笔记链接" :maxlength="300" count />
                </view>
            </view>

            <!-- 图片上传 -->
            <view class="form-item">
                <view class="form-label">笔记截图</view>
                <view class="upload-box">
                    <u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="proveImage"
                        multiple :maxCount="3" :disabled="taskInfo.status == 1 || taskInfo.status == 2"></u-upload>
                </view>
            </view>

            <!-- 提交按钮 -->
            <view class="submit-btn" v-if="taskInfo.status == 0 || taskInfo.status == 3">
                <u-button type="primary" color="#ffaa48" shape="circle" @click="submitTaskHandler">提交审核</u-button>
            </view>
        </view>
    </view>
</template>

<script>
import { getTaskDetailUser, submitTask } from "@/api/order/task.js"
export default {
    data() {
        return {
            taskId: null,
            taskStatus: 0,
            taskInfo: {
                id: 0,
                title: '',
                taskEndTime: '',
                rejectTxt: '',
                proveTxt: '',
                status: 0
            },
            formData: {
                taskId: 0,
                proveImage: [],
                rejectTxt: '',
                proveTxt: '',
            },
            fileList: []
        }
    },
    onLoad(options) {
        if (options.id) {
            this.taskId = options.id
            this.formData.taskId = options.id
            this.getTaskDetail()
        } else {
            uni.showToast({
                title: '任务ID不存在',
                icon: 'none'
            })
            setTimeout(() => {
                uni.navigateBack()
            }, 1500)
        }
    },
    methods: {
        getTaskDetail() {
            // 获取任务详情
            getTaskDetailUser(this.taskId).then(res => {
                if (res && res.code == 200) {
                    this.taskInfo = res.data

                    // 如果任务已有审核文本，填充到表单
                    if (res.data.proveTxt) {
                        this.formData.proveTxt = res.data.proveTxt;
                    }

                    // 如果任务已有图片，添加到文件列表显示
                    if (res.data.proveImage) {
                        const imageUrls = res.data.proveImage.split(',');
                        imageUrls.forEach(url => {
                            if (url) {
                                this.fileList.push({
                                    url: url,
                                    status: 'success',
                                    message: '已上传',
                                    isImage: true
                                });
                                // 同时更新formData中的图片数组
                                this.formData.proveImage.push(url);
                            }
                        });
                    }
                }
            })
        },
        uploadFilePromise(url) {
            return new Promise((resolve, reject) => {
                let uploadTask = uni.uploadFile({
                    url: 'https://store-test.catmdogd.com/test-api/h5/oss/upload',
                    filePath: url,
                    name: 'file',
                    formData: {
                        user: 'test'
                    },
                    success: (res) => {
                        if (res && res.data) {
                            try {
                                let resData = JSON.parse(res.data);
                                if (resData.url) {
                                    resolve(resData.url);
                                } else {
                                    reject("上传失败: 未获取到图片URL");
                                }
                            } catch (e) {
                                reject("上传失败: 解析响应数据错误");
                            }
                        } else {
                            reject("上传失败: 响应数据为空");
                        }
                    },
                    fail: (err) => {
                        reject("上传失败: " + (err.errMsg || JSON.stringify(err)));
                    }
                });

                // 监听上传进度
                uploadTask.onProgressUpdate((res) => {
                    // 查找当前正在上传的文件
                    const index = this.fileList.findIndex(file => file.status == 'uploading');
                    if (index != -1) {
                        // 更新上传进度信息
                        this.fileList[index].message = '上传中 ' + res.progress + '%';
                    }
                });
            })
        },
        formatDate(dateStr) {
            if (!dateStr) return '';
            let date = new Date(dateStr);
            let year = date.getFullYear();
            let month = (date.getMonth() + 1).toString().padStart(2, '0');
            let day = date.getDate().toString().padStart(2, '0');
            return `${year}-${month}-${day}`;
        },
        afterRead(event) {
            // 读取文件后的处理
            const { file } = event

            // 处理文件数组
            const fileList = Array.isArray(file) ? file : [file]

            // 遍历处理每个文件
            fileList.forEach(item => {
                // 更新UI显示上传中状态
                const fileListItem = {
                    ...item,
                    status: 'uploading',
                    message: '上传中'
                }
                this.fileList.push(fileListItem)
                const currentIndex = this.fileList.length - 1

                // 使用Promise上传图片
                this.uploadFilePromise(item.url)
                    .then(url => {
                        // 上传成功，更新状态和URL
                        this.fileList[currentIndex].status = 'success'
                        this.fileList[currentIndex].message = '上传成功'
                        this.fileList[currentIndex].url = url
                        // 保存上传后的URL
                        this.formData.proveImage.push(url)
                    })
                    .catch(err => {
                        // 上传失败
                        this.fileList[currentIndex].status = 'failed'
                        this.fileList[currentIndex].message = '上传失败'

                        uni.showToast({
                            title: '图片上传失败',
                            icon: 'none'
                        })
                    })
            })
        },
        deletePic(event) {
            // 删除图片
            const index = event.index
            this.fileList.splice(index, 1)
            this.formData.proveImage.splice(index, 1)
        },
        submitTaskHandler() {
            // 表单验证
            if (!this.formData.proveTxt) {
                uni.showToast({
                    title: '请输入笔记链接',
                    icon: 'none'
                })
                return
            }

            if (this.formData.proveImage.length == 0) {
                uni.showToast({
                    title: '请上传至少一张截图',
                    icon: 'none'
                })
                return
            }

            // 检查是否有正在上传的图片
            const isUploading = this.fileList.some(file => file.status == 'uploading')
            if (isUploading) {
                uni.showToast({
                    title: '图片正在上传中，请稍候',
                    icon: 'none'
                })
                return
            }

            // 显示提交中提示
            uni.showLoading({
                title: '提交中...'
            })

            // 提交任务
            submitTask({
                id: this.taskId,
                taskId: this.formData.taskId,
                proveTxt: this.formData.proveTxt,
                proveImage: this.formData.proveImage.join(',')
            }).then(res => {
                uni.hideLoading()
                if (res && res.code == 200) {
                    uni.showToast({
                        title: '提交成功',
                        icon: 'success'
                    })
                    // 返回任务详情页
                    setTimeout(() => {
                        uni.navigateBack()
                    }, 1500)
                } else {
                    uni.showToast({
                        title: res.msg || '提交失败',
                        icon: 'none'
                    })
                }
            }).catch(err => {
                uni.hideLoading()
                uni.showToast({
                    title: '提交失败',
                    icon: 'none'
                })
                console.error('提交任务失败:', err)
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.task-upload {
    padding: 20rpx;
    background-color: #f5f5f5;
    min-height: 100vh;

    .status-box {
        margin-bottom: 20rpx;
    }

    .reject-box {
        background-color: #fff2e8;
        border-radius: 10rpx;
        padding: 20rpx 30rpx;
        margin-bottom: 20rpx;
        display: flex;
        align-items: center;

        .reject-icon {
            font-size: 32rpx;
            color: #ff8800;
            margin-right: 15rpx;
            font-weight: bold;
        }

        .reject-content {
            flex: 1;
        }

        .reject-title {
            font-size: 28rpx;
            color: #ff8800;
            font-weight: 500;
        }
    }

    .reviewing-box {
        background-color: #fff7e6;
        border-radius: 10rpx;
        padding: 20rpx 30rpx;
        margin-bottom: 20rpx;
        display: flex;
        align-items: center;

        .reviewing-icon {
            font-size: 32rpx;
            color: #fa8c16;
            margin-right: 15rpx;
            font-weight: bold;
        }

        .reviewing-content {
            flex: 1;
        }

        .reviewing-title {
            font-size: 28rpx;
            color: #fa8c16;
            font-weight: 500;
        }
    }

    .approved-box {
        background-color: #f6ffed;
        border-radius: 10rpx;
        padding: 20rpx 30rpx;
        margin-bottom: 20rpx;
        display: flex;
        align-items: center;

        .approved-icon {
            font-size: 32rpx;
            color: #52c41a;
            margin-right: 15rpx;
            font-weight: bold;
        }

        .approved-content {
            flex: 1;
        }

        .approved-title {
            font-size: 28rpx;
            color: #52c41a;
            font-weight: 500;
        }
    }

    .upload-form {
        border-radius: 10rpx;
        padding: 10rpx;

        .form-item {
            margin-bottom: 40rpx;
            background-color: #fff;
            padding: 30rpx;
            border-radius: 10rpx;


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

            .form-label {
                font-size: 28rpx;
                color: #333;
                font-weight: 500;
                margin-bottom: 20rpx;
                position: relative;

                &::before {
                    content: '';
                    width: 6rpx;
                    height: 28rpx;
                    background-color: #ff8800;
                    position: absolute;
                    left: -20rpx;
                    top: 50%;
                    transform: translateY(-50%);
                    border-radius: 3rpx;
                }
            }

            .form-input {
                margin-bottom: 10rpx;
            }

            .upload-box {
                margin-top: 20rpx;
            }
        }

        .submit-btn {
            margin-top: 60rpx;
            padding: 0 40rpx;
        }
    }
}
</style>