<template>
	<view class="complaint-submit-page">
		<nav-bar :title="praiseFlag ? '发表评价' : '提交投诉'" color="#000"></nav-bar>

		<view class="page-content">
			<!-- 评价类型切换 -->
			<view class="type-card card-shadow">
				<view class="type-item" :class="{ 'active': !praiseFlag }" @click="praiseFlag = false">
					<view class="icon-wrap bad">
						<text class="type-emoji">{{ !praiseFlag ? '👎' : '👎🏻' }}</text>
					</view>
					<text class="type-text">不赞</text>
					<text class="type-sub" v-if="!praiseFlag">投诉</text>
				</view>
				<view class="type-divider"></view>
				<view class="type-item" :class="{ 'active': praiseFlag }" @click="praiseFlag = true">
					<view class="icon-wrap good">
						<text class="type-emoji">{{ praiseFlag ? '👍' : '👍🏻' }}</text>
					</view>
					<text class="type-text">赞</text>
					<text class="type-sub" v-if="praiseFlag">好评</text>
				</view>
			</view>

			<!-- 内容输入 -->
			<view class="form-section card-shadow">
				<view class="section-title">
					<text class="title-text">{{ praiseFlag ? '评价详情' : '投诉原因' }}</text>
					<text class="title-tip">必填</text>
				</view>
				<textarea class="content-textarea" v-model="reason" 
					:placeholder="praiseFlag ? '请记录您的满意点，帮助履约师提升服务质量...' : '请详细描述您遇到的问题，我们会尽快为您处理...'" 
					maxlength="500"></textarea>
				<view class="word-count">{{ reason.length }}/500</view>
			</view>

			<!-- 图片上传 -->
			<view class="form-section card-shadow">
				<view class="section-title">
					<text class="title-text">凭证图片</text>
					<text class="title-tip gray">最多6张</text>
				</view>
				<view class="upload-grid">
					<view class="upload-item" v-for="(img, index) in imageList" :key="index">
						<image :src="img" mode="aspectFill" @click="previewImage(index)"></image>
						<view class="delete-icon" @click.stop="removeImage(index)">
							<uni-icons type="closeempty" size="12" color="#fff"></uni-icons>
						</view>
					</view>
					<view class="upload-add" v-if="imageList.length < 6" @click="chooseImage">
						<uni-icons type="plusempty" size="32" color="#ccc"></uni-icons>
						<text class="add-text">上传凭证</text>
					</view>
				</view>
			</view>

			<!-- 订单信息提示 -->
			<view class="order-info-bar">
				<text>关联订单：{{ orderCode }}</text>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="bottom-bar">
			<button class="submit-btn" :class="{ 'is-praise': praiseFlag }" @click="handleConfirmSubmit" :loading="submitting">
				{{ praiseFlag ? '确认赞' : '确认不赞' }}
			</button>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import navBar from '@/components/nav-bar/index.vue'
import { addComplaint } from '@/api/fulfiller/complaint'
import { BASE_URL, DEFAULT_HEADERS } from '@/utils/config'

/**
 * 投诉/评价提交页面 (参考网页端设计)
 * @Author: Antigravity
 */

const orderId = ref('')
const orderCode = ref('')
const fulfillerId = ref('')
const praiseFlag = ref(false)
const reason = ref('')
const imageList = ref([])
const submitting = ref(false)

onLoad((options) => {
	if (options.orderId) orderId.value = options.orderId
	if (options.orderCode) orderCode.value = options.orderCode
	if (options.fulfillerId) fulfillerId.value = options.fulfillerId
})

// 选择图片
const chooseImage = () => {
    uni.chooseImage({
        count: 6 - imageList.value.length,
        sizeType: ['compressed'],
        success: (res) => {
            const tempFiles = res.tempFiles
            uploadFiles(tempFiles)
        }
    })
}

// 上传图片到服务器
const uploadFiles = (tempFiles) => {
    uni.showLoading({ title: '上传中...' })
    const token = uni.getStorageSync('token') || ''
    
    const uploadPromises = tempFiles.map(file => {
        return new Promise((resolve, reject) => {
            uni.uploadFile({
                url: BASE_URL + '/resource/oss/upload',
                filePath: file.path,
                name: 'file',
                header: {
                    ...DEFAULT_HEADERS,
                    'Authorization': `Bearer ${token}`
                },
                success: (res) => {
                    const data = JSON.parse(res.data)
                    if (data.code === 200) {
                        resolve(data.data.url)
                    } else {
                        reject(data.msg || '上传失败')
                    }
                },
                fail: (err) => reject('请求失败')
            })
        })
    })

    Promise.all(uploadPromises).then(urls => {
        imageList.value = [...imageList.value, ...urls]
        uni.hideLoading()
    }).catch(err => {
        uni.hideLoading()
        uni.showToast({ title: String(err), icon: 'none' })
    })
}

const previewImage = (index) => {
    uni.previewImage({
        current: index,
        urls: imageList.value
    })
}

const removeImage = (index) => {
    imageList.value.splice(index, 1)
}

