<template>
  <view class="main">	
	<view class="cont">
		<view class="cont_top">
			<view class="cont_top_l">
				<view class="cont_top_text">商品评价 <text class="cont_top_num">{{count}}</text>/{{evalList.length}}</view>
				<view class="cont_top_btn" @click="clickShopeval">一键好评</view>
			</view>
			<view class="cont_top_r">匿名</view>
		</view>
		<template v-for="(item,index) in evalList" :key="index">
			<view class="cont_shop" @click="unfold(item)">
				<view class="cont_shop_l">
					<view class="cont_shop_img">
						<image class="cont_shop_imgUrl" :src="item.image" mode="widthFix"></image>
					</view>
					<view class="cont_shop_x">
						<view class="cont_shop_title"><text>{{item.storeName}}</text></view>
						<view class="cont_shop_type">
							<block v-for="(i,idx) in item.list" :key="idx">
								<view @click.stop="clickEval(item,i)" class="cont_goos" :class="i.checkedShow?'cont_goos_aver':''"><image class="cont_goos_img" :src="i.checkedShow?i.imgUrl_aver:i.imgUrl" mode="widthFix"></image>{{i.name}}</view>
							</block>
						</view>
					</view>
				</view>
			</view>
			<block v-if="item.show">
				<view class="cont_shop_edit">
					<view class="cont_text">
						<image class="cont_text_img" src="../../static/eval/editeval.png"></image>
						<textarea class="cont_textarea" :disable-default-padding="isIos" placeholder="可以从新鲜度、包装等多个角度描述哦～" v-model="item.comment"></textarea>
					</view>
					<view class="cont_ul">
						
						<view class="cont_li" v-for="(img,i) in item.pics" :key="i">
							<view class="cont_upload_remove" @click="delImg(item,i)">
								<image class="cont_upload_remove_img" src="../../static/eval/closeImg.png" mode="widthFix"></image>
							</view>
							<image class="cont_li_img" :src="img" mode="aspectFill" @click="previewImage(item,i)"></image>
						</view>
						
						<view class="cont_li cont_upload" @click="chooseImage(item)" v-if="item.pics.length <= 5">
							<image class="cont_upload_img" src="../../static/eval/adds.png" mode="widthFix"></image>
							<view class="cont_upload_text">添加图片</view>
						</view>
						
					</view>
				</view>
				<view class="cont_shop_border"></view>
			</block>
		</template>
	</view>
	<view class="eval_server">
		<view class="eval_server_text">服务评价</view>
		<view class="eval_server_type">
			<block v-for="(i,index) in server_list" :key="index">
				<view @click="clickServerEval(i)" class="cont_goos" :class="i.checkedShow?'cont_goos_aver':''"><image class="cont_goos_img" :src="i.checkedShow?i.imgUrl_aver:i.imgUrl" mode="widthFix"></image>{{i.name}}</view>
			</block>
		</view>
	</view>
	<view style="height: 300rpx;"></view>
	<view class="footer">
		<view class="footer_btn" :class="count == 0?'opy':''" @click="commentBtn()">提交</view>
	</view>
  </view>
