<template>
	<view class="container">
		<VNavigationBar background-color="rgba(0,0,0,0)" title-color="#333" title="提交预约"></VNavigationBar>
		<view class="body">
			<view class="carInfo">
				<view class="cardInfoHeader">
					<view class="carInfoLeftTop">
						<image class="carInfoLeftTopIcon" src="../../static/icons/order-icon10.png" mode="widthFix">
						</image>
						车辆信息
					</view>
					<view class="carInfoRightTop">
						<!-- <uni-icons type="compose" color="#0174F6"></uni-icons> 修改信息 -->
						<span style="color: #0174F6;" @click="selectCar">选择车辆</span>
					</view>
				</view>
				<view class="cardInfoBody">
					<view class="cardInfoBody_content">
						<view class="carForm">
							<view class="carForm_num">车牌号：{{car.licenseNumber}}</view>
							<view class="carForm_carName">车辆持有人：{{cusInfo.cusName}}</view>
							<view class="carForm_carPhone">持有人电话：{{cusInfo.phoneNumber}}</view>
						</view>
						<image class="carImg" src="" mode="aspectFill" :src="config.baseImageUrl + car.logoImg"></image>
					</view>
					<view class="cardInfoBody_footer">
						<view class="nj">
							年检时间：<text class="date">{{car.nextInspectionDate || '未获取到'}}</text>
							<image class="cardInfoBody_footerIcon" src="../../static/icons/icon2.png" mode="aspectFit">
							</image>
						</view>
						<view class="bx">
							保险时间：<text class="date">{{car.insuranceExpiryDate || '未获取到'}}</text>
							<image class="cardInfoBody_footerIcon" src="../../static/icons/icon2.png" mode="aspectFit">
							</image>
						</view>
					</view>
				</view>
			</view>
			<view class="baseInfo">
				<view class="formItem">
					<view class="formItem_content">
						<view class="label">姓名</view>
						<input class="formItemInput" placeholder="请输入姓名" type="text" v-model="formData.userName" />
					</view>

				</view>
				<view class="formItem">
					<view class="formItem_content">
						<view class="label">联系电话</view>
						<input class="formItemInput" placeholder="请输入联系电话" type="text" v-model="formData.userMobile"/>
					</view>
				</view>
				<view class="formItem">
					<view class="formItem_content">
						<view class="label">服务顾问</view>
            <picker style="text-align: right; flex: 1;" @change="servicerPickerChange" :value="servicerIndex" :range="allServicerNameList">
              <view class="uni-input">{{allServicerNameList[servicerIndex]}}</view>
            </picker>
					</view>
				</view>
				<view class="formItem">
					<!-- <picker mode="selector" :range="['汽车维修']" @change="">
						<view class="formItem_content">
							<view class="label">预约项目</view>
							<input disabled class="formItemInput" placeholder="请选择预约项目" type="text" />
							<image class="formItemBtn" src="../../static/icons/homeInfoMore.png" mode="aspectFit">
							</image>
						</view>
					</picker> -->
					<view class="formItem_content" @click="selectServer">
						<view class="label">预约项目</view>
						<input disabled class="formItemInput" placeholder="请选择预约项目" type="text" v-model="service.label" />
						<image v-if="!service.name" class="formItemBtn" src="../../static/icons/homeInfoMore.png" mode="aspectFit">
						</image>
					</view>
				</view>
			</view>

			<view class="dateCard">
				<view class="cardTitle">预约时间</view>
				<view class="datePicker">
					<view v-for="(date, index) in dateList" :key="date.date" class="dateItem"
						:class="{active: chooseDate == date.date, disabled: date.disabled}"
						@click="chooseDateFun(date)">
						<text>{{date.date}}</text>
						<text>{{date.title}}</text>
						<image v-if="chooseDate == date.date" class="activeIcon"
							src="../../static/icons/order-icon11.png" mode="aspectFit"></image>
					</view>
				</view>
				<view class="timerPicker">
					<view v-for="(time, index) in timeList" :key="index" class="timeItem"
						:class="{active: chooseTime == time.time, disabled: time.disabled}"
						@click="chooseTimeFun(time)">
						<text>{{time.date}}</text>
						<image v-if="chooseTime == time.date" class="activeIcon"
							src="../../static/icons/order-icon11.png" mode="aspectFit"></image>
					</view>
				</view>
			</view>
		</view>
		<view class="footer">
			<view class="footerBtn" @click="submit">提交预约</view>
		</view>
	</view>