const handleConfirmSubmit = async () => {
    if (!reason.value.trim()) {
        uni.showToast({ title: praiseFlag.value ? '请输入评价内容' : '请输入投诉原因', icon: 'none' })
        return
    }
    if (!orderId.value || !fulfillerId.value) {
        uni.showToast({ title: '订单数据不完整，无法提交', icon: 'none' })
        return
    }

    submitting.value = true
    try {
        const payload = {
            orderId: orderId.value,
            fulfiller: fulfillerId.value,
            reason: reason.value,
            photos: imageList.value.join(','),
            praiseFlag: praiseFlag.value
        }
        
        await addComplaint(payload)
        
        uni.showToast({ title: '提交成功', icon: 'success' })
        setTimeout(() => {
            uni.navigateBack()
        }, 1500)
    } catch (error) {
        console.error('提交失败:', error)
        // 500提示已经在全局处理
    } finally {
        submitting.value = false
    }
}
</script>

<style lang="scss" scoped>
.complaint-submit-page {
	min-height: 100vh;
	background-color: #f8f9fb;
}

.page-content {
	padding: 30rpx;
}

.card-shadow {
	background: #fff;
	border-radius: 24rpx;
	box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.02);
	margin-bottom: 30rpx;
}

/* 类型切换卡片 */
.type-card {
	display: flex;
	align-items: center;
	height: 140rpx;
	padding: 0 16rpx;
    .type-item {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 8rpx;
        transition: all 0.3s;
        height: 110rpx;
        border-radius: 20rpx;
        &.active {
            background-color: #f6f6f6;
            .type-text { font-weight: bold; color: #333; font-size: 30rpx; }
            .type-emoji { transform: scale(1.3); }
            .type-sub { opacity: 1; }
        }
        .icon-wrap {
            width: 64rpx; height: 64rpx; border-radius: 50%; display: flex; align-items: center; justify-content: center;
        }
        .icon-wrap.bad { background: rgba(244,67,54,0.08); }
        .icon-wrap.good { background: rgba(76,175,80,0.08); }
        .type-emoji { font-size: 36rpx; line-height: 1; transition: transform 0.3s ease; }
        .type-text { font-size: 28rpx; color: #999; transition: all 0.3s; }
        .type-sub { font-size: 20rpx; color: #bbb; opacity: 0; transition: opacity 0.3s; }
    }
    .type-divider { width: 2rpx; height: 60rpx; background: linear-gradient(180deg, transparent, #EEEEEE, transparent); border-radius: 2rpx; }
}

/* 表单板块 */
.form-section {
	padding: 32rpx;
	.section-title {
		display: flex; align-items: center; gap: 12rpx; margin-bottom: 24rpx;
		.title-text { font-size: 30rpx; font-weight: bold; color: #333; }
		.title-tip { 
            font-size: 20rpx; color: #F44336; background: rgba(244,67,54,0.1); 
            padding: 2rpx 10rpx; border-radius: 4rpx; 
            &.gray { color: #999; background: #f5f5f5; }
        }
	}
	.content-textarea {
		width: 100%; height: 260rpx; font-size: 28rpx; color: #333; line-height: 1.6;
		background-color: #fafafa; border-radius: 16rpx; padding: 20rpx; box-sizing: border-box;
	}
	.word-count { text-align: right; font-size: 22rpx; color: #ccc; margin-top: 12rpx; }
}

/* 图片上传网格 */
.upload-grid {
	display: grid;
	grid-template-columns: repeat(3, 1fr);
	gap: 20rpx;
	.upload-item {
		position: relative; aspect-ratio: 1; border-radius: 12rpx; overflow: hidden;
		image { width: 100%; height: 100%; }
		.delete-icon {
			position: absolute; right: 0; top: 0; width: 36rpx; height: 36rpx;
			background: rgba(0,0,0,0.5); border-bottom-left-radius: 12rpx;
			display: flex; align-items: center; justify-content: center;
		}
	}
	.upload-add {
		aspect-ratio: 1; border-radius: 12rpx; border: 2rpx dashed #EEEEEE;
		display: flex; flex-direction: column; align-items: center; justify-content: center;
		background: #fafafa;
		.add-text { font-size: 22rpx; color: #ccc; margin-top: 8rpx; }
	}
}

.order-info-bar {
	padding: 10rpx 0; font-size: 24rpx; color: #bbb; text-align: center;
}

/* 底部按钮 */
.bottom-bar {
	position: fixed; left: 0; right: 0; bottom: 0;
	background: #fff; padding: 24rpx 40rpx; padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
	box-shadow: 0 -4rpx 16rpx rgba(0,0,0,0.03);
	.submit-btn {
		height: 96rpx; line-height: 96rpx; border-radius: 48rpx; 
		background: #333; color: #fff; font-size: 32rpx; font-weight: bold; border: none;
		transition: all 0.3s;
		&::after { border: none; }
		&.is-praise { background: #FF9500; color: #fff; }
		&:active { transform: scale(0.98); opacity: 0.9; }
	}
}
</style>
