<template>
	<view class="f-detail column">
		<view class="column items-center justify-center q-mt-md" v-if="loading">
			<u-loading mode="circle" size="40"></u-loading>
			<view class="normal-label text-center q-mt-sm">正在加载信息</view>
		</view>
		<scroll-view v-if="flight && !loading" scroll-y="true" class="col" style="height: 1px;">
			<view class="flight-card">
				<view class="row items-center" @click="goVisible=!goVisible">
					<view class="flight-status">去程</view>
					<view class="city bold">{{goList[0].DepartureName}}</view>
					<u-icon name='qianwangx' custom-prefix="tffont" color="#00000033" size="28"></u-icon>
					<view class="city bold">{{goList[goList.length-1].ArrivalCityName}}</view>
					<view class="col row" style="font-size: 14px;justify-content: flex-end;">
						<text>{{goList[0].FlightDate.split('-').splice(1,2).join('-')}} {{getWeeks(goList[0].FlightDate)}} {{goList[0].Departure_time}}</text>
						<u-icon class="q-ml-sm" name='arrow_down' custom-prefix="tffont" color="#00000066"
							size="32"></u-icon>
					</view>
				</view>
				<view class="q-mt-md" style="padding: 32rpx 0;" v-if="goVisible">
					<flight :value="goList" :show-title="false"></flight>
				</view>
			</view>
			<view class="flight-card">
				<view class="row items-center" @click="backVisible=!backVisible">
					<view class="flight-status">回程</view>
					<view class="city bold">{{backList[0].DepartureName}}</view>
					<u-icon name='qianwangx' custom-prefix="tffont" color="#00000033" size="28"></u-icon>
					<view class="city bold">{{backList[goList.length-1].ArrivalCityName}}</view>
					<view class="col row" style="font-size: 14px;justify-content: flex-end;">
						<text>{{backList[0].FlightDate.split('-').splice(1,2).join('-')}} {{getWeeks(backList[0].FlightDate)}} {{backList[0].Departure_time}}</text>
						<u-icon class="q-ml-sm" name='arrow_down' custom-prefix="tffont" color="#00000066"
							size="32"></u-icon>
					</view>
				</view>
				<view class="q-mt-md" style="padding: 32rpx 0;" v-if="backVisible">
					<flight :value="backList" :show-title="false"></flight>
				</view>
			</view>
			
			<view class="flight-card q-mt-md">
				<view class="title">选择乘机人</view>
				<guest @change-visible="(val)=>statusVisible=val" :max-num="flight.B2BSellNum" @selected="guestChangeHandle"></guest>
				<u-field
					v-model="contactName"
					label="联系人"
					placeholder="联系人名称"
					padding="20rpx 28rpx"
					:borderBottom="true"
					required>
				</u-field>
				<u-field
					v-model="contactPhone"
					label="联系电话"
					placeholder="请填写电话"
					padding="20rpx 28rpx"
					:borderBottom="true"
					required>
				</u-field>
			</view>
			
			<view class="flight-card q-mt-md" v-if="sales.length>1">
				<view class="title">服务专员</view>
				<u-field
					v-model="createBy.EmName"
					label="服务专员"
					placeholder="请选择服务专员"
					padding="20rpx 28rpx"
					right-icon="arrow-down"
					:disabled="true"
					@click="saleVisable=true"
					required>
				</u-field>
			</view>
			
			<view class="flight-card q-mt-md">
				<view class="title">
					<text>优惠券</text>
				</view>
				<view class="q-mt-md row items-center">
					<view style="font-size: 12px;width:1px;flex:1">请选择优惠券</view>
					<view style="display: flex;align-items: center;">
						<text style="color:#F20707;font-size: 12px;" @click="showCouponHandler">
							<text style="flex: 1;"
								v-if="useCouponId == 0 &&couponList.length>0">{{couponList.length}}张可用优惠券</text>
							<text class="content" style="color:grey" v-else-if="couponList.length==0">暂无优惠券</text>
							<text class="content" v-else :style="{ color: mainColor }">已优惠 {{currentCoupon.discountMoney}} 元</text>
						</text>
						<u-icon name="arrow" :size="32" color="#111" v-if="couponList.length>0"></u-icon>
					</view>
				</view>
			</view>
			
			<view class="flight-card q-mt-md">
				<view class="title">
					<text>订单金额</text>
				</view>
				<view class="form-items q-mt-md">
					<view class="label"> 在线支付 </view>
					<view class="val f14 regular" style="text-align: right">
						<text style="margin-right: 30rpx">{{ guest.length }}人</text>
						<text class="red">￥{{ price }}</text>
					</view>
				</view>
				<view class="form-items" style="border-bottom: none">
					<view class="label"> 明细 </view>
				</view>
				<view v-if="crCount>0" class="row items-center price-list-details">
					<view class="col">
						<text style="margin-right: 30rpx">成人</text>
					</view>
					<view>{{ crCount }}人 × ¥
						<!-- #ifdef MP-DI-->
							{{flight.B2CPrice}}
						<!-- #endif-->
						<!-- #ifdef MP-AG-->
							{{flight.B2BPrice}}
						<!-- #endif -->
					</view>
				</view>
				<view v-if="etCount>0" class="row items-center price-list-details">
					<view class="col">
						<text style="margin-right: 30rpx">儿童</text>
					</view>
					<view>{{ etCount }}人 × ¥
						<!-- #ifdef MP-DI-->
							{{flight.B2CPrice}}
						<!-- #endif-->
						<!-- #ifdef MP-AG-->
							{{flight.B2BPrice}}
						<!-- #endif -->
					</view>
				</view>
				<view v-if="babyCount>0" class="row items-center price-list-details">
					<view class="col">
						<text style="margin-right: 30rpx">婴儿</text>
					</view>
					<view>{{ babyCount }}人 × ¥{{babyPrice}}</view>
				</view>
				<view v-if="useCouponId.length>0" class="row items-center price-list-details" :style="{color:mainColor}">
					<view class="col">
						<text style="margin-right: 30rpx">优惠券</text>
					</view>
					<view>-¥{{currentCoupon.discountMoney}}</view>
				</view>
				<view class="row items-center price-list-details">
					<view class="col">
						<text style="margin-right: 30rpx">合计</text>
					</view>
					<view>¥{{(price-currentCoupon.discountMoney>0?price-currentCoupon.discountMoney:0)}}</view>
				</view>
			</view>
		</scroll-view>
		<view class="order-box" v-if="flight && !loading && !statusVisible">
			<view class="flight-card  order-preview row items-center">
				<view class="col" style="color: #ff3166; font-weight: bold">
					<text style="font-size: 22rpx">¥</text>
					<text v-if="crCount+etCount+babyCount>0" style="font-size: 40rpx; margin: 0 20rpx 0 5rpx;font-family: nav-font;">
						{{(price-currentCoupon.discountMoney).toFixed(2)}}
					</text>
					<text style="font-size: 40rpx; margin: 0 20rpx 0 5rpx;font-family: nav-font;" v-else>--</text>
					<text style="color: #6e6e6e; font-size: 24rpx;font-family: microsoft yahei ui light;">共计{{ guest.length }}人</text>
				</view>
				<button class="jz_OrderReNow" @click="orderHandler" :disabled="submit" :loading="submit">
					立即预定
				</button>
			</view>
		</view>

		<coupon v-if="couponList.length > 0 && showCoupon" :price="price" :list="couponList" :current="useCouponId"
			@close="closeCouponHandler"></coupon>
		<u-picker mode="selector" v-model="saleVisable" @confirm="setSaleHandle" :default-selector="[0]" :range="sales" range-key="EmName"></u-picker>
		<u-modal :border-radius="16" @confirm="nativageToOrderHandle" title="订单提醒" content="订单创建成功,请您在6小时内完成付款,否则将会被取消." @cancel="navigatorToHomeHandle" v-model="successVisible" confirm-text='查看订单' cancel-text='返回首页' confirm-color='#DEBF7B' cancel-color='#080A09' :show-cancel-button="true"></u-modal>
	</view>
