<template>
	<view class="page">
<!--		<view class="flex-row periodDate">-->
<!--			<view class="flex-row">-->
<!--				<text>服务日期：</text>-->
<!--			</view>-->
<!--			<picker @change="bindPickerChange" mode='selector' range-key="label" :value="periodDateIndex" :range="periodDateList">-->
<!--				<view class="flex-row justify-between" :style="{width:'550rpx'}">-->
<!--					<text>{{periodDate.label || '请选择服务日期' }}</text>-->
<!--					<u-icon name="arrow-right" color="#666" size="18"></u-icon>-->
<!--				</view>-->
<!--			</picker>-->
<!--		</view>-->

		<view class="dateTabs">
			<u-tabs :list="periodDateList" lineColor="#FFE05C" lineWidth="40" lineHeight="4" :activeStyle="{
            					color: '#FFE05C',
            					fontWeight: 'bold',
            					transform: 'scale(1.05)'
       							 }" @click="clickPeriodDateList"></u-tabs>
		</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 class="serobReminder">-->
<!--				<text>请注意，一人一号</text>-->
<!--			</view>-->
		</view>

		<view class="flex-col group " v-for="(item, index) in orderParam.childService">
			<view class="flex-row " v-if="serviceObjectList.length>1">
				<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 v-if="!item.serviceStartTime" class="noTime flex-row justify-center">
				<text>暂无可用的服务时段</text>
			</view>
			<view v-else>
				<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="timeItemView">
							<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>
						</view>

					</u-grid-item>
				</u-grid>
			</view>
		</view>


		<view class="flex-col group ">
			<view class="groupItemKey">
				<text>取号规则</text>
			</view>
			<view class="textareaView ">
        <view v-for=" (item,index) in takeNumberRules " class="serobReminder">
          <text>{{index+1}}.{{item.dictValue}}。</text>
        </view>
<!--				<textarea v-model="orderParam.remark" placeholder-style="color:#999999;fontSize:28rpx"-->
<!--					placeholder="如有其它特殊需求，请在此输入您的需求" />-->
<!--				<view class="serobReminder">-->
<!--					<text>1.预约需要一人一号。</text>-->
<!--				</view>-->
<!--				<view class="serobReminder">-->
<!--					<text>2.目前支付费用为时段预约占位费。</text>-->
<!--				</view>-->
<!--				<view class="serobReminder">-->
<!--					<text>3.服务费用到店享受相应服务以后在另行收取。</text>-->
<!--				</view>-->
<!--				<view class="serobReminder">-->
<!--					<text>4.到门店先签到，过时没有签到占位时段失效。</text>-->
<!--				</view>-->
			</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="openSetting">
					<text>提交</text>
				</view>
			</view>
		</view>
		<myPay ref="myPay" :blPay="false" :orderNo="subOrderNo" @payResult="payResult" @improperClose="improperClose"></myPay>
	</view>
</template>

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

			this.timeoutId = setTimeout(()=>{
				uni.showModal({
					title:'温馨提示',
					content:'您在下单页面停留太久，请重新进入！',
					showCancel:false,
					success:res=>{
						if (res.confirm){
							uni.switchTab({
								url: '/pages/index/index',
							})
						}
					}
				})
			},1000*60*5)
		},
		onShow() {
			this.userInfo = uni.getStorageSync('userInfo')
      this.getSelectionRules(this.takeNumberData)
		},
		onUnload(){
			clearTimeout(this.timeoutId);
		},
		methods: {

			back(){
				uni.switchTab({
					url: '/pages/index/index',
				})
			},

			clickPeriodDateList(e){
				console.log("666666666666666",e)
				this.periodDateIndex = e.index
				this.periodDate = e
				this.orderParam.serviceDate=this.periodDate.label
				//对所有子订单的服务人员及服务时段重新赋值
				this.getServicePerson(this.periodDate.label,true)
			},

			openSetting(){
				if (!this.userInfo.phone){
					uni.showModal({
						title:'温馨提示',
						content:'预约叫号是通过手机尾号进行查询，是否确认绑定手机号',
						success:res=>{
							if (res.confirm){
								uni.navigateTo({
									url: '/myPages/setting/setting-telphone',
								})
							}
						}
					})
					return
				}
				uni.requestSubscribeMessage({
					tmplIds: this.templateId,
					success: (res) =>{
						let {errMsg,...param} = res
						console.log('+++++++++++++success+++++++++++++',param)
						this.$api.updateSubscribe(param).then(res=>{
							console.log('+++++++++++++updateSubscribe+++++++++++++',res)
						})
					},
					fail:(err)=>{
						console.log('+++++++++++++fail+++++++++++++',err)
					},
					complete:(complete)=>{
						console.log('+++++++++++++complete+++++++++++++',complete)
						this.commitOrder()
					}
				})
			},


			getTemplateList(){
				this.$api.getTemplateList().then(res=>{
					this.templateId=res.data.data.data.map(item=>{
						return item.priTmplId
					})
				})
			},

			improperClose(){
				uni.switchTab({
					url: '/pages/order/index'
				})
			},

			bindPickerChange(e){
				console.log(e)
				if (e.detail.value == this.periodDateIndex){
					return
				}
				console.log('++++++++++++++')
				this.periodDateIndex = e.detail.value
				this.periodDate = this.periodDateList[e.detail.value]
				this.orderParam.serviceDate=this.periodDate.label
				//对所有子订单的服务人员及服务时段重新赋值
				this.getServicePerson(this.periodDate.label,true)

			},
			//获取排班日期
			selectDate() {
				console.log(this.store)
				this.$api.selectDate({
					organization: this.store.storeId
				}).then(res => {
					this.periodDate = res.data.data[0]
					this.periodDateList = res.data.data
					for (const argument of this.periodDateList) {
						let month = argument.label.substring(5,6) == 0 ? argument.label.substring(6,7) : argument.label.substring(5,7)
						let day = argument.label.substring(8,9) == 0 ? argument.label.substring(9,10) : argument.label.substring(8,10)
						argument.name =month + '月' + day +'日'
					}
					this.orderParam.serviceDate=this.periodDate.label
					this.getServicePerson(this.periodDate.label,false)
				})
			},

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

						if (this.orderParam.childService.length === 0){
							this.selectServiceObject(this.serviceObjectList[0])
						}else {
							this.serviceObjectList.forEach(i=>{
								if (i.select){
									this.orderParam.childService=[]
									i.select = false
									this.selectServiceObject(i)
								}
							})
						}

					}else {
						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)
					item.select = !item.select
				} 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
					})
				}
			},

      getSelectionRules(data){
        this.$api.getSelectionRules(data).then(res=>{
          console.log(res.data.rows,'222222222222')
          this.takeNumberRules = res.data.rows
        })
      },


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