<template>
	<view class="page">
		<view class="periodDate">
			<text>服务日期：{{orderParam.serviceDate}}</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 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.periodTimeList" :key="index2">
						<view class="timeItemView">
							<view class="flex-col justify-center timeItem " :class="{selectBack: item2.select}" @click="selectServiceTime(item.periodTimeList,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 v-for=" (item,index) in takeNumberRules " class="serobReminder">
        <text>{{index+1}}.{{item.dictValue}}。</text>
      </view>
<!--			<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 class="tabBarLineHeight "></view>
		<view class="tabBarView">
			<view class="submitButton " @click="openSetting">提交</view>
		</view>

	</view>
</template>

<script>
	export default {
		components: {
		},
		data() {
			return {
				timeoutId:null,
				periodTimeList:[],
				userInfo: {},
				store: {},
				serviceObjectList: [],
				requestStatus: false,
				orderParam: {
					orderType: 1,
					serviceAttribute: 1,
					serviceStoreId: '',
					remark: '',
					serviceDate: '',
					childService: [
						// {
						//   periodDate:'',//回显需要，不做参数
						//   serviceObjectId: '',
						//   facePhotoUrl:'', //回显需要，不做参数
						//   nickName:'', //回显需要，不做参数
						//   serviceUserId: '',
						//   personName:'',//回显需要，不做参数
						//   fee:'',//回显需要，不做参数
						//   serviceStartTime: ''
						// }
					]
				},
        takeNumberData:{
				  pageNum:1,
          pageSize:10,
          dictType:'today_make_rule'
        },
        takeNumberRules:[],
			}
		},
		onLoad() {
			this.store = uni.getStorageSync('storeInfo')
			this.userInfo = uni.getStorageSync('userInfo')
			this.orderParam.serviceStoreId = this.store.storeId
			let date = new Date();
			this.orderParam.serviceDate = date.getFullYear() + '-' + ('0' + (date.getMonth() + 1)).slice(-2) + '-' + ('0' +
				date.getDate()).slice(-2)
			 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.getServicePersonTime()
			this.getTemplateList()
      this.getSelectionRules(this.takeNumberData)
		},
		onUnload(){
			clearTimeout(this.timeoutId);
		},
		methods: {
			back(){
				uni.switchTab({
					url: '/pages/index/index',
				})
			},
			selectServiceTime(items,index,index2){
				items.forEach(e=>{
					e.select=false
				})
				let oidTime = this.orderParam.childService[index].serviceStartTime
				items[index2].select =true // 新选中的时间
				this.orderParam.childService[index].serviceStartTime = items[index2].label
				for (let i=0;i<this.orderParam.childService.length;i++){
					if (index != i){
						for (const time of this.orderParam.childService[i].periodTimeList) {
							if (time.label == oidTime){
								console.log('++++++++++++++++++++',oidTime)
								time.total = time.total + 1
							}
							if (time.label == items[index2].label) {
								console.log('------------------', items[index2].label)
								time.total = time.total - 1
							}
						}
					}
				}
				this.$forceUpdate()
			},

			// 查询服务对接信息列表
			listServiceObject() {
				this.$api.listServiceObject(this.reqParm).then((res) => {
					console.log(res)
					this.serviceObjectList = res.data.data
					this.getImgUrlByBannerOssId(this.serviceObjectList);
					this.orderParam.childService = [],
					this.serviceObjectList[0].select = true
					let periodTimeList = JSON.parse(JSON.stringify(this.periodTimeList))
					let childService = {
						periodDate: '',
						serviceObjectId: this.serviceObjectList[0].id,
						facePhotoUrl: this.serviceObjectList[0].facePhotoUrl,
						nickName: this.serviceObjectList[0].nickName,
						serviceUserId: -1,
						fee: '',
						serviceStartTime: periodTimeList[0].label,
						periodTimeList:periodTimeList
					}
					periodTimeList[0].select = true
					this.orderParam.childService.push(childService)
				})
			},
			// 获取图片
			getImgUrlByBannerOssId(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.orderParam.childService[0].facePhotoUrl = res.data.data[0].url.replace(
									/^http:/, "https:")
							}
						})
					}
				}
			},

			addServiceObject() {
				uni.navigateTo({
					url: '/myPages/ServiceObjectManagement/index'
				})
			},
			getServicePersonTime(){
				this.$api.getServicePersonTime({
					personId: -1,
					date: this.orderParam.serviceDate,
					storeId:this.store.storeId
				}).then(res=>{
					console.log("++++++++++++++++++res++++++++++++++++++++",res)
					this.periodTimeList = res.data.data
					if (this.periodTimeList.length===0){
						uni.$u.toast('暂无可预约排班')
					}
					// 服务对象
					this.listServiceObject()
				})
			},

			selectServiceObject(item) {
				if (item.select) {
					this.orderParam.childService = this.orderParam.childService.filter(selectServiceObject =>
						selectServiceObject.serviceObjectId !== item.id)
				} else {
					let periodTimeList = JSON.parse(JSON.stringify(this.periodTimeList))
					periodTimeList.forEach(i=>{
						this.orderParam.childService.forEach(i1=>{
							if (i.label == i1.serviceStartTime){
								i.total = i.total -1
							}
						})
					})

					let childService = {
						periodDate: '',
						serviceObjectId: item.id,
						facePhotoUrl: item.facePhotoUrl,
						nickName: item.nickName,
						serviceUserId: -1,
						fee: '',
						serviceStartTime: '',
						periodTimeList:periodTimeList
					}
					for (const time of periodTimeList) {
						if (time.total>0){
							time.select = true
							childService.serviceStartTime = time.label

							for (const childService of this.orderParam.childService) {
								for (const periodTime of childService.periodTimeList) {
									if (time.label == periodTime.label) {
										periodTime.total = periodTime.total - 1
									}
								}
							}
							break
						}
					}

					this.orderParam.childService.push(childService)
				}
				item.select = !item.select
				this.price = 0
				for (let childService of this.orderParam.childService) {
					this.price = this.price * 1 + childService.fee * 1
				}
			},

			getTemplateList(){
				this.$api.getTemplateList().then(res=>{
					this.templateId=res.data.data.data.map(item=>{
						return item.priTmplId
					})
				})
			},
      getSelectionRules(data){
        this.$api.getSelectionRules(data).then(res=>{
          console.log(res.data.rows,'222222222222')
          this.takeNumberRules = res.data.rows
        })
      },
			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.commonGeneralOrder()
					}
				})
			},

			commonGeneralOrder() {
				if (!this.orderParam.childService.length) {
					uni.$u.toast('请选择服务对象')
					return
				}
				let flag = false
				this.orderParam.childService.forEach(i=>{
					if (!i.serviceStartTime){
						uni.$u.toast('请选择服务时段')
						flag= true
					}
				})
				if (flag){
					return;
				}
				if (this.requestStatus) {
					return;
				}
				this.requestStatus = true

				this.$api.commonGeneralOrder(this.orderParam).then(res => {
					this.requestStatus = false
					uni.switchTab({
						url: '/pages/order/index'
					})

				}).catch(err => {
					this.requestStatus = false
				})
			}

		}
	}
</script>

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