<template>
	<!-- <page-meta :page-style="'overflow:'+(showinfo?'hidden':'visible')"></page-meta> -->
	<view class="cotainer">

		<date-picker ref="datePickers" @refresh="backDate" :data="listDates" :express="listExpress"></date-picker>


		<view class="orderForm">
			<u-form :model="form" label-width="180" ref="uForm" :error-type="['toast']">
				<view class="orderInfo">
					<view class="orderInfo-title">
						<view>{{cardInfo.sku?cardInfo.sku.name:''}}</view>
					</view>
					<view class="orderInfo-info">
						<image
							:src="cardInfo.sku?(cardInfo.sku.image_url?cardInfo.sku.image_url:require('@/static/logo-xietaitai.png')):require('@/static/logo-xietaitai.png')">
						</image>
						<view>
							<view>
								{{cardInfo.sku?cardInfo.sku.specs:''}}
							</view>
							<!-- <view>
								<view>今日剩余可提货量</view>
								<view>99</view>
							</view> -->
							<view>
								<view>卡券状态</view>
								<view class="status" v-html="type=='edit'?cardInfo.first_card.status_label:cardInfo.status_label"></view>
							</view>

						</view>
					</view>
					<view class="orderInfo-status">
						<u-form-item label="提货时间" :border-bottom="false" style="width:100%" prop="send_date"
							label-position="left">
							<!-- <view></view> -->
							<view class="hh" @click="openDatePicker">
								<view class="" v-if="form.send_date">
									<view>{{form.express}}</view>
									<view>{{form.ymd}} <text style="color:#b62828;margin:0 10rpx">[{{form.week}}]</text>
										{{form.hh}}
									</view>
								</view>
								<view v-else>
									<view>选择提货时间</view>
								</view>
								<view>
									<u-icon name="arrow-down-fill" color="#ccc" size='28'></u-icon>
								</view>
							</view>
						</u-form-item>

					</view>
				</view>
				<view class="orderForm-wrap">
					<u-form-item label="收货人" prop="contact" label-position="left">
						<u-input v-model="form.contact" placeholder="请填写收货人姓名" />
					</u-form-item>
					<u-form-item label="手机号码" prop="mobile" label-position="left">
						<u-input v-model="form.mobile" placeholder="请填写手机号码" />
					</u-form-item>
					<u-form-item label="备用号码" prop="mobile2" label-position="left">
						<u-input v-model="form.mobile2" placeholder="请填写备用号码" />
					</u-form-item>
					<u-form-item label="所在地区" prop="area" label-position="left">
						<u-input v-model="form.area" placeholder="请选择所在地区" @click="openArea" />
						<view slot="right" class="arearight" @click="changeLocation">
							<u-icon name="map"></u-icon>
							定位
						</view>
					</u-form-item>
					<u-form-item label="详细地址" prop="address" label-position="left">
						<u-input v-model="form.address" placeholder="请填写详细地址" />
					</u-form-item>
					<u-form-item label="设置默认地址" :border-bottom="false" prop="defalut" label-position="left">
						<u-switch slot="right" v-model="form.defalut" active-color="#ba8b45" inactive-color="#adadac"
							size="40"></u-switch>
					</u-form-item>
				</view>
				<!-- 				<view class="orderForm-address">
					<text><text>*</text>收货地址</text>
					<u-button @click="changeLocation" size="mini">获取位置</u-button>
				</view> -->
				<view class="orderForm-wrap">
					<u-form-item label="是否本人收货" prop="myself" label-position="left">
						<u-input v-model="myself" placeholder="选填" @click="showIsMySelf = true" type="select" />
					</u-form-item>
					<u-form-item label="购买人姓名" prop="buy_name" label-position="left">
						<u-input v-model="form.buy_name" placeholder="选填" />
					</u-form-item>
					<u-form-item label="购买人电话" :border-bottom="false" prop="buy_mobile" label-position="left">
						<u-input v-model="form.buy_mobile" placeholder="选填" />
					</u-form-item>
				</view>

			</u-form>
			<view class="orderForm-btn">
				<view @click="submit">{{type=='edit'?'点击修改':'点击提货'}}</view>
			</view>
		</view>
		<aui-picker ref="pickers" :title="'地区选择'" :data="listArea" @callback="changeArea"></aui-picker>


		<u-select @confirm="changeIsMySelf" v-model="showIsMySelf" :list="listIsMySelf"></u-select>
		<!-- 确认信息 -->
		<view class="ordercontainer" v-if="showinfo">
			<view class="confirmbox">
				<view class="confirmpicinfo">
					<view class="imgbox">
						<image :src="cardInfo.sku?(cardInfo.sku.image_url?cardInfo.sku.image_url:require('@/static/logo-xietaitai.png')):require('@/static/logo-xietaitai.png')" mode="widthFix"></image>
					</view>
					<view class="pictitle">{{cardInfo.sku?cardInfo.sku.name:''}}</view>
					<text>{{cardInfo.sku?cardInfo.sku.specs:''}}</text>
				</view>
			</view>
			<view class="confirmlist index0">
				<view class="iconimg">
					<image src="../../static/icon1.png" mode="widthFix"></image>
				</view>
				<view class="confirmright">
					<text class="confirmmarker">收货日期</text>
					<view class="flex-li confirmdate">
						<text>{{form.ymd}}</text>
						<text class="smallfont">{{form.lunarData}}</text>
					</view>
					<view class="flex-li confirmdate">
						<text>{{form.hh}}</text>
						<text class="smallfont">[{{form.week}}]</text>
					</view>
				</view>
			</view>
			<view class="confirmlist index1">
				<view class="iconimg">
					<image src="../../static/icon2.png" mode="widthFix"></image>
				</view>
				<view class="confirmright">
					<text class="confirmmarker">收货地址</text>
					<view class="flex-li confirmaddress">
						<text>{{form.area}}{{form.address}}</text>
					</view>
				</view>
			</view>
			<view class="confirmlist index2">
				<view class="iconimg">
					<image src="../../static/icon3.png" mode="widthFix"></image>
				</view>
				<view class="confirmright">
					<text class="confirmmarker">收货人</text>
					<view class="flex-li confirmcontact">
						<text>{{form.contact}}</text>
						<text>{{form.mobile}}</text>
					</view>
				</view>
			</view>
			<view class="confirmbtn">
				<text class="edit" @click="backShow">返回修改</text>
				<text class="confirmtab" @click="submit">{{type=='edit'?'确认修改':'确认提货'}}</text>
			</view>
		</view>
		<!-- 选择地址 -->
		<view class="addressinfo" v-if="showAddress">
			<u-popup v-model="showAddress" mode="bottom">
				<view class="content">
					<view class="content-title">
						选择地址
					</view>
					<view class="content-wrap">
						<u-radio-group v-model="addressInfo" @change="changeAddress">
							<u-radio v-for="(item, index) in listAddress" :key="index" :name="item.id">
								<view class="content-contact">{{item.contact}} {{item.mobile}}</view>
								<view class="content-address">{{item.area}}{{item.address}}</view>
							</u-radio>
						</u-radio-group>
					</view>
				</view>
			</u-popup>


		</view>
	</view>