</template>
<script setup>
import { url }  from '@/server/config.js'
import { loads } from '@/utils/index.js'
import { computed,ref,onMounted,onUnmounted,getCurrentInstance,nextTick } from 'vue';
import { useCounterStore } from '@/store/counter'; // 引入 Pinia Store
import { storeToRefs } from 'pinia';//实现解构付值
import { onLoad,onShow,onPullDownRefresh,onPageScroll,onReachBottom,onReady } from "@dcloudio/uni-app"
import { orderReplyproduct,uploadimage,orderReplycomment } from "@/server/api.js"
const counterStore = useCounterStore(); // 使用 Store
const { proxy } = getCurrentInstance();
//使用pinia：storeToRefs方法包裹(保持响应式更新，不使用视图无法更新)
const {statusHeight,headerHeight,statusBartop,token } = storeToRefs(counterStore);
const active = ref(0);
const isIos = ref(false);
const orderNo = ref("");
const evalList = ref([]);
const serviceScore = ref(5);
const server_list = ref([]);
const count = computed(() => {
	const count = evalList.value.filter(item => item.productScore > 0);
	return count.length
});
const System = () =>{
	const phone = wx.getSystemInfoSync();
	if (phone.platform == 'ios') {
	    isIos.value = true
	} else if (phone.platform == 'android') {
	    isIos.value = false
	}
};
const unfold = (e) =>{
	evalList.value.forEach((item,index)=>{
		if(e.id == item.id){item.show = !item.show;}
	})
}
const clickShopeval = () =>{
	let productScore = 0;
	evalList.value.forEach(item=>{
		item.list.forEach(i=>{
			if(i.id == 5){
				i.checkedShow = true
				productScore = 5;
			}
		})
		item.productScore = productScore;
	})
	server_list.value.forEach(item=>{
		if(item.id == 5){
			item.checkedShow = true
			serviceScore.value = item.id;
		}
	})
}
const clickEval = (item,i) =>{
	let productScore = 0;
	evalList.value.forEach(evalList=>{
		if(item.id == evalList.id){
			evalList.list.forEach(item=>{
				if(i.id == item.id){
					item.checkedShow = true;
					productScore = i.id;
				}else{
					item.checkedShow = false;
				}
			})
			if(item.id == evalList.id){
				item.show = true;
				item.productScore = productScore;
			}
		}
	})
}
const clickServerEval = (i) =>{
	let id = 0;
	server_list.value.forEach(item=>{
		if(i.id == item.id){
			item.checkedShow = true;
			id = i.id;
		}else{
			item.checkedShow = false;
		}
	})
	serviceScore.value = id;
}
const api_orderReplyproduct=()=>{
	loads('', true)
	const params = {
		orderNo:orderNo.value
	}
	return orderReplyproduct(params).then(({data}) => {
		uni.hideLoading();
		data.forEach((item,index) => {
			item.id = index+1;
			if(data.length > 1){
				item.show = false;
			}else{
				item.show = true;
			}
			item.comment = "";
			item.pics = [];
			item.productScore = 0;
			item.uploadImg = [];
			item.list = [
				{
				   id:2,
				   imgUrl:'../../static/eval/negative.png',
				   imgUrl_aver:'../../static/eval/negative_aver.png',
				   name:"差评",
				   checkedShow:false
				},
				{
				   id:4,
				   imgUrl:'../../static/eval/ordinary.png',
				   imgUrl_aver:'../../static/eval/ordinary_aver.png',
				   name:"一般",
				   checkedShow:false
				},
				{
				   id:5,
				   imgUrl:'../../static/eval/good.png',
				   imgUrl_aver:'../../static/eval/good_aver.png',
				   name:"好评",
				   checkedShow:false
				}
			]	
		})
		serviceScore.value = 0;
		server_list.value = [
			{
			   id:2,
			   imgUrl:'../../static/eval/negative.png',
			   imgUrl_aver:'../../static/eval/negative_aver.png',
			   name:"差评",
			   checkedShow:false
			},
			{
			   id:3,
			   imgUrl:'../../static/eval/ordinary.png',
			   imgUrl_aver:'../../static/eval/ordinary_aver.png',
			   name:"一般",
			   checkedShow:false
			},
			{
			   id:5,
			   imgUrl:'../../static/eval/good.png',
			   imgUrl_aver:'../../static/eval/good_aver.png',
			   name:"好评",
			   checkedShow:false
			}
		]
		evalList.value = data;
	}).catch(({message}) => {
		uni.hideLoading();
		uni.showModal({
			content:message,
			showCancel: false,
			success: () => {
				uni.navigateBack({
					delta:1
				})
			}
		})
	})
}
//查看上传图片
const previewImage = (item,i)=>{
	let picture = [];
	evalList.value.forEach(list=>{
		if(item.id == list.id){
			picture = item.pics
		}
	})
	uni.previewImage({
	    current: i,
	    urls:picture
	});
}
//删除上传图片
const delImg = (e,i) =>{
	evalList.value.forEach(item=>{
		if(e.id == item.id){
			const pics = item.pics.slice()
			pics.splice(i, 1)
			item.pics = pics;
		}
	})
}
//选择图片
const chooseImage = (e) => {
  uni.chooseImage({
    count: 6, // 最多选择6张
    sizeType: ['original', 'compressed'], // 可选择原图或压缩图
    sourceType: ['album', 'camera'], // 可从相册或相机选择
    success: (res) => {
	  api_uploadimage(res.tempFilePaths,e);
    },
    fail: (err) => {
      console.error('选择图片失败:', err);
    }
  });
}
//接口上传图片拿到图片url
const api_uploadimage = (tempFilePaths,e) =>{
  loads('上传中', true)
  uni.uploadFile({
    url:`${url}/api/front/user/upload/image`, // 替换为你的接口地址
    filePath: tempFilePaths[0], // 图片临时路径
    name: 'multipart', // 后端接收文件的字段名
	header: {
		'Authori-zation':token.value ,// 身份令牌
		'Content-Type': 'multipart/form-data'
	},
    formData: { // 附加的其他参数
      model: 'wechat',
      pid: '8'
    },
    success: (res) => {
	  uni.hideLoading()
      const data = JSON.parse(res.data); // 解析后端返回的数据
	  evalList.value.forEach(item=>{
			if(e.id == item.id){
				item.pics.push(data.data.url);
	  		}
	  })
    },
    fail: (err) => {
	  uni.hideLoading()
      console.error('上传失败:', err);
    }
  })
}
//评论提交
const commentBtn = () => {
	//过滤出选中的对象
	const items = evalList.value.filter(item => item.productScore > 0);
	// 提取 name 和 age 组成新数组
	const request = items.map(item => ({
	  comment: item.comment,
	  pics: item.pics.toString(),
	  productId:item.productId,
	  productScore:item.productScore,
	  serviceScore:serviceScore.value,
	  isPrivacy:0,
	  orderNo:orderNo.value,
	  unique:item.unique
	}));
	if(!request.length){
		uni.showToast({
			title:'您还未评价哦！',
			icon:'error'
		})
		return false
	}
	loads('', true)
	// const params = {request}
	return orderReplycomment(request).then(({message}) => {
		uni.hideLoading();
		uni.showToast({
			title:message,
			icon:'success',
			success: () => {
				setTimeout(()=>{
					uni.redirectTo({
						url:`/order/orderevallist/orderevallist?type=1`
					})
				},1400)
			}
		})
		
	}).catch(({message}) => {
		uni.hideLoading();
		uni.showModal({
			content:message,
			showCancel: false,
			success: () => {
				uni.navigateBack({
					delta:1
				})
			}
		})
	})
}
onLoad((options) => {
	System();
	if(options.orderNo){
		orderNo.value = options.orderNo;
		api_orderReplyproduct();
	}
	
});
onShow(() => {});
onReady(()=>{})
onPullDownRefresh(()=>{})
onReachBottom(()=>{})
</script>

<style lang="scss">
	@import './style.scss';
</style>