</template>

<script>
	import request from '../../utils/request';
	import VNavigationBar from '@/components/VNavigationBar.vue'
  import config from "@/config";
  import {getToken,getUserInfo,getJSONData} from '@/utils/auth'

	export default {
		components: {
			VNavigationBar,
		},
    computed: {
      config() {
        return config
      }
    },
		data() {
			return {
				// dateList: [{
				// 	date: '06-05',
				// 	title: '周四',
				// 	disabled: true
				// }, {
				// 	date: '06-06',
				// 	title: '周四',
				// 	disabled: false
				// }, {
				// 	date: '06-07',
				// 	title: '周四',
				// 	disabled: false
				// }, {
				// 	date: '06-08',
				// 	title: '周四',
				// 	disabled: false
				// }, {
				// 	date: '06-09',
				// 	title: '周四',
				// 	disabled: false
				// }, ],
        dateList:[],
				chooseDate: '',
				chooseTime: '',
				timeList: [],
				carList: [],
				car:{},
				cusInfo: {},
				formData:{
					userName: null,
					userMobile: null,
					repairType:  null,
					carId: null,
					carNo: null,
					bookingTime: null,
					corpId: null
				},
				serviceList: [],
				service:{},
				info: {},
        //所有可选服务顾问
        servicerList:[{
          id:"",
          nickname:"请选择",
        }],
        //所有可选服务顾问-只有名称
        allServicerNameList:["请选择"],
        //选中的服务顾问下标
        servicerIndex:0,
        //我的邀请者
        myAdviser:null
			}
		},
		onLoad(data){
      //当前登录用户信息
      this.$nextTick(()=>{
        let userInfo = JSON.parse(getUserInfo())
        console.log(userInfo,"userInfo")
        this.formData.userName = userInfo.nickname
        this.formData.userMobile = userInfo.mobile
        this.formData.corpId = this.info.id
      })
      this.info = getJSONData("shopInfo")
			this.getServer(this.info.id)
      this.initCarList()
      this.initServicerList()
		},
		onShow() {
      if(!getToken()){
        uni.reLaunch({
          url: '/pages/login/login'
        })
      }
      this.myAdviser = getJSONData("myAdviser")
      this.initDateList()
		},
		methods: {
      servicerPickerChange: function(e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        this.servicerIndex = e.detail.value
      },
      /**
       * 查询所有服务顾问
       * @returns {Promise<void>}
       */
      async initServicerList(){
        const res = await request({
          url: "/app-api/repair/booking/getAllServicer",
          method: "get",
          params:{tenantId:this.info.tenantId},
          tenantIdFlag:false
        })
        if(res.code==200 &&  res.data.length>0){
          this.servicerList = this.servicerList.concat(res.data)
          if(this.myAdviser && this.myAdviser.userId){
            this.servicerList.map((item,index)=>{
              if(this.myAdviser.userId==item.id){
                this.servicerIndex = index
              }
            })
          }
          this.allServicerNameList = this.allServicerNameList.concat(res.data.map((item)=>{return item.nickname}))
        }
      },
      async initDateList(){
        this.dateList = []
        const res = await request({
          url: "/app-api/repair/booking/getBookingTime",
          method: "get",
          params:{tenantId:this.info.tenantId},
          tenantIdFlag:false
        })
        if(res.code==200 &&  res.data.length>0){
          this.dateList = res.data
          this.chooseDateFun(this.dateList[0])
        }
      },
			chooseTimeFun(time) {
				if (time.disabled) {
					return
				}
				this.chooseTime = time.date
			},
			chooseDateFun(date) {
				if (date.disabled) {
					return
				}
				this.chooseDate = date.date
        this.timeList = date.timeList
			},
			submit() {
        if(this.servicerIndex!=0){
          //设置选择的服务顾问
          this.formData.adviserId = this.servicerList[this.servicerIndex].id
          this.formData.adviserName = this.servicerList[this.servicerIndex].nickname
		  this.info.adviserName = this.servicerList[this.servicerIndex].nickname
		  this.info.adviserMobile = this.servicerList[this.servicerIndex].mobile
        }
        if(""==this.chooseTime){
          uni.showToast({
            title: '请选择预约时间！',
            icon: 'none'
          })
          return
        }
				this.formData.bookingTime = new Date((new Date().getFullYear() + "-" + this.chooseDate + " " + this.chooseTime + ":00")).getTime()
				request({
					url: "/userClient/repair/booking/update",
					method: "post",
					data: this.formData
				}).then(res => {
					uni.redirectTo({
						url: '/pages/myReservation/reservationSuccess?info=' + encodeURIComponent(JSON.stringify(this.info))
					})
				}).catch(() => {})
			},
			async initCarList() {
				const res = await request({
					url: "/userClient/base/myCar/get",
					method: "get"
				})
				this.carList = res.data
				if(this.carList && this.carList.length > 0){
					this.car = this.carList[0]
					this.formData.carId = this.car.id
					this.formData.carNo = this.car.licenseNumber
					this.selectCusInfo(this.car.id)
				}
			},
			// 车辆选择
			selectCar() {
				const carNos = this.carList.map(item => item.licenseNumber)
				uni.showActionSheet({
					itemList: carNos,
					success: (res) => {
						this.car = this.carList[res.tapIndex]
						this.formData.carId = this.car.id
						this.formData.carNo = this.car.licenseNumber
						this.selectCusInfo(this.car.id)
					},
					fail: (err) => {
						console.error('选择框显示失败：', err);
					}
				});
			},
			// 反查客户信息
			async selectCusInfo(carId){
				const res = await request({
					url: "/userClient/customer/getByCarId?carId=" + carId,
					method: "get"
				})
				this.cusInfo = res.data
			},
			// 取服务
			async getServer(corpId) {
				const res = await request({
					url: "/userClient/dict/type?type=repair_type",
					method: 'get'
				})
				this.serviceList = res.data
				// 设置默认第一个
				this.service = this.serviceList[0]
				this.formData.repairType = this.service.value
				this.info.serviceName = this.service.label
			},
			// 选择服务
			selectServer(){
				const servers = this.serviceList.map(item => item.label)
				uni.showActionSheet({
					itemList: servers,
					success: (res) => {
						this.service = this.serviceList[res.tapIndex]
						this.formData.repairType = this.service.value
						this.info.serviceName = this.service.label
					},
					fail: (err) => {
						console.error('选择框显示失败：', err);
					}
				});
			}
		}
	}
