<template>
	<view>
		<!--mine/comments/comments.wxml-->
		<view class="page pdlr20">
			<block v-for="(item, index) in products" :key="index">
				<view class="info bgfff r20 mt20">
					<view class="spinfo dflex">
						<image :src="item.pic" mode="aspectFit"></image>
						<view class="flex">
							<view class="name">{{item.title}}</view>
							<view v-if="item.propertiesList" class="guige dflex">规格：
								<text v-for="(itemGuige, index2) in item.propertiesList" :key="index2" class="guige"
									decode="true">{{itemGuige.value}}&nbsp;
								</text>
							</view>
						</view>
					</view>
					<view class="ping dflex">
						<view>商品评分</view>
						<view class="star dflex">
							<image v-for="(it, idx) in [1, 2, 3, 4, 5]" :key="idx"
								:src="item.score >= it ? '/static/pages/images/star_h.png' : '/static/pages/images/star.png'"
								:data-index="index" :data-idx="idx" @tap="addProScores"></image>
						</view>
						<text
							v-if="item.score > 0">{{item.score == 1 ? '非常差' : item.score == 2 ? '差' : item.score == 3 ? '一般' : item.score == 4 ? '好' : '非常好'}}</text>
					</view>
				</view>
				<view class="con bgfff r20 mt20">
					<view class="tit">产品评价</view>
					<view class="text">
						<textarea @input="textareaInput" :data-index="index" :value="item.evaluateText" maxlength="200"
							name="text"></textarea>
						<view>0/250</view>
					</view>
					<view class="imgbox dflex">
						<view v-for="(it, idx1) in item.buyShow" :key="idx1" class="img">
							<image :src="item.buyShow[idx1]" mode="aspectFit"></image>
							<image src="/mine/static/mine/images/imagecuo.png" class="cuo" @tap="cleanimage"
								:data-index="index" :data-idx="idx1"></image>
						</view>
						<view class="upload" @tap="choiceImages" :data-index="index" v-if="item.buyShow.length<3">
							<image src="/static/pages/images/upload.png"></image>
						</view>
					</view>
				</view>
			</block>
			<view class="pingjia bgfff r20 mt20">
				<view class="ping dflex">
					<view>服务态度</view>
					<view class="star dflex">
						<image v-for="(it, idx) in [1, 2, 3, 4, 5]" :key="idx"
							:src="serviceScore >= it ? '/static/pages/images/star_h.png' : '/static/pages/images/star.png'"
							:data-idx="idx" @tap="addServiceScores"></image>
					</view>
					<text
						v-if="serviceScore > 0">{{serviceScore == 1 ? '非常差' : serviceScore == 2 ? '差' : serviceScore == 3 ? '一般' : serviceScore == 4 ? '好' : '非常好'}}</text>
				</view>
			</view>
		</view>



		<button class="submit" @tap="updateScore" :disabled="isDisabled">{{isDisabled ? '已评价' : '发表评价'}}</button>
		
		<canvas canvas-id="canvas" :style="'width:' + cWidth + 'px;height:' + cHeight +'px;position: absolute;left:-1000px;top:-1000px;'"></canvas>
	</view>
</template>