</template>

<script>
	import {
		toast,
		isMobile,
		isNull
	} from '@/common/util.js'
	import solarLunar from '@/node_modules/solarlunar';
	import auiPicker from '@/components/aui-picker.vue';
	import datePicker from '@/components/date-picker/date-picker.vue'
	export default {
		components: {
			auiPicker,
			datePicker
		},
		data() {
			return {
				showinfo: false,
				showAddress: false,
				listAddress: [],
				addressInfo: '',
				cardInfo: {},
				type:'',
				form: {
					card_number: '',
					password: '',

					send_date: '',
					ymd: '',
					lunarData: '',
					express: '',
					hh: '',
					week: '',

					area: '',
					address: '',
					province_id: '',
					city_id: '',
					district_id: '',
					contact: '',
					mobile: '',
					mobile2: '',
					defalut: false,
					myself: 1,
					buy_name: '',
					buy_mobile: ''
				},
				listExpress: [{
					id: 0,
					value: '顺丰快递'
				}, {
					id: 1,
					value: '中通快递'
				}],
				listDates: [],
				date: '',
				listArea: [],
				showArea: false,
				showIsMySelf: false,
				myself: '是',
				listIsMySelf: [{
					value: 1,
					label: '是'
				}, {
					value: 0,
					label: '否'
				}],
				rules: {
					send_date: [{
						required: true,
						message: '请选择提货时间',
						trigger: ['change', 'blur'],
					}],
					area: [{
						required: true,
						message: '请选择收货地址',
						trigger: ['change', 'blur'],
					}],
					address: [{
						required: true,
						message: '请填写详细地址',
						trigger: ['blur'],
					}],
					contact: [{
						required: true,
						message: '请填写收货人姓名',
						trigger: ['blur'],
					}],
					mobile: [{
						required: true,
						message: '请填写收货人电话',
						trigger: ['blur'],
					}, {
						validator: (rule, value, callback) => {
							return this.$u.test.mobile(value);
						},
						message: '手机号码不正确',
						trigger: ['blur'],
					}]
				}
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);

		},
		onLoad(option) {
			let that = this
			if (option.hasCard) {
				if(option.type=='edit'){
					this.type = 'edit'
					this.form = uni.getStorageSync("vuex_update_card") ? uni.getStorageSync("vuex_update_card") : {},
					this.cardInfo = uni.getStorageSync("vuex_update_card") ? uni.getStorageSync("vuex_update_card") : {},
					this.form.ymd = this.momentDay(this.form.send_date).ymd
					uni.removeStorageSync("vuex_update_card")
					uni.setNavigationBarTitle({
						title: '修改订单',
						success: function() {
							console.log('标题设置成功');
							that.showinfo = false
						},
						fail: function(err) {
							console.error('标题设置失败', err);
						}
					});
					console.log("this.form",this.form)
					// uni.removeStorageSync("vuex_update_card")
				}else{
					this.cardInfo = uni.getStorageSync("vuex_card") ? uni.getStorageSync("vuex_card").card : {}
					this.form.card_number = uni.getStorageSync("vuex_card") ? uni.getStorageSync("vuex_card").card_number : ''
					this.form.password = uni.getStorageSync("vuex_card") ? uni.getStorageSync("vuex_card").password : ''
					uni.removeStorageSync("vuex_card")
				}
				
				this.getAddress()
				this.getDates()
				this.getExpress()
				this.getArea()
			} else {
				toast("未查询到卡券信息")
				uni.removeStorageSync("vuex_card")
				uni.redirectTo({
					url: '/packages/change/change'
				})
			}
		},
		methods: {
			async getAddress() {
				const res = await this.$u.api.getUserAddress()
				this.listAddress = res.address
				if(!this.type == 'edit'){
					this.showAddress = this.listAddress.length > 0 ? true : false
				}
			},
			async getExpress() {
				const res = await this.$u.api.getExpress()
				this.listExpress = res
			},
			changeAddress(e) {
				console.log("e", e)
				if (e) {
					this.listAddress.map(item => {
						if (item.id == e) {
							this.form.address_id = item.id
							this.form.area = item.area
							this.form.address = item.address
							this.form.province_id = item.province_id
							this.form.city_id = item.city_id
							this.form.district_id = item.district_id
							this.form.contact = item.contact
							this.form.mobile = item.mobile
							this.showAddress = false
						}
					})
				}
			},

			async getDates() {
				await this.$u.api.getDates({
					card_number: this.form.card_number
				}).then(res => {
					let data = res.card
					if (data.open_dates) {
						for (var k in data.open_dates) {
							if (data.open_dates[k]['quantity'] - data.open_dates[k]['booked'] > 0) {
								let _k = this.momentDay(k)
								this.listDates.push({
									canUse: data.open_dates[k],
									..._k
								})
							}
						}
					}
				}).then(res => {

				})
			},
			momentDay(date) {
				if (date) {
					const weeks = ["周日", '周一', '周二', '周三', '周四', '周五', '周六', ]
					let dateArr = date.split("-")
					let ymd = this.$moment(date).format("M月DD日")
					let week = weeks[this.$moment(date).day()]
					const solar2lunarData = solarLunar.solar2lunar(dateArr[0], dateArr[1], dateArr[2]);

					return {
						date: date,
						ymd: ymd,
						week: week,
						lunarData: `农历${solar2lunarData.monthCn}${solar2lunarData.dayCn}`,
					}
				}

			},
			backDate(e) {
				console.log("e123", e)
				if (e) {
					this.form.send_date = e.date
					this.form.ymd = e.ymd
					this.form.express = e.expressname
					this.form.express_type_id = e.expressid
					this.form.hh = e.hhtime
					this.form.week = e.week
					this.form.lunarData = e.lunarData
				}
			},
			openDatePicker() {
				this.$refs.datePickers.show = true
			},
			async getArea() {
				const res = await this.$u.api.getRegion()
				this.listArea = res.regions

				console.log(res)
				console.log(this.listArea)
			},
			openArea() {
				this.$refs.pickers.open().then(function() {
					console.log('picker打开');
				});
			},
			changeArea(e) {
				console.log(e)
				// return
				if (e) {
					let data = e.data
					let _this = this
					data.forEach(function(item, index) {
						_this.form.area += item.value + '   ';
					});
					this.form.province_id = data[0] ? data[0].id : ''
					this.form.city_id = data[1] ? data[1].id : ''
					this.form.district_id = data[2] ? data[2].id : ''
					console.log(this.form)
					// this.form.area = e.province.label + e.city.label + e.area.label
					// this.$u.api.matchRegion({
					// 	province: e.province.label,
					// 	city: e.city.label,
					// 	district: e.area.label
					// }).then(res => {
					// 	this.form.province_id = res.province_id ? res.province_id.id : ''
					// 	this.form.city_id = res.city_id ? res.city_id.id : ''
					// 	this.form.district_id = res.district_id ? res.district_id.id : ''
					// })
				}
			},
			changeIsMySelf(e) {
				console.log(e)
				if (e) {
					this.myself = e[0].label
					this.form.myself = e[0].value
				}
			},
			changeLocation() {
				console.log("location")
				let _this = this
				uni.authorize({
					scope: 'scope.userLocation',
					success: (res) => {
						console.log("authorize", res)

						uni.chooseLocation({
							success(res) {
								console.log("res", res)
								_this.form.area = res.address
								_this.form.address = res.name
							},
							fail(res) {
								console.log("fail", res)

							}
						})
					},
					fail(res) {
						console.log("authorize-fail", res)
					}
				})
			},
			backShow() {
				let that = this
				uni.setNavigationBarTitle({
					title: '信息确认',
					success: function() {
						console.log('标题设置成功');
						that.showinfo = false
					},
					fail: function(err) {
						console.error('标题设置失败', err);
					}
				});
			},
			saveDefalutAddress() {
				if (this.form.defalut) {
					this.$u.api.saveUserAddress({
						id: this.form.address_id ? this.form.address_id : '',
						area: this.form.area,
						address: this.form.address,
						contact: this.form.contact,
						mobile: this.form.mobile,
						province_id: this.form.province_id,
						city_id: this.form.city_id,
						district_id: this.form.district_id,
						defalut: 1
					}).then(res => {
						if(this.type=='edit'){
							uni.redirectTo({
								url: '/packages/myorder/myorder'
							})
						}else{
							uni.redirectTo({
								url: '/packages/product/public'
							})
						}
						
					}).then(res => {
						if(this.type=='edit'){
							uni.redirectTo({
								url: '/packages/myorder/myorder'
							})
						}else{
							uni.redirectTo({
								url: '/packages/product/public'
							})
						}
					})
				} else {
					if(this.type=='edit'){
						uni.redirectTo({
							url: '/packages/myorder/myorder'
						})
					}else{
						uni.redirectTo({
							url: '/packages/product/public'
						})
					}
				}

			},
			submit() {
				let that = this
				if ((!isNull(this.form.mobile2) && this.form.mobile2.length > 0) || (!isNull(this.form.buy_mobile) && this
						.form.buy_mobile.length > 0)) {
					if (!isMobile(this.form.mobile2)) {
						toast('备用电话不正确')
						return
					}
					if (!isMobile(this.form.buy_mobile)) {
						toast('购买人电话不正确')
						return
					}
				}
				this.$refs.uForm.validate(valid => {
					// console.log('验证通过');
					if (valid) {
						if (!this.showinfo) {
							uni.setNavigationBarTitle({
								title: '信息确认',
								success: function() {
									console.log('标题设置成功');
									that.showinfo = true
								},
								fail: function(err) {
									console.error('标题设置失败', err);
								}
							});
						} else {
							this.form.show = 0
							if(this.type=='edit'){
								console.log("this.form",this.form)
								// return
								this.$u.api.saveUserOrder(this.form).then(res => {
									uni.removeStorageSync('vuex_update_card')
									toast(res.msg, 1000, function() {
										setTimeout(function() {
											that.saveDefalutAddress()
										}, 500)
								
									})
								
								}).then(res => {
									console.log('res1', res)
								
								})
							}else{
								this.$u.api.addUserOrder(this.form).then(res => {
									console.log("res", res)
									uni.removeStorageSync('vuex_card')
									toast(res.msg, 1000, function() {
										setTimeout(function() {
											that.saveDefalutAddress()
										}, 500)
								
									})
								
								}).then(res => {
									console.log('res1', res)
								
								})
							}
							
						}

					} else {
						console.log('验证失败');
						// toast('请填写完整信息')
					}
				});
			}
		}

	}
