<template>
	<view>
		<view class="content">
			<view class="box-card">
				<view class="box-card-title">
					预约详情
				</view>
				<view class="box-card-content">
					<view class="book-box" style="padding-top: 20rpx;">
						<view class="book-box-card">
							<view class="book-box-title">
								日期
							</view>
							<view class="book-box-row">
								<view class="book-box-row-date">
									<block v-for="(item,index) in listDatePrice" :key="index">
										<view class="book-box-row-dateitem" :class="{'book-box-row-dateitem-on':item.checked,
										'book-box-row-dateitem-none':item.is_open==0}" @click="handleDate(index)">
											<view class="book-box-row-dateitem-status">
												<u-icon name="checkmark" color="#fff" size="20rpx" v-if="item.checked">
												</u-icon>
												<text v-else>{{item.is_open==1?'余票':"售罄"}}</text>
											</view>
											<view>{{item.week}}</view>
											<view>{{item.datef}}</view>
										</view>
									</block>
								</view>
								<view class="book-box-row-select" @click="openCalendar">
									<view>
										<view>指定</view>
										<view>日期</view>
									</view>
									<view class="book-box-row-select-more">
										<u-icon name="arrow-right" color="#EF9525" size="20rpx"></u-icon>
									</view>
								</view>
							</view>
						</view>
						<view class="book-box-card">
							<view class="book-box-title">
								参观时间
							</view>

							<view class="book-box-timerow">
								<view class="book-box-row-timeitem" v-for="(item,index) in currentDate.rules"
									:class="{'book-box-row-timeitem-on':item.checked}" @click="handleSelectTime(index)">
									<view class="book-box-row-timeitem-status" v-if="item.checked">
										<u-icon name="checkmark" color="#fff" size="20rpx"></u-icon>
									</view>
									<view class="book-box-row-timeitem-txt">{{item.start_time+'-'+item.end_time}}</view>
									<view class="book-box-row-timeitem-txt">{{item.total}}张</view>
								</view>
							</view>
						</view>
					</view>
					<view class="book-box-selectInfo" style="width: 100%;">
						<view class="book-box-selectInfo-left">已选：{{currentDate.datef||""}}
							{{(currentTime.start_time||"")+"-"+(currentTime.end_time||"")}}
						</view>
						<view class="book-box-selectInfo-right" @click="openNoticeInfo(0)">
							<text class="book-box-selectInfo-righttxt">预约须知</text>
							<u-icon name="arrow-right" color="#EF9525" size="20rpx"></u-icon>
						</view>
					</view>
				</view>

			</view>
			<u--form labelPosition="left" :model="form" :rules="rules" ref="form">
				<view class="box-card">
					<view class="box-card-title">
						添加观众
					</view>
					<view class="box-card-content">
						<u-form-item label="参观人数" labelWidth="120" prop="total" ref="total">
							<u-number-box slot="right" v-model="form.total" inputWidth="44" color="#EF9525"
								bgColor="#FCF6E3" :min="(type=='user'?1:8)" :max="(type=='user'?5:50)" class="plus">
							</u-number-box>
						</u-form-item>
						<view class="box-tips">
							<text class="box-tips-txt" v-if="type=='user'">每单限购5张，同一身份证当天限购1张</text>
							<text class="box-tips-txt" v-if="type=='team'">8人以上可团体预约，一个团体最多50人</text>
						</view>
						<view class="box-visitor">
							<block v-for="(item,index) in form.details_list" :key="index">

								<view class="box-visitor-item">
									<view class="box-visitor-item-left">
										<u-icon name="minus-circle" size="22" color="#828282" @click="delUser(index)">
										</u-icon>
										<view class="box-visitor-info">
											<view>{{item.name}}</view>
											<view>{{item.idcard}}</view>
										</view>
									</view>
									<view class="box-visitor-item-right" @click="openAdd(index)">
										<u-icon name="edit-pen" size="24" color="#828282"></u-icon>
									</view>
								</view>
							</block>
						</view>

						<view class="box-footer">
							<view class="box-footer-left">
								<view class="box-button" @click="openAdd">
									<u-icon name="plus" color="#EF9525"></u-icon>
									<text class="box-button-txt">添加观众</text>
								</view>
							</view>
							<view class="box-footer-right" v-if="type=='team'">
								<view class="box-button" @click="selectFile">
									<u-icon name="plus" color="#EF9525"></u-icon>
									<text class="box-button-txt">批量导入观众</text>
								</view>
							</view>
						</view>
						<view class="book-box-selectInfo" v-if="type=='team'" style="width: 100%; margin-top: 20rpx;">

							<view class="book-box-selectInfo-right" @click="openNoticeInfo(1)">
								<u-icon name="question-circle-fill" color="#EF9525" size="40rpx"></u-icon>
								<text class="book-box-selectInfo-righttxt" style="margin-left: 20rpx;">批量导入说明</text>
							</view>
						</view>
					</view>
				</view>
				<view class="box-card">
					<view class="box-card-title">
						{{type=="team"?"领队人信息":"联系人信息"}}
					</view>
					<view class="box-card-content" style="padding: 10px;">
						<u-form-item :label="(type=='team'?'领队人':'联系人')" labelWidth="80" prop="leader" ref="leader"
							required>
							<u-input placeholder="请输入联系人" v-model="form.leader"></u-input>
						</u-form-item>
						<block v-if="type=='team'">
							<u-form-item label="单位名称" labelWidth="80" prop="unit" required>
								<u-input placeholder="请输入单位名称" v-model="form.unit"></u-input>
							</u-form-item>
							<u-form-item label="证件类型" labelWidth="80" prop="card_type1" required>
								<u-radio-group v-model="form.card_type">
									<u-radio width="50%" activeColor="#EF9525" v-for="(item, index) in cardList"
										:key="index" :name=item.idx :label="item.name">
									</u-radio>
								</u-radio-group>
							</u-form-item>
							<u-form-item label="证件号码" labelWidth="80" prop="from.idcard" required>
								<u-input placeholder="请输入证件号码" v-model="form.idcard"></u-input>
							</u-form-item>
						</block>
						<u-form-item label="手机号" labelWidth="80" prop="mobile" ref="mobile" required>
							<u-input placeholder="请输入手机号" v-model="form.mobile"></u-input>
						</u-form-item>
					</view>
				</view>
			</u--form>
			<view class="page-bottom">
				<u-button type="primary" @click="submitOrder">确定</u-button>
			</view>
		</view>
		<u-popup :show="showAdd" mode="bottom" @close="closeAdd" :round="10" closeable>
			<view class="mpopup">
				<view class="mpopup-title">
					添加观众
				</view>
				<view class="mpopup-content" style="margin-top: 60rpx;">
					<u--form labelPosition="left" :model="formUser" :rules="rules" ref="formUser">
						<u-form-item label="姓名" labelWidth="80" prop="name" ref="name" required>
							<u-input placeholder="请输入姓名" v-model="formUser.name"></u-input>
						</u-form-item>
						<u-form-item label="证件类型" labelWidth="80" prop="card_type1" ref="card_type" required>
							<u-radio-group v-model="formUser.card_type">
								<u-radio width="50%" activeColor="#EF9525" v-for="(item, index) in cardList"
									:key="index" :name=item.idx :label="item.name">
								</u-radio>
							</u-radio-group>
						</u-form-item>
						<u-form-item label="证件号码" labelWidth="80" prop="idcard" ref="idcard" required>
							<u-input placeholder="请输入证件号码" v-model="formUser.idcard"></u-input>
						</u-form-item>
						<u-form-item label="手机号" labelWidth="80" prop="from.mobile" ref="mobile">
							<u-input placeholder="请输入手机号" v-model="formUser.mobile"></u-input>
						</u-form-item>
					</u--form>

					<u-button type="primary" @click="handleAddUser">确定</u-button>
				</view>
			</view>
		</u-popup>


		<u-popup :show="showInfo" mode="bottom" @close="closeInfo" :round="10" closeable>
			<view class="mpopup">
				<view class="mpopup-title">
					{{currentNotice.title}}
				</view>
				<view class="mpopup-content" style="margin-top: 60rpx;">
					<rich-text :nodes="currentNotice.content"></rich-text>
					<view style="margin-top: 80px;"></view>
					<u-button type="primary" @click="closeInfo">知道了</u-button>
				</view>
			</view>
		</u-popup>

		<u-calendar ref="calendar" :show-confirm="false" :show="showCalendar" :minDate="minDate" :maxDate="maxDate"
			color="#EF9525" round="20" defaultDate="2022-02-15" @confirm="handleSelectDate" @close="closecalendar">
		</u-calendar>
	</view>