<script>
	// mine/comments/comments.js
	const app = getApp();
	const req = require("../../utils/request.js");

	export default {
		data() {
			return {
				scoreList: [],
				serviceScore: 0,
				products: "",
				cWidth: 0,
				cHeight: 0
			};
		},

		components: {},
		props: {},
		onLoad: function(options) {
			this.id = options.id;
			let that = this;
			req.getRequest('/api/order/detail', {
				id: this.id
			}, data => {
				let products = [];
				data.products.map(it => {
					it.bindId = it.id;
					it.bindType = 1;
					it.score = 5;
					it.scoreType = 1;
					it.evaluateText = '';
					it.buyShow = [];
					products.push(it);
				});
				that.setData({
					products: products
				});
				// console.log('订单详情', this.products);
			});
		},
		onShow: function() {
			let that = this;
		},
		methods: {
			addProScores(event) {
				const index = event.currentTarget.dataset.index;
				const idx = event.currentTarget.dataset.idx;
				const page = this.products;
				let d = {};
				d['products[' + index + '].score'] = parseInt(idx) + 1;
				this.setData(d);
			},

			textareaInput(event) {
				const index = event.currentTarget.dataset.index;
				let d = {};
				d['products[' + index + '].evaluateText'] = event.detail.value;
				this.setData(d);
			},
			// req.loadIng("上传中");
			// req.uploadFile('/api/upload', allList[count].filePath, res => {
			// 	let avatar = that.products[index].buyShow;
			// 	let d = {};
			// 	d['products[' + index + '].buyShow'] = avatar
			// 		.concat(res.src);
			// 	that.setData(d);
			// 	uni.showToast({
			// 		title: '上传成功',
			// 		icon: 'success',
			// 		duration: 2000
			// 	});
			// })
			//上传图片
		  choiceImages(event) {
			let that = this;
			let index = event.currentTarget.dataset.index;
			let products = that.products[index];
			wx.chooseImage({
			  count: 9,
			  sourceType: ['album', 'camera'],
			  sizeType: ['compressed'],
			  async success(res) {
				console.log(res);
				let list = res.tempFiles;
				console.log(list);
				let allList = [];
				for (let i = 0; i < list.length; i++) {
				  //两M
				  if (list[i].size > 50000) {
					var path = await that.compressImg(list[i].path)
					var data = {
					  formData: {
						flag: 726
					  },
					  filePath: path,
					  name: 'file'
					}
					allList.push(data);
				  } else {
					var data = {
					  formData: {
						flag: 722
					  },
					  filePath: list[i].path,
					  name: 'file'
					}
					allList.push(data);
				  }
				}
				console.log(allList)
				let successUp = 0;
				let failUp = 0;
				let count = 0
				// 多图上传 allList:图片数组 successUp：上传成功次数 现在上传的下标
				that.uploadImgs(allList, successUp, failUp, count,products,index);
			  },
			  fail(err) {}
			})
		  },
		  //通过canvans缩放长宽来压缩图片 path:图片本地路径  limitNum：压缩到长宽多大
		  async compressImg(path, multiple = 2, limitNum = 600) {
			console.log('图片链接',path)
			let that = this;
			return new Promise((resolve, reject) => {
			  wx.getImageInfo({
				src: path,
				success(res) {
				  var canvasWidth = res.width //图片原始长宽
				  var canvasHeight = res.height
				  console.log('图片的基本信息', res)
				  // while循环 保证宽高在100以内 Math.trunc()去掉小数点右边数
				  while (canvasWidth > limitNum || canvasHeight > limitNum) {
					canvasWidth = Math.trunc(res.width / multiple)
					canvasHeight = Math.trunc(res.height / multiple)
					multiple++
				  }
				  //设置画布长宽
				  that.setData({
					cWidth: canvasWidth,
					cHeight: canvasHeight
				  })
				  //----------绘制图形并取出图片路径--------------
				  var ctx = wx.createCanvasContext('canvas')
				  ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight)
				  ctx.draw(false, setTimeout(() => {
					wx.canvasToTempFilePath({
					  canvasId: 'canvas',
					  destWidth: canvasWidth,
					  destHeight: canvasHeight,
					  success: function (res) {
						console.log(res.tempFilePath) //图片路径
						resolve(res.tempFilePath)
					  },
					  fail: function (res) {
						console.log(res.errMsg)
					  }
					})
				  }, 100))
				},
				fail: function (res) {
				  console.log(res.errMsg)
				},
			  })
			})
		  },
		  //多张图片上传
		  uploadImgs: function (allList, successUp, failUp, count,products,index) {
			console.log(allList, successUp, failUp, count)
			let that = this;
			let length = allList.length; //总共上传的数量
			let releaseImageList = products;
			var promise = Promise.all(allList.map(tempFilePath => {
				return new Promise(function(resolve, reject) {
					req.loadIng("上传中");
					req.uploadFile('/api/upload', tempFilePath.filePath, res => {
						// console.log(res)
						let avatar = that.products[index].buyShow;
						let d = {};
						d['products[' + index + '].buyShow'] = avatar
							.concat(res.src);
						that.setData(d);
						uni.showToast({
							title: '上传成功',
							icon: 'success',
							duration: 2000
						});
					});
				});
			}));
			promise.then(function(results) {
				// console.log(results);
			}).catch(function(err) {
				// console.log(err);
			});
			
		  },
			uploadImg(event) {
				let that = this;
				let index = event.currentTarget.dataset.index;
				let products = that.products[index];
				uni.chooseImage({
					count: products.buyShow.length - 3,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					crop: {
						quality: 40
					},
					success: function({
						tempFilePaths
					}) {
						var promise = Promise.all(tempFilePaths.map(tempFilePath => {
							return new Promise(function(resolve, reject) {
								req.loadIng("上传中");
								req.uploadFile('/api/upload', tempFilePath, res => {
									// console.log(res)
									let avatar = that.products[index].buyShow;
									let d = {};
									d['products[' + index + '].buyShow'] = avatar
										.concat(res.src);
									that.setData(d);
									uni.showToast({
										title: '上传成功',
										icon: 'success',
										duration: 2000
									});
								});
							});
						}));
						promise.then(function(results) {
							// console.log(results);
						}).catch(function(err) {
							// console.log(err);
						});
					}
				});
			},

			// 删除图片
			cleanimage(event) {
				let index = event.currentTarget.dataset.index;
				let idx = event.currentTarget.dataset.idx;
				let arr = this.products[index].buyShow;
				arr.splice(idx, 1);
				this.setData({
					['products[' + index + '].buyShow']: arr
				});
			},

			addServiceScores(event) {
				const index = event.currentTarget.dataset.idx;
				this.setData({
					serviceScore: parseInt(index) + 1
				});
			},

			updateScore() {
				if (this.serviceScore == 0) return req.msg('请对服务态度进行评分');
				let borrow = {
					uid: req.getStorage('userInfo').id,
					orderId: this.id,
					isOpen: 1
				};
				let scoreList = this.scoreList;
				let products = this.products;
				products.map(item => {
					scoreList = scoreList.concat({
						bindId: item.id,
						bindType: item.bindType,
						score: item.score,
						scoreType: item.scoreType,
						evaluateText: item.evaluateText,
						buyShow: item.buyShow.length > 0 ? item.buyShow.join(',') : ''
					});
				});
				scoreList = scoreList.concat({
					bindId: this.id,
					bindType: 5,
					score: this.serviceScore,
					scoreType: 3,
					evaluateText: '',
					buyShow: ''
				});
				borrow.scoreList = JSON.stringify(scoreList);
				// console.log(scoreList);
				req.postRequest('/api/sysScore/save', borrow, () => {
					req.msg('评分成功', () => {
						uni.navigateBack();
					});
				});
			}

		}
	};
</script>
<style>
	@import "./comments.css";
</style>
