<template>
	<view class="page">
		<view class="periodDate">
			<text>服务日期：{{periodDate.label}}</text>
		</view>

		<view class="flex-col group">
			<view class="serob"><text>服务对象</text></view>
			<u-grid :border="false" col="4">
				<u-grid-item v-for="(item,index) in serviceObjectList" :key="index">
					<view class="serobItem flex-col" >
						<view class="serobImgView" @click="selectServiceObject(item)">
							<image class="serobImg" mode="aspectFill" :src="item.facePhotoUrl || '/static/me/ud4.png'"></image>
						</view>
						<text class="serobName">{{item.nickName || '未填写'}}</text>
						<view class="serobV" v-if="item.select === true">
							<image class="serobVicon" src="/static/order/ud20.png"></image>
						</view>
					</view>
				</u-grid-item>
			</u-grid>
		</view>

		<view class="flex-col group " v-for="(item, index) in orderParam.childService">
			<view class="flex-row " >
				<image class="selectSerobImg" mode="aspectFill" :src="item.facePhotoUrl || '/static/me/ud4.png'"></image>
				<text class="selectSerobName">{{item.nickName || '未填写'}}</text>
			</view>
			<view class="serob">
				<text>服务人员</text>
			</view>
			<view>
				<u-grid col="4">
					<u-grid-item  v-for="(item1,index1) in item.serviceTeacherList" :key="index1">
						<view class="serobItem flex-col"  @click="selectServiceTeach(item.serviceTeacherList,index,index1)">
							<view class="serobImgView">
								<image class="serobImg" mode="aspectFill" :src="item1.facePhotoUrl || '/static/me/ud4.png'"></image>
							</view>
							<text class="serobName ">{{item1.personName || '未填写'}}</text>
							<view class="flex-row justify-center ">
								<u-icon name="rmb-circle" size="14"></u-icon>
								<text class="teachPrice">￥{{item1.fee}}</text>
							</view>
							<view class="serobV " v-if="item1.select">

								<image class="serobVicon" src="/static/order/ud20.png"></image>
							</view>
						</view>
					</u-grid-item>
				</u-grid>
			</view>
			<view class="serob" :style="{'marginTop':'32rpx'}">
				<text>服务时段</text>
			</view>
			<view>
				<u-grid :border="false" col="5">
					<u-grid-item v-if="item2.total > 0"  v-for="(item2,index2) in item.serviceTimeList" :key="index2">
						<view class="flex-col justify-center timeItem " :class="{selectBack: item2.select}" @click="selectServiceTime(item.serviceTimeList,index,index2)">
							<view class="flex-row justify-center">
								<text class="time">{{item2.label}}</text>
							</view>
							<view class="flex-row justify-center">
								<text class="price">￥{{item2.price}}</text>
							</view>
						</view>
					</u-grid-item>
				</u-grid>
			</view>
		</view>


		<view class="flex-col group ">
			<view class="groupItemKey">
				<text>服务定制</text>
			</view>
			<view class="textareaView">
				<textarea v-model="orderParam.remark" placeholder-style="color:#999999;fontSize:28rpx"
					placeholder="如有其它特殊需求，请在此输入您的需求" />
			</view>
		</view>

		<view :style="{'height':'236rpx'}"></view>

		<view class="flex-col  group2 ">
			<view class="btnTitle flex-row">
				<u-icon v-if="selectIcon" name="checkmark-circle-fill" color="#FFE52C" size="18"
					@click="selectChange"></u-icon>
				<u-icon v-else name="/static/order/ud9.png" color="#FFE52C" size="18" @click="selectChange"></u-icon>
				<text :style="{'margin-left':'10rpx'}">请阅读并同意</text>
				<text :style="{'color':'red'}" @click="goTermsOfService">《预约需知》</text>
			</view>
			<view class="btn flex-row justify-between">
				<view>
					<text class="title">待支付</text>
					<text class="num">￥{{price}}</text>
				</view>
				<view class="btnRight" @click="commitOrder">
					<text>提交</text>
				</view>
			</view>
		</view>
		<myPay ref="myPay" :blPay="false" :orderNo="subOrderNo" @payResult="payResult"></myPay>
	</view>