</script>

<style lang="less" scoped>
	.container {
		height: 100%;
		display: flex;
		flex-direction: column;

		background: linear-gradient(180deg, #C1DEFF 0%, rgba(193, 222, 255, 0) 100%);
		background-size: 100% 500rpx;
		background-repeat: no-repeat;

	}

	.body {
		flex: 1;
		height: 0;
		overflow: auto;
		background: linear-gradient(180deg, rgba(193, 222, 255, 0) 0%, #F3F5F7 50%, #F3F5F7 100%);

		.carInfo {
			margin: 20rpx 32rpx 30rpx;
			background: #022B9A;
			box-shadow: 0rpx 8rpx 16rpx 0rpx rgba(10, 54, 104, 0.1);
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			overflow: hidden;

			.cardInfoHeader {
				display: flex;
				align-items: stretch;
			}

			.carInfoLeftTop {
				display: flex;
				align-items: center;
				column-gap: 10rpx;
				padding: 20rpx;
				color: #fff;

				.carInfoLeftTopIcon {
					width: 36rpx;
				}
			}

			.carInfoRightTop {
				flex: 1;
				width: 0;
				background-color: #fff;
				text-align: right;
				padding-right: 20rpx;

				display: flex;
				align-items: center;
				justify-content: flex-end;
				border: 10rpx;
				clip-path: polygon(20rpx 0, 100% 0, 100% 0, 100% 100%, 100% 100%, 0 100%, 10rpx 10rpx);
			}

			.cardInfoBody {
				padding: 30rpx;
				background-color: #fff;
				border-radius: 16rpx 0rpx 0 0;
			}

			.cardInfoBody_content {
				display: flex;
				align-items: stretch;
				column-gap: 32rpx;
				padding-bottom: 20rpx;
				border-bottom: 1rpx dashed #858BA0;

				.carForm {
					padding: 10rpx 0;
					display: flex;
					flex-direction: column;
					justify-content: space-between;
					font-weight: 500;
					font-size: 28rpx;
					color: #858BA0;
					flex: 1;
					width: 0;
				}

				.carForm_num {
					font-weight: bold;
					font-size: 36rpx;
					color: #333333;
				}

				.carImg {
					width: 240rpx;
					height: 150rpx;
					border-radius: 8rpx 8rpx 8rpx 8rpx;
					background-color: #efefef;
				}
			}

			.cardInfoBody_footer {
				display: flex;
				align-items: center;
				font-weight: 500;
				font-size: 28rpx;
				color: #333333;
				padding-top: 20rpx;

				.nj {
					border-right: 1rpx solid #ddd;
					margin-right: 20rpx;
				}

				.nj,
				.bx {
					flex: 1;
					width: 0;

					display: flex;
					align-items: center;
					column-gap: 10rpx;
				}

				.date {
					color: #0174F6;
				}

				.cardInfoBody_footerIcon {
					width: 28rpx;
					height: 28rpx;
				}
			}
		}

		.baseInfo {
			margin: 20rpx 32rpx 30rpx;
			background: #FFFFFF;
			border-radius: 12rpx 12rpx 12rpx 12rpx;
			padding: 0 30rpx;
			font-weight: 500;
			font-size: 28rpx;
			color: #333333;

			.formItem {
				padding: 40rpx 0;
				border-bottom: 1rpx solid #EEEEEE;

				&:last-child {
					border: none;
				}
			}

			.formItem_content {
				display: flex;
				align-items: center;
				column-gap: 10rpx;
			}

			.formItemInput {
				flex: 1;
				width: 0;
				text-align: right;
			}

			.formItemBtn {
				width: 24rpx;
				height: 24rpx;
			}
		}

		.dateCard {
			margin: 20rpx 32rpx 30rpx;
			padding: 22rpx 30rpx;
			background: #FFFFFF;
			border-radius: 16rpx 16rpx 16rpx 16rpx;

			.cardTitle {
				font-weight: bold;
				font-size: 28rpx;
				color: #333333;
			}

			.datePicker {
				display: flex;
				column-gap: 20rpx;
				overflow: auto;
				padding: 30rpx 0;
				border-bottom: 1rpx solid #EEEEEE;

				.dateItem {
					padding: 20rpx 40rpx;
					border-radius: 8rpx 8rpx 8rpx 8rpx;
					border: 1rpx solid rgba(0, 0, 0, 0.1);

					font-size: 24rpx;
					color: #666666;

					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;

					flex-shrink: 0;
				}
			}

			.timerPicker {
				display: grid;
				grid-template-columns: 1fr 1fr 1fr;
				gap: 20rpx;
				padding-top: 30rpx;

				.timeItem {
					border-radius: 8rpx 8rpx 8rpx 8rpx;
					border: 1rpx solid rgba(0, 0, 0, 0.1);
					padding: 30rpx 0;
					text-align: center;

				}
			}

			.timeItem,
			.dateItem {
				position: relative;
				overflow: hidden;

				&.active {
					border-radius: 8rpx 8rpx 8rpx 8rpx;
					border: 2rpx solid #0174F6;
					color: #0174F6;
				}

				&.disabled {
					border-radius: 8rpx 8rpx 8rpx 8rpx;
					border: 1rpx solid rgba(0, 0, 0, 0.1);
					color: rgba(51, 51, 51, 0.4);
				}

				.activeIcon {
					position: absolute;
					right: 0;
					top: 0;
					width: 36rpx;
					height: 24rpx;
				}
			}
		}
	}

	.footer {
		background: #FFFFFF;
		padding: 12rpx 0;
		padding-bottom: calc(12rpx + env(safe-area-inset-bottom));

		.footerBtn {
			width: 80%;
			margin: 0 auto;
			padding: 22rpx 0;
			background: #0174F6;
			border-radius: 38rpx 38rpx 38rpx 38rpx;

			display: flex;
			align-items: center;
			justify-content: center;

			font-weight: bold;
			font-size: 32rpx;
			color: #FFFFFF;
		}
	}
</style>
