<template>
	<view class="page">
		<view class="periodDate">
			<text>服务日期：{{orderParam.serviceDate}}</text>
		</view>
    <view class="store-wrap">
      <view class="store-info">
        <view class="logo">
          <image src="../../static/index/u55.png" mode=""></image>
        </view>
        <view @click="gotoStoreChoose()" class="store-content">
          <view class="h-row">
            <view class="store-desc">
              <view class="store-name">
                <view class="">{{ storeInfo.storeName }}</view>
              </view>
            </view>
            <view class="arrow-right">
              <view class="change-store">更换门店</view>
              <u-icon name="arrow-right" color="#333" size="16"></u-icon>
            </view>
          </view>
          <view class="h-row">
            <text class="address">地址：{{ storeInfo.address }}</text>
            <!-- <text class="address">距你1.8km</text> -->
          </view>
        </view>
      </view>

    </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,
				templateId:[],
				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:[],
        storeInfo: {},
			}
		},
		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() {

      // 查询门店信息
      const data = uni.getStorageSync('storeInfo');
      this.store = uni.getStorageSync('storeInfo')
      if (!data) {
        // 获取位置信息查询门店列表数据
        this.getLocation();
      } else {
        this.storeInfo = data;
      }
			this.getServicePersonTime()
			this.getTemplateList()
      this.getSelectionRules(this.takeNumberData)
		},
		onUnload(){
			clearTimeout(this.timeoutId);
		},
		methods: {
      // 获取门店列表数据
      getStoreListData(data) {
        let that = this;
        // 用户绑定门店
        this.$api.storeList(data).then((res) => {
          console.log(res.data.data[0])
          that.storeInfo = res.data.data[0]
          // 更新用户选择的门店信息
          uni.setStorageSync('storeInfo', res.data.data[0])
        })
      },
      // 获取经纬度信息
      getLocation() {
        let that = this
        console.log('+++++++++++++开始获取位置信息++++++++++++++++')
        uni.getLocation({
          type: 'gcj02',
          success: function (res) {
            console.log(res)
            let latitude = res.latitude; // 纬度
            let longitude = res.longitude; // 经度
            let speed = res.speed; // 速度
            let accuracy = res.accuracy; // 精确度
            // 在这里可以对位置信息进行处理
            console.log("纬度：" + latitude + ";经度" + longitude)
            that.reqParm.latitude = latitude
            that.reqParm.longitude = longitude
            uni.setStorageSync('location', that.reqParm)
            that.getStoreListData(that.reqParm)
          },
          fail:function (fail) {
            console.log('获取用户地址失败==》',fail)
            that.getStoreListData(that.reqParm)
          },
          complete:function (complete) {
            console.log('获取用户地址失败or成功==》',complete)
          }
        });
      },
      // 去选择门店
      gotoStoreChoose() {
        uni.setStorageSync('router','0')
        uni.redirectTo({
          url: '/storePages/store/store-choose?type=1',
        })
      },
			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
        uni.showLoading({
          title: '加载中'
        });
				this.$api.commonGeneralOrder(this.orderParam).then(res => {
					this.requestStatus = false
          uni.hideLoading();
          uni.$u.toast('预约成功')
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/order/index'
            })
          }, 500)


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

		}
	}
</script>

<style scoped lang="scss">
	@import './index.rpx.scss';
  .store-wrap {
    margin-top: 10rpx;
background-color: white;
    .store-info {
      display: flex;

      .logo {
        width: 10%;
        text-align: center;
        display: flex;
        justify-content: center;
        align-items: center;

        image {
          width: 30px;
          height: 30px;
        }
      }

      .store-content {
        width: 90%;
        padding-bottom: 13px;

        .h-row {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .store-desc {
            width: 90%;
            display: flex;
            line-height: 30px;
            font-size: 14px;

            .store-name {
            }

          }

          .arrow-right {
            text-align: right;
            margin: 0 auto;
            cursor: pointer;
            padding-top: 3px;
            width: 100px;
            display: flex;
            font-size: 14px;

            .change-store {
              text-align: right;
              color: #666;
            }

            image {
              width: 18px;
              height: 18px;
            }
          }

          .address {
            color: #999999;
            font-size: 12px;
            padding-right: 12px;
          }
        }
      }

    }

    .adress {
      font-size: 22rpx;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      padding-left: 80rpx;
      color: #666;
    }
  }
</style>