</script>

<style lang="scss">
	.cotainer {
		padding: 30rpx;
		background-color: #f0efed;
		padding-bottom: 200rpx;

		.addressinfo {
			position: fixed;
			top: 0;
			right: 0;
			bottom: 0;
			left: 0;
			background: rgba(0, 0, 0, .5);
			z-index: 9999999;
			display: flex;
			align-items: center;
			justify-content: center;

			.content {
				width: 100%;
				height: 800rpx;
				// overflow: scroll;
				position: relative;

				&-wrap {
					box-sizing: border-box;
					background: #fff;
					border-radius: 20rpx;
					overflow: scroll;
					width: 100%;
					height: 650rpx;
					padding: 40rpx;
					padding-top: 0;
				}

				&-title {
					text-align: center;
					padding: 30rpx;
					font-size: 32rpx;

				}

				.u-radio {
					align-items: baseline;
					margin-bottom: 20rpx;
				}

				&-contact {}

				&-address {
					color: #ccc;
					line-height: 1.2;
					font-size: 28rpx;
				}
			}
		}


		.orderInfo {
			padding: 40rpx 24rpx;
			border-radius: 10rpx;
			background-color: #fff;
			font-size: 24rpx;
			color: #000;

			&-title {

				>view {
					font-size: 24rpx;
					font-weight: bolder;
					margin-bottom: 20rpx;
				}
			}

			&-info {
				display: flex;

				font-weight: normal;
				margin-bottom: 40rpx;

				image {
					width: 150rpx;
					height: 150rpx;
					border: 1px solid #ba8b45;
					border-radius: 10rpx;
					margin-right: 20rpx;
				}

				>view {
					&:last-child {
						width: calc(100% - 170rpx);

						>view {
							display: flex;
							justify-content: space-between;
							margin-bottom: 20rpx;

							.status {
								background-color: #ba8b45;
								color: #fff;
								padding: 5rpx 20rpx;
								border-radius: 10rpx;
							}

						}
					}

				}
			}

			&-status {
				display: flex;
				flex-wrap: wrap;
				justify-content: space-between;

				.u-form-item {
					padding: 0;

					.u-form-item__body {
						align-items: baseline;
					}
				}

				.hh {
					&:last-child {
						text-align: right;
						display: flex;
						align-items: center;
						justify-content: flex-end;

						>view {
							&:first-child {
								view {
									height: 50rpx;
									line-height: 50rpx;

									&:last-child {
										margin-bottom: 0rpx
									}
								}
							}

							&:last-child {
								margin-left: 20rpx
							}
						}
					}
				}
			}
		}

		.orderForm {
			&-wrap {
				padding: 40rpx 24rpx;
				border-radius: 10rpx;
				background-color: #fff;
				font-size: 24rpx;
				color: #000;
				margin-top: 24rpx;

				.u-form-item {
					padding-bottom: 0
				}

				.arearight {
					color: #000
				}
			}

			&-address {
				height: 72rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				line-height: 72rpx;
				padding-top: 20rpx;
				position: relative;

				text {
					text {
						position: absolute;
						left: -16rpx;
						vertical-align: middle;
						color: #fa3534;
						padding-top: 6rpx;
					}
				}
			}

			&-btn {
				background: #fff;
				position: fixed;
				bottom: 0;
				left: 0;
				width: 100%;
				padding: 40rpx;
				z-index: 9;

				>view {
					background-color: #ba8b45;
					color: #fff;
					border-radius: 40rpx;
					width: 60%;
					margin: 0 auto;
					height: 75rpx;
					text-align: center;
					line-height: 75rpx;
				}
			}
		}

		.ordercontainer {
			background: #f0efed;
			width: 100%;
			height: 100vh;
			padding: 42rpx 50rpx 300rpx;
			overflow-y: scroll;
			position: fixed;
			top: 0;
			right: 0;
			bottom: 0;
			left: 0;
			z-index: 9999999;
		}

		.confirmbox {
			width: 100%;
			padding-top: 22rpx;
			padding-bottom: 35rpx;
			background: url(../../static/confirmbg1.jpg) no-repeat center top;
			background-size: cover;
			border-radius: 10rpx;
			box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, .47);

		}

		.confirmpicinfo {
			text-align: center;
			font-size: 24rpx;
			color: #d5c7b5;
			line-height: 42rpx;
		}

		.imgbox {
			width: 307rpx;
			margin: 0 auto;
			border-radius: 10rpx;
			border: 1px solid #ba8b45;
			overflow: hidden;
			margin-bottom: 14rpx;
		}

		.imgbox image {
			width: 100%;
			height: auto;
			vertical-align: middle;
		}

		.confirmpicinfo .pictitle {
			color: #ba8b45;
		}

		.confirmlist {
			margin-top: 30rpx;
			border-radius: 10rpx;
			overflow: hidden;
			display: flex;
			align-items: center;
			justify-content: space-between;
			background-repeat: no-repeat;
			background-position: center top;
			background-size: cover;
			box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, .47);
			padding: 10rpx 10rpx 10rpx 20rpx;
		}

		.confirmlist.index0 {
			background-image: url(../../static/confirmbg2.jpg);
		}

		.confirmlist.index1 {
			background-image: url(../../static/confirmbg3.jpg);
		}

		.confirmlist.index2 {
			background-image: url(../../static/confirmbg4.jpg);
		}

		.confirmlist image {
			width: 62rpx;
			height: auto;
		}

		.confirmlist .confirmright {
			width: 550rpx;
			background: #fff;
			border-radius: 10rpx;
			padding: 45rpx 20rpx 25rpx;
		}

		.confirmmarker {
			display: block;
			font-size: 24rpx;
			color: #000;
			font-weight: bold;
			margin-bottom: 8rpx;
		}

		.flex-li {
			display: flex;
			justify-content: space-between;
			color: #000;
			font-size: 30rpx;
			line-height: 60rpx;
		}

		.confirmdate text.smallfont {
			font-size: 24rpx;
		}

		.confirmbtn {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;
			// height: 115rpx;

			display: flex;
			padding: 40rpx 0rpx;
			justify-content: space-between;
			background: #fff;
			align-items: center;
		}

		.confirmbtn text {
			display: inline-block;
			width: 284rpx;
			line-height: 74rpx;
			height: 74rpx;
			text-align: center;
			border-radius: 74rpx;
			border: 1rpx solid #d1d1d0;
			margin: 0 38rpx;
			font-size: 29rpx;
			color: #000;
		}

		.confirmbtn text.confirmtab {
			color: #fff;
			border: 1rpx solid #ba8b45;
			background: #ba8b45;
		}
	}
</style>