<template>
	<view class="app-container">
		<view class="status-container">请先联系客服再进行退货操作</view>
		<view class="main-container">
			<view class="goods-container card">
				<view class="title">商品信息</view>
				<block v-for="(item, index) in orderGoodsList" :key='index'>
					<view class="item">
						<view class="check" v-if="item.selected" @tap="selectList(index)"><image src="@/static/icon/select_1.png" mode=""></image></view>
						<view class="check" v-else @tap="selectList(index)"><image src="@/static/icon/select_0.png" mode=""></view>
						<view class="img"><image :src="item.imgUrl" mode="aspectFill"></image></view>
						<view class="right">
							<view class="top">
								<view class="name ellipsis-2">{{item.goodsName}}</view>
								<view class="des">{{item.goodsSpecValue}}</view>
							</view>
							<view class="bottom">
								<view class="price">￥{{item.price | numToFixed}}</view>
								<u-number-box
									v-model="item.num" 
									:min="1" 
									:max="item.oldNum"
									:buttonSize="26" 
									iconStyle="font-size: 12px;">
								</u-number-box>
							</view>
						</view>
					</view>
				</block>
			</view>
			
			<view class="total-container card">
				<view class="top">
					<view class="item">
						<view>商品金额</view>
						<view>￥{{orderDetail.totalProductAmount | numToFixed}}</view>
					</view>
					<view class="item">
						<view>运费</view>
						<view>￥{{orderDetail.freight | numToFixed}}</view>
					</view>
					<view class="item">
						<view>优惠</view>
						<view>-￥{{orderDetail.couponValue | numToFixed}}</view>
					</view>
				</view>
				<view class="bottom">
					<view class="total">付款合计：<text>￥{{orderDetail.payAmount | numToFixed}}</text></view>
					<!-- <view class="total">预计收入：<text>￥{{1 | numToFixed}}</text></view> -->
				</view>
			</view>
			
			<view class="form-container card">
				<view class="title">退货信息填写</view>
				<view class="item">
					<view class="label">请选择类型：</view>
					<view class="radio-group">
						<view class="radio" @tap="returnType = 'REFUND_AMOUNT'">
							<image src="@/static/icon/select_0.png" v-if="returnType == 'REFUND_GOODS'"></image>
							<image src="@/static/icon/select_1.png" v-if="returnType == 'REFUND_AMOUNT'"></image>
							仅退款
						</view>
						<view class="radio" @tap="returnType = 'REFUND_GOODS'" v-if="is_REFUND_GOODS && has_INSTALL_GOODS">
							<image src="@/static/icon/select_1.png" v-if="returnType == 'REFUND_GOODS'"></image>
							<image src="@/static/icon/select_0.png" v-if="returnType == 'REFUND_AMOUNT'"></image>
							退货退款
						</view>
					</view>
				</view>
				<view class="item">
					<view class="label">退换货原因：</view>
					<view class="picker">
						<picker @change="changeReason" :value="reasonIndex" :range="reasonArray">
							<view>{{reasonArray[reasonIndex]}}</view>
						</picker>
					</view>
				</view>
				<view class="item">
					<view class="label">退换货说明：</view>
					<view class="textarea">
						<textarea maxlength="80" placeholder="退换货说明(选填)" v-model="returnExplain" />
					</view>
				</view>
				<view class="item">
					<view class="label">*上传凭证：</view>
					<view class="images">
						<block v-for="(item, index) in images" :key='index'>
							<view class="img">
								<image :src="item.url" mode="aspectFill"></image>
								<text @tap="delImage(index)">x</text>
							</view>
						</block>
						<view class="add"  @tap="addImage" v-if="images.length < 3">
							<image src="@/static/icon/camera.png"></image>
							<text>上传凭证</text>
							<text>(最多3张)</text>
						</view>
					</view>
				</view>
			</view>
			
			<view class="bottom-container">
				<view class="button" @tap="submitApply">提交申请</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { base_url } from '@/utils/config.js';
	
	export default {
		data() {
			return {
				orderId: null, // 订单id
				orderDetail: {}, // 订单详情
				orderGoodsList: [],
				reasonArray: ['7天无理由退货', '与商品信息描述不符', '质量问题', '卖家发错货', '包装/商品破损/污渍', '其它原因'], // 退货原因列表
				reasonIndex: 0, // 退货原因选择值
				images: [], // 凭证
				returnType: 'REFUND_AMOUNT', // 退款类型：REFUND_AMOUNT=仅退款 REFUND_GOODS=退货退款
				returnExplain: '', // 退换货说明
				canClickSave: true, // 能否点击提交
			}
		},
		
		computed: {
			is_REFUND_GOODS() {
				if(this.orderDetail.orderStatus === 'DFH') {
					this.returnType = 'REFUND_AMOUNT';
					return false;
				}
				if(this.orderDetail.orderStatus === 'REFUND' && !this.orderDetail.logisticsNo) {
					this.returnType = 'REFUND_AMOUNT';
					return false;
				}
				
				return true;
			},
			
			has_INSTALL_GOODS() {
				// 只要选中安装产品，就true
				for (let i=0; i<this.orderGoodsList.length; i++) {
					if(this.orderGoodsList[i].selected && this.orderGoodsList[i].workOrderType === 'INSTALL') {
						return true;
						break;
					}
				}
				
				return false;
			}
		},
		
		onLoad({orderId}) {
			this.orderId = orderId;
			this.getOrderDetail();
		},
		
		methods: {
			getOrderDetail() {
				this.$axios({
					url: '/order/detail',
					method: 'get',
					params: {
						orderId: this.orderId
					}
				}).then(res => {
					this.orderDetail = res.data;
					this.orderGoodsList = res.data.orderDetails;
					this.orderGoodsList.forEach((item, index) => {
						item.selected = true;
						item.oldNum = item.num;
					})
				})
			},
			
			selectList(index) {
				this.orderGoodsList[index].selected = !this.orderGoodsList[index].selected;
				
				var ocuritem = this.orderGoodsList.pop();
				this.orderGoodsList.push(ocuritem);
			},
			
			changeReason: function(e) {
				console.log('picker发送选择改变，携带值为', e.target.value)
				this.reasonIndex = e.target.value
			},
			
			// 删除图片
			delImage(index) {
				this.images.splice(index, 1);
			},
			
			// 添加图片
			async addImage() {
				const files = await new Promise((resolve,reject)=>{
					uni.chooseImage({
						count: 3 - this.images.length,
						success:res=>{
							resolve(res.tempFilePaths)
						},fail:err=>{
							reject()
						}
					})
				});
				uni.showLoading({
					title:'上传中'
				})
				let arr = [];
				files.forEach(item=>{
					arr.push(this.uploadFile(item))
				});
				Promise.all(arr).then(res=>{
					this.images = this.images.concat(res.map(item=>{
						return JSON.parse(item).data;
					}))
					console.log(this.images);
				}).catch(err=>{
					uni.showModal({
						title:'上传失败'
					})
				}).finally(()=>{
					uni.hideLoading();
				})
			},
			
			// 上传图片
			async uploadFile(file) {
				const result = new Promise((resolve, reject) => {
					uni.uploadFile({
						url: base_url + '/common/upload',
						header: {
							"Content-Type": 'multipart/form-data',
							"x-token": uni.getStorageSync('token')
						},
						name: 'file',
						filePath: file,
						success(res) {
							resolve(res.data)
						}
					})
				})
				return result;
			},
			
			// 验证数据
			vailateData() {
				let goodsList = [];
				this.orderGoodsList.forEach(item => {
					if(item.selected) {
						goodsList.push(item);
					}
				})
				if(goodsList.length < 1) {
					this.$toast('请选择商品');
					return false;
				}
				
				if(this.images.length < 1) {
					this.$toast('请上传凭证');
					return false;
				}
				return true;
			},
			
			// 提交申请
			submitApply() {
				if (!this.canClickSave) return false;
				this.canClickSave = false;
				setTimeout(() => { this.canClickSave = true }, 3000)
				if(!this.vailateData())return;
				
				let goodsList = [];
				this.orderGoodsList.forEach(item => {
					let obj = {};
					if(item.selected) {
						obj = {
							orderDetailId: item.orderDetailId,
							num: item.num
						}
						goodsList.push(obj);
					}
				})
				
				let imgIds = [];
				this.images.forEach(item => {
					imgIds.push(item.id);
				})
				
				this.$axios({
					url: '/order/refund/apply',
					type: 'application/json',
					params: {
						orderId: this.orderId,
						refundReason: this.reasonArray[this.reasonIndex],
						refundExplain: this.returnExplain,
						refundType: this.returnType,
						imgIds: imgIds,
						refundGoods: goodsList,
					}
				}).then(res => {
					this.$successToast('申请已提交');
					uni.$emit('refreshOrderList', res.data);
					uni.$emit('refreshOrderDetail', res.data);
					setTimeout(() => {
						// uni.navigateBack({
						// 	delta: 1
						// })
						uni.redirectTo({
							url:'/pages/mine/order/return/detail?orderRefundId=' + res.data
						})
					}, 1000)
				})
			},
		}
	}