</template>

<script>
	import myPay from '../../components/pay/pay';
	export default {
		components: {
			myPay
		},
		data() {
			return {
				//服务对象列表
				serviceObjectList:[],
				//服务人员列表
				serviceTeacherList:[],
				userInfo: {},
				//服务门店
				store: {},
				//默认服务时间
				periodDate: [],
				//预约费用
				price: '0',
				//订单编号
				subOrderNo:'',
				selectIcon: true,
				orderParam:{
					orderType: 1,
					serviceAttribute: 2,
					serviceStoreId: '',
					remark: '',
					serviceDate:'',
					childService:[
						// 	{
						// 		serviceObjectId: '',
						// 		facePhotoUrl:'', //回显需要，不做参数
						// 		nickName:'', //回显需要，不做参数
						// 		serviceUserId: '',
						// 		personName:'',//回显需要，不做参数
						// 		fee:'',//回显需要，不做参数
						// 		serviceStartTime: '',
						// 		serviceTeacherList:[],//服务人员列表,回显需要，不做参数
						// 		serviceTimeList:[]//服务时段列表,回显需要，不做参数
						// }
					]
				}
			}
		},
		onLoad() {
			this.store = uni.getStorageSync('storeInfo')
			this.userInfo = uni.getStorageSync('userInfo')
			this.orderParam.serviceStoreId = this.store.storeId
			//获取排班日期
			this.selectDate()

		},
		onShow() {

		},
		mounted(){




		},
		methods: {
			//获取排班日期
			selectDate() {
				console.log(this.store)
				this.$api.selectDate({
					organization: this.store.storeId
				}).then(res => {
					this.periodDate = res.data.data[0]
					this.orderParam.serviceDate=this.periodDate.label
					this.getServicePerson(this.periodDate.label)
				})
			},

			// 查询服务工作人员列表
			getServicePerson(date) {
				this.$api.getServicePerson({
					storeId:this.store.storeId,
					date:date
				}).then((res) => {
					this.serviceTeacherList = res.data.data;
					this.serviceTeacherList[0].select = true
					this.getServicePersonUrl(this.serviceTeacherList);
					this.listServiceObject()

				})
			},
			getServicePersonUrl(items){
				for (let i = 0; i < items.length; i++) {
					if (items[i].facePhoto) {
						this.$api.getImgUrlByOssId({
							ossId: items[i].facePhoto
						}).then(res => {
							items[i].facePhotoUrl = res.data.data[0].url.replace(/^http:/, "https:")
							this.$set(this.serviceTeacherList, i, items[i])
						})
					}
				}
			},


			// 查询服务对象信息列表
			listServiceObject() {
				this.$api.listServiceObject(this.reqParm).then((res) => {
					console.log(res)
					this.serviceObjectList = res.data.data
					this.getServiceObjectUrl(this.serviceObjectList);

				})
			},
			// 获取图片
			getServiceObjectUrl(items) {
				for (let i = 0; i < items.length; i++) {
					if (items[i].facePhoto) {
						this.$api.getImgUrlByOssId({
							ossId: items[i].facePhoto
						}).then(res => {
							items[i].facePhotoUrl = res.data.data[0].url.replace(/^http:/, "https:")
							this.$set(this.serviceObjectList, i, items[i])
							if (i === 0){
								this.selectServiceObject(items[i])
							}
						})
					}
				}
			},

			selectServiceObject(item) {
				if (!this.serviceTeacherList || this.serviceTeacherList.length==0){
					uni.showToast({
						icon: 'none',
						duration: 2000,
						title: '暂无可预约排班'
					});
					return
				}
				if (item.select) {
					this.orderParam.childService = this.orderParam.childService.filter(selectServiceObject =>
						selectServiceObject.serviceObjectId !== item.id)
				} else {

					this.$api.getServicePersonTime({
						personId: this.serviceTeacherList[0].personId,
						date: this.periodDate.label,
						storeId:this.store.storeId
					}).then(res => {
						if (!res.data.data || res.data.data.length==0){
							uni.showToast({
								icon: 'none',
								duration: 2000,
								title: '暂无可预约排班'
							});
							return
						}
						item.select = !item.select
						let periodTimeList = res.data.data
						let selectServiceObjectList = this.orderParam.childService


						//选择服务对象时，获取的排班时间为全部技师的排班时间，所以只要某个时段被选过，那么这个时段的数量-1
						selectServiceObjectList.forEach(selectServiceObject =>{
							periodTimeList.forEach(periodTime =>{
								if (selectServiceObject.serviceStartTime === periodTime.label ){
									periodTime.total = periodTime.total - 1
								}
							})
						})


						let date = null //系统为当前服务对象分配的时间

						for (const time of periodTimeList) {
							if (time.total>0){
								time.select = true
								date = time
								//为当前服务对象分配时间段成功时，需要将以前的服务对象的可选择的时间段的total -1
								selectServiceObjectList.forEach(selectServiceObject =>{

									if (selectServiceObject.serviceUserId === -1){
										//如果子订单没有指定技师，则对应的时段-1
										selectServiceObject.serviceTimeList.forEach(t=>{
											if (t.label == date.label){
												t.total = t.total -1
											}
										})

									}else {
										selectServiceObject.serviceTimeList.forEach(t=>{
											//如果子订单指定技师，且该技师的服务时段未被选中，则对应的时段-1
											if (t.label == date.label && !t.select){
												t.total = t.total -1
											}
										})
									}

								})
								break
							}
						}
						console.log(periodTimeList)
						//这里只为了断开技师列表的应用关系
						let serviceTeacherListStr = JSON.stringify(this.serviceTeacherList)
						let serviceTeacherList = JSON.parse(serviceTeacherListStr)
						//创建子订单项
						let childService ={
							serviceObjectId: item.id,
							facePhotoUrl:item.facePhotoUrl, //回显需要，不做参数
							nickName:item.nickName, //回显需要，不做参数
							serviceUserId: serviceTeacherList[0].personId,
							fee:serviceTeacherList[0].fee,//回显需要，不做参数
							serviceStartTime: date.label,
							serviceTeacherList:serviceTeacherList,//服务人员列表,回显需要，不做参数
							serviceTimeList:periodTimeList//服务时段列表,回显需要，不做参数
						}
						this.orderParam.childService.push(childService)

					})

				}

				this.price = 0
				for (let childService of this.orderParam.childService) {
					this.price =  this.price * 1 + childService.fee * 1
					this.price = this.price.toFixed(2)
				}
			},


			selectServiceTeach(items,index,index1){
				items.forEach(e=>{
					e.select=false
				})
				items[index1].select =true
				this.orderParam.childService[index].fee = items[index1].fee
				this.orderParam.childService[index].serviceUserId = items[index1].personId
				this.$api.getServicePersonTime({
					personId: items[index1].personId,
					date: this.periodDate.label,
					storeId:this.store.storeId
				}).then(res => {
					let serviceTimeList = res.data.data
					let selectServiceObjectList = this.orderParam.childService.filter(selectServiceObject =>
							(selectServiceObject.serviceUserId === items[index1].personId
							&& selectServiceObject.serviceObjectId !== this.orderParam.childService[index].serviceObjectId)
							|| selectServiceObject.serviceUserId === -1
					)
					selectServiceObjectList.forEach(selectServiceObject =>{
						serviceTimeList.forEach(periodTime =>{
							if (selectServiceObject.serviceStartTime === periodTime.label ){
								if (selectServiceObject.serviceUserId === -1){
									selectServiceObject.serviceTimeList.forEach(t=>{
										if (t.label == periodTime.label && t.total === 1){
											periodTime.total = periodTime.total - 1
										}
									})
								}else {
									periodTime.total = periodTime.total - 1
								}
							}
						})
					})
					for (const time of serviceTimeList) {
						if (time.total>0){
							time.select = true
							break
						}
					}
					serviceTimeList[0].select = true
					this.orderParam.childService[index].serviceStartTime= serviceTimeList[0].label,
					this.orderParam.childService[index].serviceTimeList= serviceTimeList
				})
				this.price = 0
				for (let childService of this.orderParam.childService) {
					this.price =  this.price * 1 + childService.fee * 1
					this.price = this.price.toFixed(2)
				}

				console.log(this.price)
				this.$forceUpdate()
			},
			selectServiceTime(items,index,index2){
				console.log(items,index,index2)
				items.forEach(e=>{
					e.select=false
				})
				items[index2].select =true // 新选中的时间
				let selectServiceObject = this.orderParam.childService[index] //旧的时间
				this.orderParam.childService.forEach(i=>{
					if (selectServiceObject.serviceUserId === -1){
						i.serviceTimeList.forEach(t=>{
							if (t.label == selectServiceObject.serviceStartTime && !t.select ){
								console.log('-1----------加1')
								t.total +=1
							}
							if (t.label == items[index2].serviceStartTime && i.serviceObjectId != selectServiceObject.serviceObjectId){
								console.log('-1----------减1')
								t.total -=1
							}
						})
					}else {
						if (selectServiceObject.serviceUserId == i.serviceUserId){
							i.serviceTimeList.forEach(t=>{
								if (t.label == selectServiceObject.serviceStartTime && !t.select ){
									t.total +=1
								}
								if (t.label == items[index2].serviceStartTime && i.serviceObjectId != selectServiceObject.serviceObjectId){
									t.total -=1
								}
							})
						}
					}
				})
				this.orderParam.childService[index].serviceStartTime = items[index2].label
				this.$forceUpdate()
			},

			selectChange() {
				this.selectIcon = !this.selectIcon
			},


			goTermsOfService() {
				uni.navigateTo({
					url: '/myPages/TermsOfService/index?name=' + '预约需知' + '&type=' + 5
				})
			},

			//支付组件回调
			payResult(e){
				console.log(e)
				if(e.payResult){
					uni.showToast({
						title: '支付成功!'
					});
				}else {
					uni.showToast({
						title: '支付失败',
						icon: 'error'
					});
				}
				setTimeout(()=>{
					uni.switchTab({
						url: '/pages/order/index'
					})
				},1000)
			},


			//提交订单
			commitOrder() {
				if (this.subOrderNo){
					this.$refs.myPay.openPopup()
				}else {
					if (!this.selectIcon) {
						uni.$u.toast('请阅读并同意《预约需知》')
						return;
					}

					if (this.orderParam.childService.length === 0) {
						uni.$u.toast('请选择服务对象')
						return;
					}
					if (this.requestStatus) {
						return;
					}
					this.requestStatus = true

					this.$api.commonGeneralOrder(this.orderParam).then(res => {
						console.log('++++++++++++++++++订单提交+++++++++++', res)
						if (res.data.data.subOrderNo) {
							this.subOrderNo = res.data.data.subOrderNo
							this.$refs.myPay.openPopup()
						} else {
							uni.$u.toast('预约成功')
							setTimeout(() => {
								uni.switchTab({
									url: '/pages/order/index'
								})
							}, 1000)
						}
						this.requestStatus = false
					}).catch(err => {
						this.requestStatus = false
					})
				}
			},




		}
	}
</script>
<style scoped lang="scss">
	@import './index.rpx.scss';
</style>