</template>

<script>
	import guest from './components/guest/index.vue'
	import coupon from '@/components/coupon/index';
	import Flight from './components/flight/Index.vue'
	export default {
		data() {
			return {
				id: 0,
				loading: false,
				flight: null,
				goList: [],
				backList: [],
				dateRangeValue: {
					type: 0,
					startDate: '',
					fuzzy: {
						fuzzyType: 0,
						fuzzyTypeName: '',
						weeks: [],
						dayRangStatus: false,
						dayRange: [4, 10]
					},
					formatStartDate: '任意时间出发'
				},
				chosenResult: [{
						type: 0,
						ID: 0,
						Name: '全部城市'
					},
					{
						type: 1,
						ID: 0,
						Name: '全部城市'
					}
				],
				parementers: {
					StartDate: '',
					EndDate: '',
					DepartCityId: 0,
					ArriveCityId: 0,
					AirLineID: 0,
					groupId: 2,
					TicketType: 2,
					StartPlayDay: 0,
					EndPlayDay: 0,
					WeekDay: ''
				},
				showCoupon: false,
				couponList: [],
				useCouponId: [],
				currentCoupon: {
					discountMoney: 0
				},
				customer: {},
				guest: [],
				mainColor: '',
				submit:false,
				contactName:'',
				contactPhone:'',
				successVisible:false,
				createBy:{
					EmName:'',
					CreateBy:0
				},
				sales:[],
				saleVisable:false,
				statusVisible:false,
				backVisible:false,
				goVisible:false
			}
		},
		components: {
			guest,
			coupon,
			Flight
		},
		computed: {
			price() {
				if (!this.flight) return 0
				let p = 0
				//#ifdef MP-DI
					p = this.flight.B2CPrice
				//#endif
				//#ifdef MP-AG
					p = this.flight.B2BPrice
				//#endif
				if (this.guest.length == 1) return p
				const f = this.guest.filter(x => x.year > 1).length
				const b = this.guest.filter(x => x.year < 2).length

				return (f * p) + (b * this.babyPrice)
			},
			babyPrice() {
				if (!this.flight) return 0
				let p = 0
				//#ifdef MP-DI
					p = this.flight.B2CPrice
				//#endif
				//#ifdef MP-AG
					p = this.flight.B2BPrice
				//#endif
				let bp = this.flight.BabyPrecent
				bp = bp && bp != '' ? (parseFloat(bp) / 100.00) : 0

				return Math.ceil(bp * p)
			},
			crCount() {
				const r = this.guest.filter(x => x.year >= 12 && x.Checked)
				return r.length
			},
			etCount() {
				const r = this.guest.filter(x => x.year >= 2 && x.year < 12 && x.Checked)
				return r.length
			},
			babyCount() {
				const r = this.guest.filter(x => x.year < 2 && x.Checked)
				return r.length
			},
		},
		onLoad(options) {
			if (options.id && uni.getStorageSync('scf')) {
				this.id = options.id

				uni.setNavigationBarColor({
					backgroundColor: '#DEBF7B',
					frontColor: '#000000'
				})
				const s = uni.getStorageSync('scf')
				this.dateRangeValue = s.dateRange
				this.chosenResult = s.cities
				this.getTopLowTicketHandle()

				return
			}
			this.navigatorToHomeHandle()
		},
		created() {
			this.mainColor = this.$uiConfig.mainColor
			this.customer = uni.getStorageSync("b2b_user");
			this.getUserCouponList()
			// #ifdef MP-DI
				this.createBy.CreateBy = this.customer.pid
			// #endif
			// #ifdef MP-AG
				this.getSalesHandle()
			// #endif
		},
		methods: {
			getSalesHandle(){
				const p = { CustomerId: this.customer.customerId }
				this.apipost( "b2b_get_GetCustomerCreateByList", p,(res) => {
					if (res.resultCode == 1) {
						this.sales = res.data
						if(this.sales.length==1) this.createBy=this.sales[0]
					}
				},(err) => {
					
				});
			},
			setSaleHandle(val){
				this.createBy=this.sales[val[0]]
			},
			nativageToOrderHandle(){
				uni.redirectTo({
					url:'/pages/airTicket/TicketOrderList'
				})
			},
			orderHandler(){
				if(this.submit) return
				const error = this.validate()
				if(error!=''){
					uni.showToast({
						icon:'none',
						title:error
					})
					return
				}
				this.submit=true
				const p = this.createParameter()
				this.apipost('sellorder_post_SetOrderInfoForAirTicket',p,r=>{
					if(r.resultCode==1){
						this.successVisible=true
					}else{
						uni.showToast({
							icon:'error',
							title: r.message
						})
					}
					this.submit=false
				},e=>{
					this.submit=false
				})
			},
			validate(){
				let msg = ''
				if(this.crCount+this.etCount+this.babyCount==0){
					msg = '请选择乘机人'
				} else if(this.crCount+this.etCount>this.flight.B2BSellNum){
					msg = '机位数不足'
				} else if(this.crCount==0){
					msg = '不支持儿童或婴儿单独出游'
				} else if(this.price-this.currentCoupon.discountMoney<=0){
					msg = '机票价格异常，无法生成订单'
				} else if(this.contactName==''){
					msg = '请输入联系人名称'
				} else if(this.contactPhone=='' || this.contactPhone.length!=11){
					msg = '请输入11位联系电话'
				} else if(this.createBy.CreateBy==0){
					msg = '请选择与你对接的服务人员'
				}
				return msg
			},
			createParameter(){
				const mallUser = uni.getStorageSync('mall_UserInfo')
				const list = this.guest.map(x=>{
					const n = {
						SurName:x.SurName,
						Name:x.GivenName,
						Sex:x.Sex=='M'?1:2,
						PassportNo:x.Passport,
						PassportExpiry:x.PassportExpired,
						Birthday:x.BrithDay,
						MobilePhone:x.Mobile,
						Nationality:x.CountryId
					}
					return n
				})
				let PriceNum = 0
				//#ifdef MP-DI
					PriceNum = this.flight.B2CPrice
				//#endif
				//#ifdef MP-AG
					PriceNum = this.flight.B2CPrice
				//#endif
				const p = {
					OrderId:0,
					TCID:this.id,
					CustomerType:2,
					GroupType:5,
					ContactName:this.contactName,
					ContactMobile:this.contactPhone,
					CustomerId:this.customer.customerId,
					OrderSource:5,
					Unit_Price:PriceNum,
					TC_Price:PriceNum,
					CouponAllotIds:this.useCouponId.join(','),
					ManNum:this.crCount,
					ChirdNum:this.etCount,
					ChirdNeedBedNum:this.etCount,
					BabyNum:this.babyCount,
					PreferPrice:this.price,
					YSeatNum:this.crCount+this.etCount,
					GuestNum:this.crCount+this.etCount+this.babyCount,
					PlaceOrderFrom:2,
					MiniAppUserId:mallUser.UserId,
					DirectCustomerId:0,
					EnterID:0,
					GuestList:list,
					CreateBy:this.createBy.CreateBy
				}
				return p
			},
			showCouponHandler() {
				this.showCoupon = this.couponList.length > 0;
			},
			guestChangeHandle(val) {
				this.guest = val ? val : []
			},
			closeCouponHandler(e) {
				this.useCouponId = []
				this.currentCoupon.discountMoney = 0
				if (e != -1) {
					this.useCouponId = e;
					if (this.useCouponId.length>0) {
						const cp = this.couponList.filter(x=>this.useCouponId.indexOf(x.id)!=-1)
						
						if(cp.length>0){
							cp.forEach(x=>{
								if (x.couponsType == 1) {
									this.currentCoupon.discountMoney += x.denomination
								} else {
									this.currentCoupon.discountMoney += parseFloat((parseFloat(this.price) * (1 - parseFloat(x.denomination / 10))).toFixed(2))
								}
							})
						}
					}
				}
				this.showCoupon = false;
			},
			getUserCouponList() {
				let couponParams = {
					"lineId": 0,
					"lineteamId": 0,
					"userId": this.customer.accountId,
					"CouponsUseScope": 4,
					"isExpansion": 0,
					"CustomerType": 0,
					"TCID": 0,
				}
				this.apipost(
					"coupon_post_GetUserCanUseCouponList", couponParams,
					(res) => {
						console.log("coupon_post_GetUserCanUseCouponList", res);
						if (res.resultCode == 1) {
							this.couponList = res.data
							this.calcPzCouponHandler()
						}
					},
					(err) => {}
				);
			},
			usePzCouponHandler() {
				this.showPz = false
				this.closeCouponHandler(this.pzCoupon.id)
				this.pzCoupon = null
			},
			calcPzCouponHandler() {
				this.couponList.forEach((x) => {
					if (x.expansionModel.denomination > 0) {
						if (this.pzCoupon && this.pzCoupon.expansionModel.denomination < x.expansionModel
							.denomination)
							this.pzCoupon = x
						else
							this.pzCoupon = x

						x.realDenomination = x.denomination
						x.denomination = x.expansionModel.denomination
					}
				})
				this.showPz = this.pzCoupon ? true : false
			},
			navigatorToHomeHandle() {
				uni.redirectTo({
					url: '/pages/index/index'
				})
			},
			getTopLowTicketHandle() {
				this.resolveParameterHanle()
				this.lowData = []
				this.loading = true
				this.apipost('AirTicket_get_GetTopTicketProduct', this.parementers, (r) => {
					if (r.resultCode == 1) {
						this.resolveTicketHandle(r.data)
					} else {
						this.navigatorToHomeHandle()
					}

					this.loading = false
				}, (e) => {
					this.loading = false
					this.navigatorToHomeHandle()
				})
			},
			resolveTicketHandle(data) {
				const t = data[0].TicketProductList.find(x => x.TCID == this.id)
				if (!t) {
					this.navigatorToHomeHandle()
					return
				}
				this.goList = t.FlightList.filter(x => x.FlightType == 1)
				this.backList = t.FlightList.filter(x => x.FlightType == 3)

				this.flight = t
				// const demo = {
				// 	g: this.goList,
				// 	b: this.backList,
				// 	f: this.flight
				// }
				// uni.setStorageSync('demo_flight', demo)
			},
			getWeeks(d) {
				const date = new Date(d)
				const weeks = ['日', '一', '二', '三', '四', '五', '六']
				return `周${weeks[date.getDay()]}`
			},
			resolveParameterHanle() {
				this.resetParameterHandle()
				this.parementers.DepartCityId = this.chosenResult[0].ID
				this.parementers.ArriveCityId = this.chosenResult[1].ID

				if (this.dateRangeValue.type == 1) {
					this.currentDate = this.formatDateHandle(start)
					this.filterDate.start = this.dateRangeValue.startDate
					this.filterDate.end = this.dateRangeValue.startDate
				} else {
					const d = this.resolveDateByFuzzyHandle(this.dateRangeValue.fuzzy.fuzzyType)
					this.parementers.StartDate = d[0]
					this.parementers.EndDate = d[1]
				}
			},
			resetParameterHandle() {
				this.currentDate = ''
				this.parementers = {
					StartDate: '',
					EndDate: '',
					DepartCityId: 0,
					ArriveCityId: 0,
					AirLineID: 0,
					groupId: 2,
					TicketType: 2,
					StartPlayDay: 0,
					EndPlayDay: 0,
					WeekDay: ''
				}
			},
			formatDateHandle(date) {
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2,'0')}-${String(date.getDate()).padStart(2,'0')}`
			},
			resolveDateByFuzzyHandle(t) {
				if (t == 0) return ['', '']
				let start = new Date();
				let end = new Date()
				if (t == -1) {
					start.setTime(start.getTime() + 3600 * 1000 * 24 * 1);
					end.setMonth(end.getMonth() + 1);
				} else if (t == -2) {
					start.setTime(start.getTime() + 3600 * 1000 * 24 * 1);
					end.setMonth(end.getMonth() + 3)
				} else {
					const currentDate = new Date()
					currentDate.setMonth(currentDate.getMonth() + t);
					const year = currentDate.getFullYear();
					const month = currentDate.getMonth();
					start = new Date(year, month, 1);
					end = new Date(year, month + 1, 0);
				}
				return [this.formatDateHandle(start), this.formatDateHandle(end)]
			},
		}
	}
</script>

<style>
	@import url('../../asset/css/flex.css');

	.f-detail {
		background-color: #F5F5F5;
		background-image: linear-gradient(180deg, #DEBF7B, #F5F5F5);
		background-size: 100% 900rpx;
		background-repeat: no-repeat;
		height: 100vh;
		width: 100vw;
		padding-top: 30rpx;
		
	}
	.f-detail .safeBottom{
		/* background-color: #f5f5f5; */
		padding-bottom: calc(156rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(156rpx + env(safe-area-inset-bottom));
	}
	.f-detail .flight-card {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 20rpx;
		margin: 30rpx;

	}

	.f-detail .flight-card .title {
		font-size: 32rpx;
		font-weight: bold;
		color: #080A09;
	}

	.f-detail .flight-card .flight-status {
		background: #E1C278;
		border-radius: 8rpx;
		font-size: 24rpx;
		color: #111111;
		font-weight: 400;
		padding: 7rpx 14rpx;
	}

	.f-detail .flight-card .city {
		width: 98rpx;
		margin: 0 12rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		color: #080A09;
	}

	.f-detail .flight-card .bold {
		font-size: 28rpx;
		font-weight: bold;
		line-height: 1;
	}

	.f-detail .f14 {
		font-size: 28rpx;
	}

	.f-detail .form-items {
		margin-bottom: 20rpx;
		display: flex;
		align-items: center;
		padding-bottom: 20rpx;
		border-bottom: 1px solid #f5f5f5;
		font-size: 28px;
		font-weight: 500;
	}

	.f-detail .form-items:last-child {
		border-bottom: none;
	}

	.f-detail .form-items .label {
		font-size: 28rpx;
		font-weight: 600;
		margin-right: 60rpx;
		flex-shrink: 0;
		width: 115rpx;
	}

	.f-detail .form-items .val {
		flex: 1;
	}

	.f-detail .price-list-details {
		margin-bottom: 40rpx;
		color: #999;
		font-size: 24rpx;
	}

	.f-detail .order-box {
		padding-top: 24rpx;
		padding-bottom: calc(constant(safe-area-inset-bottom));
		padding-bottom: calc(env(safe-area-inset-bottom));
		
		min-height: 156rpx;
		background: #F5F5F5;
	}
	.f-detail .order-box .order-preview{
		margin: 0 16px;
		padding: 10rpx;
		box-shadow: 0 0 40rpx #00000033;
		
	}
	.f-detail .jz_OrderReNow {
		height: 80rpx;
		background-color: #111111;
		text-align: center;
		line-height: 80rpx;
		color: #fff;
		font-weight: 600;
		font-size: 28rpx;
		border-radius: 16rpx;
	}

</style>