</script>

<style lang="scss">
	.app-container {
		background: #F4F2F2;
		box-sizing: border-box;
	}
	.status-container {
		background: #FE781F;
		line-height: 80rpx;
		text-align: center;
		font-size: 32rpx;
		color: #FFFFFF;
	}
	.card {
		background: #FFFFFF;
		border-radius: 20rpx;
		margin-bottom: 20rpx;
	}
	.main-container {
		padding: 20rpx 20rpx 120rpx;
	}
	.goods-container {
		padding: 0 20rpx;
		.title {
			font-size: 32rpx;
			color: #333333;
			line-height: 32rpx;
			padding-top: 20rpx;
		}
		.item {
			padding: 20rpx 0;
			border-bottom: 1px solid #eaeaea;
			display: flex;
			justify-content: space-between;
			align-items: center;
			&:last-child {
				border: none;
			}
			.check {
				margin-right: 20rpx;
				image {
					width: 32rpx;
					height: 32rpx;
					display: block;
				}
			}
			.img image {
				width: 180rpx;
				height: 180rpx;
				flex-shrink: 0;
				margin-right: 20rpx;
				display: block;
			}
			.right {
				width: 470rpx;
				height: 180rpx;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				.top {
					.name {
						font-size: 28rpx;
						color: #333333;
						line-height: 36rpx;
					}
					.des {
						font-size: 28rpx;
						color: #999999;
						margin-top: 10rpx;
					}
				}
				.bottom {
					display: flex;
					justify-content: space-between;
					align-items: center;
					.price {
						font-size: 28rpx;
						color: #FF3F42;
						line-height: 28rpx;
					}
				}
			}
		}
	}
	.total-container {
		padding: 0 20rpx;
		font-size: 28rpx;
		color: #333333;
		.top {
			padding: 10rpx 0;
			border-bottom: 1px solid #eaeaea;
		}
		.item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			height: 64rpx;
		}
		.bottom {
			padding: 10rpx 0;
		}
		.total {
			display: flex;
			justify-content: flex-end;
			height: 50rpx;
			align-items: center;
			text {
				color: #FF3F42;
			}
		}
	}
	.form-container {
		padding: 0 20rpx 20rpx;
		.title {
			font-size: 32rpx;
			color: #333333;
			line-height: 32rpx;
			padding-top: 20rpx;
		}
		.item {
			display: flex;
			margin-top: 30rpx;
			.label {
				line-height: 48rpx;
				width: 180rpx;
			}
			.radio-group {
				display: flex;
				height: 48rpx;
				align-items: center;
				.radio {
					display: flex;
					align-items: center;
					margin-right: 40rpx;
					image {
						width: 32rpx;
						height: 32rpx;
						display: block;
						margin-right: 10rpx;
					}
				}
			}
			.picker {
				picker {
					width: 480rpx;
					height: 48rpx;
					line-height: 48rpx;
					border: 1px solid #eaeaea;
					border-radius: 10rpx;
					padding: 0 20rpx;
					box-sizing: border-box;
				}
			}
			.textarea {
				textarea {
					width: 480rpx;
					height: 200rpx;
					border: 1px solid #eaeaea;
					border-radius: 10rpx;
					padding: 10rpx 20rpx;
					box-sizing: border-box;
				}
			}
			.images {
				display: flex;
				.add {
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					width: 146rpx;
					height: 146rpx;
					border: 2rpx dashed #dadada;
					border-radius: 10rpx;
					image {
						width: 48rpx;
						height: 34rpx;
						display: block;
						margin-bottom: 8rpx;
					}
					text {
						font-size: 22rpx;
						color: #999999;
						line-height: 24rpx;
					}
				}
				.img {
					position: relative;
					margin-right: 18rpx;
					&:nth-child(3) {
						margin-right: 0;
					}
					image {
						width: 150rpx;
						height: 150rpx;
						border-radius: 10rpx;
						overflow: hidden;
						display: block;
					}
					text {
						position: absolute;
						right: -10rpx;
						top: -10rpx;
						width: 40rpx;
						height: 40rpx;
						border-radius: 50%;
						background: #FF3F42;
						font-size: 28rpx;
						color: #FFFFFF;
						text-align: center;
						line-height: 36rpx;
						display: block;
					}
				}
			}
		}
	}
	.bottom-container {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		padding: 0 20rpx;
		box-sizing: border-box;
		height: 100rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		background: #FFFFFF;
		border-top: 1px solid #F4F2F2;
		.button {
			width: 100%;
			height: 70rpx;
			line-height: 70rpx;
			text-align: center;
			border-radius: 70rpx;
			background: linear-gradient(-90deg,#ff3f42 0%, #fe781f 100%);
			font-size: 32rpx;
			color: #FFFFFF;
			
		}
	}
</style>