</template>

<script>
	export default {

		data() {
			const d = new Date()
			const year = d.getFullYear()
			let month = d.getMonth() + 1
			month = month < 10 ? `0${month}` : month
			const date = d.getDate()
			return {
				showInfo: false,
				currentNotice: {},
				notice: [{
					title: "预约须知",
					content: "预约须知的内容"
				}, {
					title: "批量上传帮助",
					content: "<p>1.批量上传EXCEL的以xlsx结尾</p><p>2.第一列为标题列 姓名	手机号	证件号</p><p>3.文件是从微信聊天记录中选取或者微信文件传输助手</p>"
				}],
				form: {
					date: "",
					rule_id: "",
					unit: "",
					leader: "",
					card_type: 1,
					idcard: "",
					total: 1,
					mobile: "",
					type: "",
					details_list: []
				},
				formUser: {
					name: "",
					idcard: "",
					mobile: "",
					card_type: 1
				},
				rules: {
					name: [{
						required: true,
						message: '请输入姓名',
						trigger: 'blur'
					}],
					idcard: [{
						required: true,
						message: '请输入证件号',
						trigger: 'blur'
					}],
					card_type: [{
						required: true,
						message: '请选择证件类型',
						trigger: 'change'
					}]
				},
				listVistor: [{}, {}],
				showAdd: false,
				showInfo: false,
				showBook: false,
				minDate: `${year}-${month}-${date + 1}`,
				maxDate: `${year}-${month}-${date + 7}`,
				showCalendar: false,
				listDatePrice: [],
				currentDate: {},
				currentTime: {},
				bcurrentDate: {},
				bcurrentTime: {},
				currentIndex: 0,
				listCalendar: [],
				type: "user",
				user: {},
				cardList: [{
						idx: 1,
						name: '身份证'
					},
					{
						idx: 2,
						name: '护照'
					}
				]
			}
		},
		onReady() {
			// 如果需要兼容微信小程序的话，需要用此写法
			this.$refs.calendar.setFormatter(this.formatter)
			this.$refs.formUser.setRules(this.rules);
		},
		onLoad(options) {
			if (options.currentDate) {
				this.bcurrentDate = JSON.parse(options.currentDate);
				this.currentDate = this.bcurrentDate;
			}
			if (options.currentTime) {
				this.bcurrentTime = JSON.parse(options.currentTime);
				this.currentTime = this.bcurrentTime;
			}
			this.form.type = (options.from == 'user' ? 2 : 1);
			this.type = options.from;
			this.load3Day(this.bcurrentDate.date);
			uni.setNavigationBarTitle({
				title: (options.from == 'user' ? "个人预约" : "团队预约")
			})
			var that = this;
			that.util.getUserInfo(function(r) {
				that.user = r;
				that.form.mobile = r.mobile;
			}, true);
			
		},
		methods: {
			closeInfo() {
				this.showInfo = false;
			},
			openNoticeInfo(type) {
				this.showInfo = true;
				this.currentNotice = this.notice[type];
			},
			submitOrder() {
				this.form.date = this.currentDate.date;
				this.form.rule_id = this.currentTime.id;
				if (this.util.isNull(this.form.leader)) {
					if (this.type == "user") {
						uni.showToast({
							icon: "none",
							title: "请填写联系人"
						})
					} else {

						uni.showToast({
							icon: "none",
							title: "请填写领队姓名"
						})
					}
					return false;
				}

				if (this.type != "user") {
					if (this.util.isNull(this.form.unit)) {
						uni.showToast({
							icon: "none",
							title: "请填写单位名称"
						})
						return false;
					}

					if (this.util.isNull(this.form.idcard)) {
						uni.showToast({
							icon: "none",
							title: "请填写证件号"
						})
						return false;
					}

					if (this.form.card_type == 1) {
						if (!uni.$u.test.idCard(this.form.idcard)) {
							uni.showToast({
								icon: "none",
								title: "请正确输入身份证号"
							})
							return false;
						}
					}
				}



				if (this.util.isNull(this.form.mobile)) {
					uni.showToast({
						icon: "none",
						title: "请填写手机号"
					})
					return false;
				} else if (!uni.$u.test.mobile(this.form.mobile)) {
					uni.showToast({
						icon: "none",
						title: "请正确填写手机号"
					})
					return false;
				}
				if (this.form.details_list.length != this.form.total) {
					uni.showToast({
						icon: "none",
						title: "请正确添加观众数量"
					})
					return false;
				}

				var that = this;
				this.util.request({
					api: '/api/mobile/visit/order',
					method: "POST",
					data: this.form,
					utilSuccess: function(res) {
						console.log(res)
						uni.showToast({
							icon: "none",
							title: "下单成功",
							complete() {
								uni.reLaunch({
									url: "/pages/success/success?from=visit&id=" + res.id
								})
							}
						})
					},
					utilFail: function(res) {
						uni.showToast({
							icon: "none",
							title: res
						})
					}
				})

			},
			selectFile() {
				let _that = this
				wx.chooseMessageFile({
					count: 1, //最多可以选择的文件个数，可以 0～100
					type: 'file', //所选的文件的类型，具体看官方文档
					success(res) {
						// tempFilePath可以作为img标签的src属性显示图片
						const tempFilePaths = res.tempFiles[0].path
						let filename = res.tempFiles[0].name; //用于页面显示的名字
						// 这一步判断可以省略，如果需求没有格式要求的话
						if (filename.indexOf(".xlsx") == -1) {
							uni.showToast({
								icon: "none",
								title: "暂时仅支持xlsx格式的文件"
							})
							return
						} else {
							console.log("开始上传");
							uni.showLoading({
								title: "正在上传"
							})
							wx.uploadFile({
								url: _that.util.HOST + '/api/mobile/visit/excel-analyse', //上传的路径
								filePath: tempFilePaths, //刚刚在data保存的文件路径
								name: 'file', //后台获取的凭据
								formData: { //如果是需要带参数，请在formData里面添加，不需要就去掉这个就可以的
									"token": uni.getStorageSync("userInfo").token
								},
								success(res) {
									var jsonlist = JSON.parse(res.data)
									for (var m of jsonlist) {

										_that.form.details_list.push({
											name: m.name,
											idcard: m.idcard,
											mobile: m.mobile,
											card_type: 1
										})
									}
									uni.hideLoading();
								}
							})
							console.log('上传到服务器')
						}
					}
				})
			},
			handleAddUser() {
				var that = this;
				//验证表单
				try {
					this.$refs.formUser.validate().then(res => {
						if (that.formUser.card_type == 1) {
							if (!uni.$u.test.idCard(that.formUser.idcard)) {
								uni.showToast({
									icon: "none",
									title: "请正确输入身份证号"
								})
								return false;
							}
						}

						that.form.details_list.push(that.formUser);
						that.showAdd = false;
					}).catch(errors => {
						uni.showToast({
							icon: "none",
							title: "观众信息提交不正确"
						})
					})

				} catch (e) {
					console.log(e)
					//TODO handle the exception
				}

			},
			closecalendar() {
				this.showCalendar = false;
			},
			handleSelectDate(e) {
				if (e.length != 0 && (e[0] != this.currentDate.date)) {
					this.load3Day(e[0]);
					this.showCalendar = false;
				}
			},
			openCalendar() {
				var that = this;
				var edate = this.$moment().add('days', 7).format("yyyy-MM-DD");
				var ndate = this.$moment().add('days', 1).format("yyyy-MM-DD")
				this.loadCalendar(ndate, edate, function(res) {
					that.listCalendar = res;
					that.showCalendar = true;
				});
			},
			formatter(day) {
				for (var m of this.listCalendar) {
					let date = this.$moment(day.date).format("yyyy-MM-DD");
					if (date == m.date) {
						if (m.is_open == 1)
							day.bottomInfo = '余票'
						else {
							day.bottomInfo = '售罄'
						}
					}
				}
				return day
			},
			handleDate(index) {
				var nt = this.$moment().format("yyyy-MM-DD");
				let list = this.listDatePrice;
				let cdate = list[index];
				if (nt == cdate.date) {
					uni.showToast({
						icon: "none",
						title: "请提前一天预约"
					})
					return;
				}
				for (var m of list) {
					m.checked = false;
				}
				cdate.checked = true;
				let i = 0;
				for (var m of cdate.rules) {
					m.checked = false;

					m.checked = i == 0
					if (m.checked) {
						this.currentTime = m;
					}
					i++;
				}

				this.currentDate = cdate;
				this.listDatePrice = list;
				this.$forceUpdate();
			},
			handleSelectTime(index) {
				for (var m of this.currentDate.rules) {
					m.checked = false;
				}
				this.currentDate.rules[index].checked = true;
				this.currentTime = this.currentDate.rules[index];
				this.$forceUpdate();
			},
			load3Day(sdate) { //加载7天数据
				var that = this;
				that.listDatePrice = [];
				var nt = this.$moment().format("yyyy-MM-DD");
				sdate = sdate == "" ? nt : sdate;
				var edate = this.$moment(sdate).add('days', 2).format("yyyy-MM-DD");
				var ndate = this.$moment(sdate).add('days', 1).format("yyyy-MM-DD")

				var mt = this.$moment().add('days', 1).format("yyyy-MM-DD");
				var ht = this.$moment().add('days', 2).format("yyyy-MM-DD");
				var selectDate = (nt == sdate) ? ndate : sdate;
				this.loadCalendar(sdate, edate, function(res) {
					that.listDatePrice = res;
					var i = 0;
					for (var m of that.listDatePrice) {
						m.checked = false;
						m.datef = that.$moment(m.date).format("MM月DD日");
						var week = that.$moment(m.date).format("dddd");
						if (m.date == nt)
							m.week = "今天";
						else if (m.date == mt) {
							m.week = "明天";
						} else if (m.date == ht) {
							m.week = "后天";
						} else {
							m.week = week;
						}
						if (m.date == selectDate) {
							m.checked = true;
							that.currentDate = m;
							that.currentIndex = i;
							let idx = 0;
							for (var mod of m.rules) {
								mod.checked = false;
								if (that.bcurrentTime) {
									console.log(that.bcurrentTime)
									console.log("mod", mod)
									if (mod.id == that.bcurrentTime.id)
										mod.checked = true;
									that.currentTime = that.bcurrentTime;
								} else {
									mod.checked = idx == 0
									if (mod.checked) {
										that.currentTime = mod;
									}
								}
								idx++;
							}
						}
						i++;
					}
				})
			},
			loadCalendar(sdate, edate, cb) {
				var that = this;
				this.util.request({
					api: '/api/mobile/visit/get-calendar',
					data: {
						start_date: sdate,
						end_date: edate
					},
					utilSuccess: function(res) {
						cb(res);
					},
					utilFail: function(res) {

					}
				})
			},
			closeAdd() {
				this.showAdd = false
			},
			openAdd(index) {
				this.formUser = this.$options.data().formUser;
				console.log(index)
				if (index || index == 0) {
					let r = Object.assign(this.formUser, this.form.details_list[index]);
				}
				this.showAdd = true
			},
			delUser(index) {
				this.form.details_list.splice(index, 1);
			}
		}
	}
