<template>
	<view class="page-evaluate">
		<!-- 头部商品信息 -->
		<view class="card">
			<view class="goods-list">
				<view v-if="order.isPackage!=1" v-for="(item,index) in items" :key="index" class="item">
					<view class="img-box">
						<image :src="JSON.parse(item.jsonInfo).image" mode="aspectFill"></image>
					</view>
					<view class="info-box">
						<view>
							<view class="name-box ellipsis2">
								<view v-if="item.isPrescribe==1" class="tag">处方药</view>{{JSON.parse(item.jsonInfo).productName}}
							</view>
							<view class="spec ellipsis2">{{JSON.parse(item.jsonInfo).sku}}</view>
						</view>
						<view class="price-num">
							<view class="price">
								<text class="unit">¥</text>
								<text class="num">{{JSON.parse(item.jsonInfo).price.toFixed(2)}}</text>
							</view>
							<view class="num">x{{JSON.parse(item.jsonInfo).num}}</view>
						</view>
					</view>
				</view>
				<view  v-if="order.isPackage==1&&order.packageJson!=null"   class="item"  >
					<view class="img-box">
						<image :src="JSON.parse(order.packageJson).imgUrl" mode="aspectFill"></image>
					</view>
					<view class="info-box">
						<view>
							<view class="name-box ellipsis2">
								<view class="tag">套餐</view>{{JSON.parse(order.packageJson).title}}
							</view>
							<view class="spec ellipsis2">{{JSON.parse(order.packageJson).descs}}</view>
						</view>
						 
					</view>
				</view>
			</view>
		</view>
		<view class="card">
			<!-- 表单区 -->
			<u-form ref="form" :model="form" :rules="rules" label-width="140rpx" errorType="toast">
				<!-- 1. 商品打分 -->
				<u-form-item label="商品打分" prop="rating">
					<u-rate v-model="form.rating" :count="5" active-icon="star-fill" inactive-icon="star" size="24"></u-rate>
				</u-form-item>

				<!-- 2. 评价内容 -->
				<u-form-item label="评价内容" prop="content">
					<u-textarea v-model="form.content" placeholder="请分享您的使用感受~" maxlength="200" height="160"
						count></u-textarea>
				</u-form-item>

				<!-- 3. 上传图片 -->
				<u-form-item label="上传图片">
					<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
						:maxCount="6" :previewFullImage="true"></u-upload>
				</u-form-item>

				<!-- 4. 是否匿名 -->
				<u-form-item label="匿名评价">
					<view><checkbox :checked="form.isAnonymous" @click="handleAnonymous()" style="transform: scale(0.7);" /></view>
				</u-form-item>
			</u-form>
		</view>
		<!-- 5. 提交按钮 -->
		<view class="u-p-30">
			<u-button type="primary" shape="circle" @click="submit">提交评价</u-button>
		</view>
	</view>
</template>

