<template>
	<view class="container">
		<view class="form-item top_item" @click="navTo">
			<text>我的咨询投诉</text>
			<u-icon name="arrow-right" color="#333" size="20"></u-icon>
		</view>
		<u-form labelPosition="top" labelWidth='0' :model="formdata" :rules="rules" ref="uForm" errorType="toast">
			<u-form-item label=" " prop="complaintType">
				<view class="form-item">
					<view class="form-item-title">投诉方式</view>
					<view class="tagbox">
						<view :class="formdata.complaintType == 1?'tagitem active':'tagitem'"
							@click="formdata.complaintType = 1">咨询</view>
						<view :class="formdata.complaintType == 2?'tagitem active':'tagitem'"
							@click="formdata.complaintType = 2">投诉/举报</view>
					</view>
				</view>
			</u-form-item>
			<u-form-item label=" " prop="type">
				<view class="form-item">
					<view class="form-item-title">投诉类型</view>
					<view class="tagbox">
						<view :class="formdata.type == 1?'tagitem active':'tagitem'" @click="formdata.type = 1">店铺
						</view>
						<view :class="formdata.type == 2?'tagitem active':'tagitem'" @click="formdata.type = 2">商品
						</view>
						<view v-if="formdata.complaintType == 1" :class="formdata.type == 0?'tagitem active':'tagitem'" @click="formdata.type = 0">其他
						</view>
					</view>
				</view>
			</u-form-item>
			<u-form-item label=" " v-if="formdata.type == 1">
				<view class="form-item" @click="openStore">
					<view class="form-item-title x-bc">
						<text>选择店铺</text>
						<u-icon name="arrow-right" color="#333" size="18"></u-icon>
					</view>
					<view class="storename x-bc">
						<text>{{storeId? storeName : "选择店铺"}}</text>
					</view>
				</view>
			</u-form-item>
			<u-form-item label=" " v-if="formdata.complaintType == 2&&formdata.type == 2">
				<view class="form-item">
					<view class="form-item-title x-bc" @click="openOrder">
						<text> 选择订单商品</text>
						<u-icon name="arrow-right" color="#333" size="18"></u-icon>
					</view>
					<view class="orderbox chooseorder" v-show="item&&JSON.stringify(item)!='{}'">
						<view class="item" >
							<!-- 订单号，状态 -->
							<view class="ordersn-box">
								<view class="num">订单号：{{item.orderCode}}</view>
								<!-- <view class="status-box">
									<text   class="text success">
										{{$getDictLabelName("storeOrderStatus",item.status)}}
									</text>
								</view> -->
							</view>
							<!-- 药品列表 -->
							<view  class="drug-list"  >
								<view v-if="item.isPackage!=1" v-for="(subItem,subIndex) in item.items" :key="subIndex" class="drug-item" >
									<view class="x-f">
										<checkbox :value="subItem.checked" :checked="subItem.checked" @click="checkShopChange(subItem)" />
										<view class="img-box">
											<image :src="JSON.parse(subItem.jsonInfo).image" mode="aspectFill"></image>
										</view>
									</view>
									<view class="drug-info"  >
										<view>
											<view class="name-box ellipsis2">
												<view v-if="subItem.isPrescribe==1" class="tag">处方药</view>{{JSON.parse(subItem.jsonInfo).productName}}
											</view>
											<view class="spec ellipsis2">{{JSON.parse(subItem.jsonInfo).sku}}</view>
										</view>
										<view class="num-box">
											<view class="price">
												<text class="unit">¥</text>
												<text class="num">{{JSON.parse(subItem.jsonInfo).price.toFixed(2)}}</text>
											</view>
											<view class="amount">x{{JSON.parse(subItem.jsonInfo).num}}</view>
										</view>
									</view>
								</view>
								<view v-if="item.isPackage==1&&item.packageJson!=null" class="drug-item" >
									<view class="img-box">
										<image :src="JSON.parse(item.packageJson).imgUrl" mode="aspectFill"></image>
									</view>
									<view class="drug-info"  >
										<view>
											<view class="name-box ellipsis2">
												<view class="tag">套餐</view>{{JSON.parse(item.packageJson).title}}
											</view>
											<view class="spec ellipsis2">{{JSON.parse(item.packageJson).descs}}</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</u-form-item>
			<u-form-item label=" " prop="title">
				<view class="form-item">
					<view class="form-item-title">标题</view>
					<u--input v-model="formdata.title" placeholder="请输入标题" maxlength='100'></u--input>
				</view>
			</u-form-item>
			<u-form-item label=" " prop="content">
				<view class="form-item">
					<view class="form-item-title">内容</view>
					<u--textarea v-model="formdata.content" placeholder="请详细描述您遇到的问题，我们会认真处理您的问题" count
						maxlength='200'></u--textarea>
				</view>
			</u-form-item>
			<u-form-item label=" " prop="images">
				<view class="form-item">
					<view class="form-item-title">上传凭证</view>
					<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1"
						:maxCount="4"></u-upload>
				</view>
			</u-form-item>
		</u-form>
		<view class="btn-box">
			<view class="sub-btn" @click="submit()">提交</view>
		</view>
		<u-popup :show="show" :closeable="true" @close="close">
			<view class="storePop">
				<view class="storePop-title">选择店铺</view>
				<scroll-view class="scroll-list" scroll-y="true" @scrolltolower="lower" >
					<view v-if="storeList.length == 0" class="no-data-box" >
						<image src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/app/newImages/empty_icon.png" mode="aspectFit"></image>
						<view class="empty-title">暂无店铺</view>
					</view>
					<view class="storebox" v-for="(item,index) in storeList" :key="index">
						<image class="logo" :src="item.store.logoUrl" mode="aspectFill"></image>
						<view class="storebox-r">
							<view class="x-bc" style="flex: 1;min-height: 104rpx;">
								<view class="storename ellipsis">{{item.store.storeName || ''}}</view>
								<view class="storebox-btn" @click="handleClick(item,'store')">选择</u-icon></view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
		<u-popup :show="showOrder" :closeable="true" @close="closeOrder">
			<view class="storePop">
				<view class="storePop-title">选择订单</view>
				<scroll-view class="scroll-list" style="height: 80vh" scroll-y="true" @scrolltolower="lowerOrder" >
					<view v-if="orderList.length == 0" class="no-data-box" >
						<image src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/app/newImages/empty_icon.png" mode="aspectFit"></image>
						<view class="empty-title">暂无订单</view>
					</view>
					<view class="item" v-for="(item,index) in orderList" :key="index">
						<!-- 订单号，状态 -->
						<view class="ordersn-box">
							<view class="num">订单号：{{item.orderCode}}</view>
							<view class="storebox-btn" @click="handleClick(item,'order')">选择</u-icon></view>
							<!-- <view class="status-box">
								<text   class="text success">
									{{$getDictLabelName("storeOrderStatus",item.status)}}
								</text>
							</view> -->
						</view>
						<!-- 药品列表 -->
						<view  class="drug-list"  >
							<view v-if="item.isPackage!=1" v-for="(subItem,subIndex) in item.items" :key="subIndex" class="drug-item" >
								<view class="img-box">
									<image :src="JSON.parse(subItem.jsonInfo).image" mode="aspectFill"></image>
								</view>
								<view class="drug-info"  >
									<view>
										<view class="name-box ellipsis2">
											<view v-if="subItem.isPrescribe==1" class="tag">处方药</view>{{JSON.parse(subItem.jsonInfo).productName}}
										</view>
										<view class="spec ellipsis2">{{JSON.parse(subItem.jsonInfo).sku}}</view>
									</view>
									<view class="num-box">
										<view class="price">
											<text class="unit">¥</text>
											<text class="num">{{JSON.parse(subItem.jsonInfo).price.toFixed(2)}}</text>
										</view>
										<view class="amount">x{{JSON.parse(subItem.jsonInfo).num}}</view>
									</view>
								</view>
							</view>
							<view v-if="item.isPackage==1&&item.packageJson!=null" class="drug-item" >
								<view class="img-box">
									<image :src="JSON.parse(item.packageJson).imgUrl" mode="aspectFill"></image>
								</view>
								<view class="drug-info"  >
									<view>
										<view class="name-box ellipsis2">
											<view class="tag">套餐</view>{{JSON.parse(item.packageJson).title}}
										</view>
										<view class="spec ellipsis2">{{JSON.parse(item.packageJson).descs}}</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {getMyStoreOrderList} from '@/api/myStoreOrder.js'
	import {recommendList} from "@/api/index.js"
	import {storeComplaint} from "@/api/user.js"
	export default {
		data() {
			return {
				show: false,
				total: 0,
				pageNum: 1,
				storeId: '',
				storeName: "",
				isLastPage: false,
				storeList: [],
				fileList1: [],
				formdata: {
					title: '',
					type: undefined, //0默认1店铺2商品
					content: '',
					images: '',
					complaintType: '',
				},
				rules: {
					complaintType: [{
						required: true,
						message: '请选择投诉方式'
					}],
					type: [{
						required: true,
						message: '请选择投诉类型'
					}],
					title: [{
						required: true,
						message: '请输入标题'
					}],
					content: [{
						required: true,
						message: '请输入内容'
					}],
					// images: [{
					// 	required: true,
					// 	message: '请上传凭证'
					// }]
				},
				item: {},
				showOrder: false,
				orderList: [],
				orderParamQuery: {
					total: 0,
					pageNum: 1,
					isLastPage: false
				},
				orderInfo: {}
			}
		},
		methods: {
			openStore() {
				this.storeId = ''
				this.storeName = ''
				this.show = true
				this.pageNum = 1
				this.getList()
			},
			close() {
				this.show = false
			},
			lower(event) {
				if(this.total>this.storeList.length){
					this.pageNum++;
					this.getList();
				}
			},
			handleClick(item,type) { 
				if(type=='order') {
					this.showOrder = false
					item.items = item.items.map(it=>({
						...it,
						checked: true
					}))
					this.item = item
					this.orderId = item.id
					console.log("this.item==",this.item)
				} else if(type=='store') {
					this.storeId = item.store.storeId
					this.storeName = item.store.storeName
					this.show = false
				}
			},
			checkShopChange(item) {
				item.checked = !item.checked;
			},
			getList(){
				if(this.isLastPage){
					return;
				}
				const param = {
					pageNum: this.pageNum,
					pageSize: 10
				};
				recommendList(param).then(res => {
					if(res.code==200){
						//设置列表数据
						if (this.pageNum == 1) {
							this.storeList = res.rows; 
						} else {
							this.storeList = this.storeList.concat(res.rows);
						}
						this.total=res.total
						this.isLastPage=this.storeList.length>=res.total
					}else{
						uni.showToast({
							icon:'none',
							title: "请求失败",
						});
					}
				});
			},
			navTo() {
				this.$isLogin().then(
					res => {
						if (res) {
							uni.navigateTo({
								url: '/pages_user/complaintList'
							})
						} else {
							uni.navigateTo({
								url: '/pages/auth/login'
							})
						}
					}
				);
			},
			submit() {
				const images = this.getSuccessUrls(this.fileList1);
				if (images === 'failed') return;
				this.formdata.images = images;
				
				if(this.formdata.complaintType == 2&&!this.formdata.images) {
					uni.showToast({
						title: '请上传凭证',
						icon: 'none'
					})
					return
				}
				if(this.formdata.complaintType == 2&&this.formdata.type == 1&&!this.storeId) {
					uni.showToast({
						title: '请选择店铺',
						icon: 'none'
					})
					return
				}
				let productIds = ''
				if(this.formdata.complaintType == 2&&this.formdata.type == 2) {
					if(this.item==null || JSON.stringify(this.item)=='{}') {
						uni.showToast({
							title: '请选择订单',
							icon: 'none'
						})
						return
					}
					productIds = this.item.items.filter(it => it.checked == true).map(ele=>ele.productId).join(',')
					if(!productIds) {
						uni.showToast({
							title: '请选择商品',
							icon: 'none'
						})
						return
					}
				}
				this.$refs.uForm.validate().then(res => {
					if (res) {
						this.$isLogin().then(res => {
							if (res) {
								this.formdata = {
									...this.formdata,
									storeId: this.storeId || undefined,
									orderId: this.orderId || undefined,
									productIds: productIds || undefined
								}
								storeComplaint(this.formdata).then(res => {
									if (res.code == 200) {
										uni.showModal({
											title: '',
											content: '我们已收到您的反馈，谢谢',
											showCancel: false,
											success: function(res) {
												if (res.confirm) {
													uni.navigateBack()
												} else if (res.cancel) {
													uni.navigateBack()
												}
											}
										});
									} else {
										uni.showToast({
											title: res.msg,
											icon: 'none'
										})
									}
								})
							} else {
								uni.navigateTo({
									url: '/pages/auth/login'
								})
							}
						});
					}
				})

			},
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			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++
				}
			},
			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(',');
			},
			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'
							})
						}
					});
				})
			},
			openOrder() {
				this.showOrder = true
				this.orderParamQuery.pageNum = 1
				this.getOrderList()
			},
			closeOrder() {
				this.showOrder = false
			},
			lowerOrder(event) {
				if(this.orderParamQuery.total>this.orderList.length){
					this.orderParamQuery.pageNum++;
					this.getOrderList();
				}
			},
			getOrderList(){
				if(this.orderParamQuery.isLastPage){
					return;
				}
				const param = {
					pageSize: 10,
					statusList:'3,4',
					page: this.orderParamQuery.pageNum,
				};
				getMyStoreOrderList(param).then(res => {
					if(res.code==200){
						//设置列表数据
						if (this.orderParamQuery.pageNum == 1) {
							this.orderList = res.data.list; 
						} else {
							this.orderList = this.orderList.concat(res.data.list);
						}
						this.orderParamQuery.total=res.data.total
						this.orderParamQuery.isLastPage=res.data.isLastPage
					}else{
						uni.showToast({
							icon:'none',
							title: "请求失败",
						});
					}
				});
			},
		}
	}