</script>

<style>
	@import url("@/static/css/bookbox.css");

	.box-visitor-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.box-visitor-item-left {
		display: flex;
	}

	.box-visitor-info {
		font-size: 24rpx;
		color: #4E4E4E;
		margin-left: 22rpx;
	}

	.box-visitor {
		margin: 32rpx 0rpx 27rpx 0rpx;
	}

	.box-footer {
		display: flex;
		justify-content: space-between;
		padding-top: 28rpx;
		border-top: 2px solid #F7F6F4;
	}

	.box-footer-left {
		display: flex;
		flex: 1;
		margin-right: 8rpx;
	}

	.box-footer-right {
		display: flex;
		flex: 1;
		margin-left: 8rpx;
	}

	.box-button-txt {
		margin-left: 20rpx;
	}

	.box-button {
		display: flex;
		background: #FCF6E3;
		border: 1px solid #EF9525;
		border-radius: 5px;
		padding: 20rpx 0rpx;
		width: 100%;
		justify-content: center;
		color: #4E4E4E;
	}

	.box-tips {
		background-color: #f7f6f4;
		height: 62rpx;
		line-height: 62rpx;
		color: #828282;
		padding: 0rpx 16rpx;
		font-size: 24rpx;
	}

	.page-bottom {
		background: #FFFFFF;
		height: 108rpx;
		box-shadow: 2rpx 3rpx 10rpx 0rpx rgba(107, 94, 77, 0.3);
		width: 100%;
		position: fixed;
		bottom: 0;
		left: 0;
		padding: 15rpx 25rpx;
		box-sizing: border-box;
		z-index: 1024;
	}

	.content {
		background-color: #f7f6f4;
		padding: 31rpx 26rpx;
		min-height: 100vh;
		padding-bottom: 128rpx;
	}

	.box-card {
		background: #FFFFFF;
		border-radius: 16rpx;
		padding: 31rpx 18rpx;
		margin-bottom: 20rpx;
	}

	.u-form-item__body__left__content__label {

		color: #4E4E4E !important;
	}

	.box-card-title {
		font-size: 32rpx;
		color: #351C1B;
		padding-bottom: 25rpx;
		border-bottom: 2px solid #F7F6F4;
	}

	.box-card-content {}
</style>