<script>
	import {getMyStoreOrderById,addOrderComment} from '@/api/myStoreOrder.js'
	export default {
		data() {
			return {
				form: {
					rating: 5, // 默认 5 星
					content: '',
					isAnonymous: false
				},
				fileList1: [], // 上传组件回显列表
				rules: {
					rating: [{
						type: 'number',
						min: 1,
						required: true,
						message: '请打分',
						trigger: 'change'
					}],
					content: [{
							required: true,
							message: '请输入评价',
							trigger:  ['change','blur']
						},
						{
							min: 5,
							message: '至少 5 个字',
							trigger:  ['change','blur']
						}
					]
				},
				orderId: '',
				order:{},
				items:[],
			}
		},
		onLoad(option) {
			this.orderId = option.orderId
			this.getMyStoreOrderById()
		},
		onReady() {
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			handleAnonymous() {
				this.form.isAnonymous = !this.form.isAnonymous;
			},
			// 选择图片后回调
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: result.status,
						message: result.status == 'failed' ? '上传失败' : '',
						url: result.url
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: uni.getStorageSync('requestPath') +'/app/common/uploadOSS', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						success: (res) => {
							if(res.statusCode == 200&&JSON.parse(res.data).code == 200) {
								resolve({
									url:JSON.parse(res.data).url,
									status: 'success'
								})
							} else {
								resolve({
									url:url,
									status: 'failed'
								})
							}
						},
						fail: (res) => {
							resolve({
								url:url,
								status: 'failed'
							})
						}
					});
				})
			},
			getSuccessUrls(list) {
			  if (!list || list.length === 0) return '';
			
			  const hasUploading = list.some(v => v.status === 'uploading');
			  const hasFailed = list.some(v => v.status === 'failed');
			
			  if (hasUploading) {
			    uni.showToast({ title: '请等待图片上传完成', icon: 'none' });
			    return 'failed';
			  }
			  if (hasFailed) {
			    uni.showToast({ title: '请检查是否有图片上传失败', icon: 'none' });
			    return 'failed';
			  }
			
			  return list.filter(v => v.status === 'success').map(v => v.url).join(',');
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 提交
			submit() {
				this.$refs.form.validate().then(res => {
					if(res) {
						const imgUrls = this.getSuccessUrls(this.fileList1);
						if (imgUrls === 'failed') return;
						
						const params = {
							orderId: this.orderId,
							rating: this.form.rating,
							content: this.form.content.trim(),
							imageUrl: imgUrls,
							isAnonymous: this.form.isAnonymous ? 1 : 0,
							isShow: 1,
							isDel: 0,
							nickName: uni.getStorageSync('nickName'),
							userId: uni.getStorageSync('userId'),
						}
						uni.showLoading({
							title: '提交中'
						})
						addOrderComment(params).then(res=>{
							uni.hideLoading()
							if(res.code == 200) {
								uni.showToast({
									title: '评价成功',
									icon: 'success'
								})
								uni.$emit('refreshOrder')
								setTimeout(() => uni.navigateBack(), 800)
							} else {
								uni.showToast({
									title: res.msg,
									icon: 'success'
								})
							}
						})
					}
				})
			},
			getMyStoreOrderById(){
				var data={orderId:this.orderId};
				getMyStoreOrderById(data).then(res => {
					if(res.code==200){
						 this.order=res.order;
						 this.items=res.items;
					}else{
						uni.showToast({
							icon:'none',
							title: "请求失败",
						});
						 
					}
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.page-evaluate {
		padding: 24rpx;
	}
	.card {
		background: #fff;
		padding: 24rpx;
		border-radius: 16rpx;
		margin-bottom: 20rpx;
	}
	.goods-list{
		padding: 0 30upx;
		background-color: #FFFFFF;
		border-radius: 16upx;
		.item{
			padding: 30upx 0;
			border-bottom: 1px solid #EDEEEF;
			display: flex;
			align-items: center;
			.img-box{
				width: 160upx;
				height: 160upx;
				margin-right: 30upx;
				image{
					width: 100%;
					height: 100%;
				}
			}
			.info-box{
				width: calc(100% - 190upx);
				height: 160upx;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				.name-box{
					font-size: 28upx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #111111;
					line-height: 40upx;
					.tag{
						display: inline-block;
						padding: 0 6upx;
						height: 30upx;
						background: linear-gradient(90deg, #2BC7B9 0%, #2BC7A4 100%);
						border-radius: 4upx;
						margin-right: 10upx;
						font-size: 22upx;
						font-family: PingFang SC;
						font-weight: bold;
						color: #FFFFFF;
						line-height: 30upx;
						float: left;
						margin-top: 7upx;
					}
				}
				.spec{
					margin-top: 18upx;
					font-size: 24upx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #999999;
					line-height: 1;
				}
				.price-num{
					display: flex;
					align-items: center;
					justify-content: space-between;
					.price{
						display: flex;
						align-items: flex-end;
						.unit{
							font-size: 24upx;
							font-family: PingFang SC;
							font-weight: 500;
							color: #111111;
							line-height: 1.2;
							margin-right: 4upx;
						}
						.num{
							font-size: 32upx;
							font-family: PingFang SC;
							font-weight: 500;
							color: #111111;
							line-height: 1;
						}
					}
					.num{
						font-size: 24upx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #999999;
						line-height: 1;
					}
				}
			}
		}
		.sub-total{
			height: 88upx;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			.discount{
				font-size: 24upx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #999999;
				line-height: 1;
				margin-right: 30upx;
			}
			.label{
				font-size: 24upx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #999999;
			}
			.price{
				display: flex;
				align-items: flex-end;
				.unit{
					font-size: 24upx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #FF6633;
					line-height: 1.2;
					margin-right: 4upx;
				}
				.num{
					font-size: 32upx;
					font-family: PingFang SC;
					font-weight: bold;
					color: #FF6633;
					line-height: 1;
				}
			}
		}
	}
</style>