</script>

<style scoped lang="scss">
	.container {
		padding: 24rpx;
	}
	.scroll-list {
		height: 60vh;
		padding: 24rpx;
		box-sizing: border-box;
	}
	::v-deep .u-form-item__body {
		padding: 0 !important;
	}
	.chooseorder {
		padding: 0 !important;
		.item {
			padding: 0 !important;
			margin-bottom: 0 !important;
		}
		.ordersn-box {
			padding: 20rpx 0 !important;
		}
	}
	.storePop{
		background-color: #f5f5f5;
		&-title {
			padding: 24rpx;
			text-align: center;
			border-bottom: 1rpx solid #eee;
			background-color: #fff;
		}
		.storebox {
			background-color: #fff;
			padding: 20rpx;
			font-family: PingFang SC;
			color: #333333;
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			overflow: hidden;
			display: flex;
			align-items: flex-start;
			margin-bottom: 24rpx;
			.logo {
				flex-shrink: 0;
				width: 104rpx;
				height: 104rpx;
				background: #fff;
				border-radius: 16rpx 16rpx 16rpx 16rpx;
				border: 1rpx solid #eee;
				margin-right: 16rpx;
				box-sizing: border-box;
			}
			.storename {
				font-weight: 500;
				font-size: 32rpx;
			}
			.storedesc {
				margin-top: 12rpx;
				font-weight: 400;
				font-size: 22rpx;
			}
			.storebox-r {
				flex: 1;
				overflow: hidden;
			}
		}
	}
	.storebox-btn {
		flex-shrink: 0;
		padding: 10rpx 24rpx;
		font-size: 28rpx;
		border-radius: 28rpx 28rpx 28rpx 28rpx;
		border: 2rpx solid #FF5C03;
		font-weight: 500;
		font-size: 24rpx;
		color: #FF5C03;
	}
	.btn-box {
		width: 100%;
		height: 120upx;
		padding: 0 30upx;
		display: flex;
		align-items: center;
		justify-content: center;

		.sub-btn {
			width: 100%;
			height: 88upx;
			line-height: 88upx;
			text-align: center;
			font-size: 30upx;
			font-family: PingFang SC;
			font-weight: bold;
			color: #FFFFFF;
			background: #2583EB;
			border-radius: 44upx;
		}
	}

	.tagbox {
		display: flex;
		align-items: center;
		flex-wrap: wrap;

		.tagitem {
			min-width: 100rpx;
			box-sizing: border-box;
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			font-size: 30rpx;
			padding: 8rpx 12rpx;
			background: #FFF;
			border: 1rpx solid #2583EB;
			color: #2583EB;
			border-radius: 4rpx 4rpx 4rpx 4rpx;
			margin-right: 24rpx;
			text-align: center;
		}

		.active {
			color: #FFFFFF;
			border: 1rpx solid #2583EB;
			background: #2583EB;
		}
	}

	.form-item {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 0 24rpx 24rpx 24rpx;
		margin-bottom: 16rpx;

		&-title {
			font-family: PingFang SC, PingFang SC;
			font-weight: 600;
			font-size: 32rpx;
			color: #222222;
			padding: 24rpx 0;
		}
	}

	.top_item {
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		font-size: 30rpx;
		color: #222222;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 24rpx !important;
	}
	.orderbox{
		padding: 20upx;
	}
	.item{
		background: #FFFFFF;
		border-radius: 16upx;
		padding: 0 30upx;
		margin-bottom: 20upx;
		.ordersn-box{
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 34upx 0 20upx;
			.num{
				font-size: 26upx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #999999;
				line-height: 1;
			}
			.status-box{
				display: flex;
				align-items: center;
				.recom-box{
					width: 108upx;
					height: 30upx;
					line-height: 30upx;
					text-align: left;
					padding-left: 8upx;
					font-size: 22upx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #FFFFFF;
					background-image: url('https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/app/newImages/shopping/recom.png');
					background-repeat: no-repeat;
					background-size: 100% 100%;
					margin-right: 8upx;
				}
				.text{
					font-size: 28upx;
					font-family: PingFang SC;
					font-weight: 500;
					line-height: 1;
					&.success{
						color: #2BC7B9;
					}
					&.black{
						color: #111111;
					}
					&.info{
						color: #999999;
					}
				}
			}
		}
		.drug-list{
			.drug-item{
				padding: 30upx 0;
				border-bottom: 1px soli #F0F0F0;
				display: flex;
				align-items: center;
				.img-box{
					width: 160upx;
					height: 160upx;
					margin-right: 30upx;
					flex-shrink: 0;
					image{
						width: 100%;
						height: 100%;
					}
				}
				.drug-info{
					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{
						font-size: 24upx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #999999;
						line-height: 1;
						margin-top: 10upx;
					}
					.num-box{
						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;
							}
						}
						.amount{
							font-size: 24upx;
							font-family: PingFang SC;
							font-weight: 500;
							color: #999999;
							line-height: 1;
						}
					}
				}
			}
		}
	}
</style>