<template>
	<view style="height: 100vh;background-color: #F3F1EF;" class="flight-list column">
		<chosen-city :enable-all="false" :padding-top="`${barHeight}px`" @closed="resetCityVisible=false" @change="setNewCitiesHandle" :value="chosenResult" v-if="resetCityVisible"></chosen-city>
		<view class="nav-box row items-center" :style="{paddingTop:barHeight+'px',height:(barHeight+44)+'px'}">
			<view class="home-btn row items-center" @click="goBackHandle">
				<u-icon name="arrowleft" custom-prefix="tffont" color="#111" size="34"
					style="font-weight: bolder;"></u-icon>
			</view>
			<view class="home-btn row items-center" @click="goHomeHandle">
				<u-icon name="home_1" custom-prefix="tffont" color="#111" size="38"
					style="font-weight: bolder;"></u-icon>
			</view>
			<view class="title row items-center justify-center" @click="resetCityVisible=true">
				<text>{{chosenResult[0].Name}}</text>
				<view style="margin:0 20rpx">
					<u-icon name="wangfan1" custom-prefix="tffont" color="#00000066" size="36"></u-icon>
				</view>
				<text>{{chosenResult[1].Name}}</text>
				<u-icon class="q-ml-sm" name='arrow_down' custom-prefix="tffont" color="#00000066" size="32"></u-icon>
			</view>
		</view>
		<view class="column items-center justify-center q-mt-md" v-if="loadingLow">
			<u-loading mode="circle" size="40"></u-loading>
			<view class="normal-label text-center q-mt-sm">正在加载信息</view>
		</view>
		<view style="margin:10vh 0" class="text-center" v-else-if="lowData.length==0">
			<u-empty mode="data"></u-empty>
		</view>
		<template v-else>
			<view class="time-list row" style="padding:0 12rpx;">
				<scroll-view :scroll-left="scrollLeft" scroll-x class="col header-scroll" style="padding:12rpx 0;width:1px;">
					<view class="row items-center">
						<view class="time-item" :id="'a'+x.FlightDate.replaceAll('-','')" @click="flightDateChangeHandle(x.FlightDate)"
							:class="{'active':currentDate==x.FlightDate}" v-for="(x,i) in lowHeadData" :key="i">
							<view class="">{{x.FlightDate.split('-').splice(1,2).join('-')}}</view>
							<view style="margin: 10rpx 0;">{{x.WeekDayStr}}</view>
							<view class="">¥{{x.B2BPrice}}</view>
						</view>
					</view>
				</scroll-view>
				<view class="time-item more row items-center justify-center">
					<date-select @change="dateFilterChange" :default-value="[filterDate.start,filterDate.end]">
						<image src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Upload/Goods/638753835239709518.png" mode="widthFix" style="width: 30rpx;max-height: 60px;"></image>
					</date-select>
				</view>
			</view>
			<view class="filter-list">
				<view class="filter-items col" @click="sortChangeHandle(x.id)" :class="{'active':x.id==sortBy}" v-for="(x,i) in sortList" :key="i">{{x.name}}</view>
			</view>
			<scroll-view scroll-y="true" class="col" style="width: 100%;height: 1px;">
				<view style="padding:30rpx">
					<view class="flight-card" @click="nativageToOrderHandle(x.TCID)" v-for="(x,i) in flights">
						
						<view class="q-mt-md row items-start">
							<view class="col">
								<view class="first-blond">
									<view class="row items-start">
										<view class="flight-status">去程</view>
										<view class="flight-time">
											<view class="">{{x.GoFlightList[0].Departure_time}}</view>
											<view class="thin">{{x.GoFlightList[0].dName.replaceAll('国际机场','').replaceAll('机场','')}}</view>
										</view>
										<view class="used-time column col">
											<view class="how-time row items-center justify-center">
												<text>{{x.DepartureTime.Days*24+x.DepartureTime.Hours}}h {{x.DepartureTime.Minutes}}m</text>
												<view class="other-status" v-if="x.GoFlightList.length>1">
													中转{{x.GoFlightList.length-1}}次
												</view>
											</view>
											<view class="line">&nbsp;</view>
											<view class="t-cities" v-if="x.GoFlightList.length>1">
												<template v-for="(c,ci) in x.BackFlightList">
													<text :key="ci" v-if="ci>0" style="margin-right: 6rpx;">{{c.DepartureName}}</text>
												</template>
											</view>
										</view>
										<view class="flight-time">
											<view class="day-diff" v-if="x.GoDiffDay!=0">
												{{`${x.GoDiffDay>0?'+':''}${x.GoDiffDay}`}}天
											</view>
											<view class="">{{x.GoFlightList[x.GoFlightList.length-1].Arrival_time}}</view>
											<view class="thin">{{x.GoFlightList[x.GoFlightList.length-1].aName.replaceAll('国际机场','').replaceAll('机场','')}}</view>
										</view>
									</view>
									<view class="q-mt-md row items-center">
										<view class="row items-center" v-for="(a,ai) in x.GoFlightList">
											<view class="login-box">
												<image :src="`https://static.tripcdn.com/packages/flight/airline-logo/latest/airline/48/${a.AlCode}.png`" mode="widthFix"></image>
											</view>
											<text class="login-text">{{a.Flight_number}} </text>
										</view>
									</view>
								</view>
								<view class="second-blond" style="margin-top: 62rpx;">
									<view class="row items-start">
										<view class="flight-status">回程</view>
										<view class="flight-time">
											<view class="">{{x.BackFlightList[0].Departure_time}}</view>
											<view class="thin">{{x.BackFlightList[0].dName.replaceAll('国际机场','').replaceAll('机场','')}}</view>
										</view>
										<view class="used-time column col">
											<view class="how-time row items-center justify-center">
												<text>{{x.ArrivalTime.Days*24+x.ArrivalTime.Hours}}h {{x.ArrivalTime.Minutes}}m</text>
												<view class="other-status" v-if="x.BackFlightList.length>1">
													中转{{x.BackFlightList.length-1}}次
												</view>
											</view>
											<view class="line">&nbsp;</view>
											<view class="t-cities" v-if="x.BackFlightList.length>1">
												<template v-for="(c,ci) in x.BackFlightList">
													<text v-if="ci>0" :key="ci" style="margin-right: 6rpx;">{{c.DepartureName}}</text>
												</template>
											</view>
										</view>
										<view class="flight-time">
											<view class="day-diff" v-if="x.BackDiffDay!=0">
												{{`${x.BackDiffDay>0?'+':''}${x.BackDiffDay}`}}天
											</view>
											<view class="">{{x.BackFlightList[x.BackFlightList.length-1].Arrival_time}}</view>
											<view class="thin">{{x.BackFlightList[x.BackFlightList.length-1].aName.replaceAll('国际机场','').replaceAll('机场','')}}</view>
										</view>
									</view>
									<view class="q-mt-md row items-center">
										<view class="row items-center" v-for="(a,ai) in x.BackFlightList">
											<view class="login-box">
												<image :src="`https://static.tripcdn.com/packages/flight/airline-logo/latest/airline/48/${a.AlCode}.png`" mode="widthFix"></image>
											</view>
											<text class="login-text">{{a.Flight_number}} </text>
										</view>
									</view>
								</view>
							</view>
							<view>
								<view class="price">
									<text>¥</text>
									<text class="big">{{x.B2BPrice}}</text>
								</view>
								<view class="num row items-center">
									<text style="padding: 6rpx;">剩余</text>
									<text class="col text-center" style="padding:6rpx;background-color: #B99846;">{{x.B2BSellNum}}张</text>
								</view>
								<view  class="text-center buy-button">预定</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</template>
		
	</view>
</template>

<script>
	import DateSelect from '../components/time/DateSelect.vue';
	import ChosenCity from '../components/address/ChosenCity.vue';
	export default {
		data() {
			return {
				barHeight: 0,
				currentDate: '',
				lowData: [],
				lowHeadData: [],
				dateRangeValue: {
					type: 0,
					startDate: '',
					fuzzy: {
						fuzzyType: 0,
						fuzzyTypeName: '',
						weeks: [],
						dayRangStatus: false,
						dayRange: [4, 10]
					},
					formatStartDate: '任意时间出发'
				},
				resetCityVisible:false,
				chosenResult: [{
						type: 0,
						ID: 0,
						Name: '全部城市'
					},
					{
						type: 1,
						ID: 0,
						Name: '全部城市'
					}
				],
				loadingLow: false,
				parementers: {
					StartDate: '',
					EndDate: '',
					DepartCityId: 0,
					ArriveCityId: 0,
					AirLineID: 0,
					groupId: 2,
					TicketType: 2,
					StartPlayDay: 0,
					EndPlayDay: 0,
					WeekDay: ''
				},
				sortBy:0,
				scrollLeft:0,
				sortList:[
					{id:0,name:'更早起飞'},
					{id:1,name:'耗时更短'},
					{id:2,name:'价格更低'},
					{id:3,name:'仅看直飞'}
				],
				filterDate:{
					start:'',
					end:''
				}
			}
		},
		components:{DateSelect,ChosenCity},
		computed: {
			flights() {
				if(this.currentDate=='') return []
				let filteredFlights = this.lowData.filter(flight => flight.FlightDate === this.currentDate);
				return this.applySorting(filteredFlights);
			}
		},
		created() {
			if (uni.getStorageSync('scf')) {
				const s = uni.getStorageSync('scf')
				this.dateRangeValue = s.dateRange
				this.chosenResult = s.cities
			}
			this.chosenResult.sort((a, b) => {
				return a.type - b.type;
			});
			this.getTopLowTicketHandle()
		},
		onLoad(options) {
			if(options.dv){
				this.currentDate = decodeURIComponent(options.dv)
			}
		},
		mounted() {
			let that = this
			uni.getSystemInfo({
				success(r) {
					that.barHeight = r.statusBarHeight
				},
			});
		},
		methods: {
			nativageToOrderHandle(id){
				uni.navigateTo({
					url:'/pages/airTicket/flightDetail?id='+id
				})
			},
			applySorting(flights) {
			    switch (this.sortBy) {
			      case 0:
			        return flights.sort((a, b) => new Date(`${a.FlightDate} ${a.FlightList[0].Departure_time}`) - new Date(`${b.FlightDate} ${b.FlightList[0].Departure_time}`));
			      case 1:
			        return flights.sort((a, b) => this.getFlightDuration(a) - this.getFlightDuration(b));
			      case 2:
			        return flights.sort((a, b) => a.B2BPrice - b.B2BPrice);
			      case 3:
			        return flights.filter(flight => flight.GoFlightList.length === 1 && flight.BackFlightList.length === 1);
			      default:
			        return flights;
			    }
			  },
			  getFlightDuration(flight) {
			    const duration = (flight.DepartureTime.Days * 24 * 60) + (flight.DepartureTime.Hours * 60) + flight.DepartureTime.Minutes;
			    return duration;
			  },
			centerSelectedItem() {
				if (!this.currentDate || this.currentDate === '') return;
				const i = this.lowHeadData.findIndex(x => x.FlightDate === this.currentDate);
				let targetScrollLeft = 0;
				if (i >= 3) {
					targetScrollLeft = (i - 2) * 76;
				}
				const duration = 500; // 滚动时长，单位为毫秒
				const startScrollLeft = this.scrollLeft;
				const distance = targetScrollLeft - startScrollLeft;
	
				const animation = uni.createAnimation({
					duration: duration,
					timingFunction: 'ease-in-out'
				});
	
				let currentTime = 0;
				const interval = setInterval(() => {
					currentTime += 16; // 约 60fps
					if (currentTime >= duration) {
						clearInterval(interval);
						this.scrollLeft = targetScrollLeft;
					} else {
						const progress = currentTime / duration;
						this.scrollLeft = startScrollLeft + distance * this.easeInOutQuad(progress);
					}
				}, 16);
			},
			easeInOutQuad(t) {
				return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
			},
			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 = ''
					this.parementers.EndDate = ''
					this.filterDate.start=d[0]
					this.filterDate.end = d[1]
				}
			},
			resetParameterHandle() {
				this.currentDate = ''
				this.parementers = {
					StartDate: '',
					EndDate: '',
					DepartCityId: 0,
					ArriveCityId: 0,
					AirLineID: 0,
					groupId: 2,
					TicketType: 2,
					StartPlayDay: 0,
					EndPlayDay: 0,
					WeekDay: ''
				}
			},
			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);
				}
				this.currentDate = this.formatDateHandle(start)
				return [this.formatDateHandle(start), this.formatDateHandle(end)]
			},
			formatDateHandle(date) {
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2,'0')}-${String(date.getDate()).padStart(2,'0')}`
			},
			getTopLowTicketHandle() {
				this.resolveParameterHanle()
				this.lowData = []
				this.loadingLow = true
				this.apipost('AirTicket_get_GetTopTicketProduct', this.parementers, (r) => {
					if (r.resultCode == 1) {
						this.lowData = this.formatLowData(r.data)
					}
					this.centerSelectedItem()
					this.loadingLow = false
				}, (e) => {
					this.loadingLow = false
				})
			},
			formatLowData(d) {
				if (!d || d.length == 0) return []
				const list = d[0].TicketProductList
				list.sort((a, b) => {
					return new Date(a.FlightDate) - new Date(b.FlightDate);
				})
				list.forEach(x=>{
					x.GoFlightList = x.FlightList.filter(f=>f.FlightType==1)
					x.BackFlightList = x.FlightList.filter(f=>f.FlightType==3)
					
					const go = x.GoFlightList[0]
					const back = x.BackFlightList[0]
					x.GoDiffDay = this.resolveDiffDayHandle(`${go.FlightDate} ${go.Departure_time}`,go.DepartureUTCZone,go.ArrivalCityUTCZone,x.DepartureTime)
					x.BackDiffDay = this.resolveDiffDayHandle(`${back.FlightDate} ${back.Departure_time}`,back.DepartureUTCZone,back.ArrivalCityUTCZone,x.ArrivalTime)
				})
				this.lowHeadData =this.foramtHeaderListHandle(list)
				if(this.lowHeadData.findIndex(x=>x.FlightDate==this.currentDate)==-1){
					this.currentDate = this.lowHeadData[0].FlightDate
				}
				return list
			},
			foramtHeaderListHandle(list){
				const d = list.filter(x=>{
					const td = new Date(x.FlightDate)
					const max = new Date()
					let flag = true
					if(this.filterDate.start!=''){
						flag = td>=new Date(this.filterDate.start)
					}
					if(this.filterDate.end!='' && flag){
						flag = td<=new Date(this.filterDate.end)
					}
					return flag
				})
				const result = d.reduce((acc, item) => {
				    const groupValue = item.FlightDate;
				    const currentPrice = item.B2BPrice;
				
				    if (!acc[groupValue]) {
				        acc[groupValue] = {
				            FlightDate: groupValue,
				            B2BPrice: currentPrice,
				            WeekDayStr: item.WeekDayStr
				        };
				    } else {
				        acc[groupValue].B2BPrice = Math.min(acc[groupValue].B2BPrice, currentPrice);
				    }
				
				    return acc;
				}, {});
				
				const finalResult = Object.values(result);
				return finalResult
			},
			formatDateString(d) {
				const date = new Date(d)
				const weeks = ['日', '一', '二', '三', '四', '五', '六']

				return `${String(date.getMonth()+1).padStart(2,'0')}.${String(date.getDate()).padStart(2,'0')} 周${weeks[date.getDay()]}` //周${weeks[date.getDay()]}
			},
			goBackHandle() {
				uni.navigateBack(-1)
			},
			goHomeHandle() {
				uni.redirectTo({
					url: '/pages/index/index'
				})
			},
			flightDateChangeHandle(date){
				this.currentDate = date
				this.centerSelectedItem()
			},
			sortChangeHandle(id){
				this.sortBy = id
			},
			resolveDiffDayHandle(s,sz,ez,ti){
				const sDate = new Date(s)
				const sourceDate = new Date(s)
				sDate.setHours(sDate.getHours()+(ez-sz))
				sDate.setDate(sDate.getDate()+ti.Days)
				sDate.setHours(sDate.getHours()+ti.Hours)
				sDate.setMinutes(sDate.getMinutes()+ti.Minutes)
				sDate.setHours(0,0,0)
				sourceDate.setHours(0,0,0)
				return (((sDate.getTime()-sourceDate.getTime())/(24 * 60 * 60 * 1000)))
			},
			dateFilterChange(val){
				this.filterDate.start = val[0]
				this.filterDate.end = val[1]
				this.lowHeadData = this.foramtHeaderListHandle(this.lowData)
				
				if(this.lowHeadData.length>0&& this.lowHeadData.findIndex(x=>x.FlightDate==this.currentDate)==-1){
					this.currentDate = this.lowHeadData[0].FlightDate
				} else if(this.lowHeadData.length==0) this.currentDate=''
			},
			setNewCitiesHandle(val){
				this.chosenResult = val
				uni.setStorageSync('scf',{
					cities:this.chosenResult,
					dateRange: this.dateRangeValue
				})
				this.getTopLowTicketHandle()
				this.resetCityVisible = false
			},
		}
	}
</script>

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

	.nav-box {
		height: 44px;
		/* 这里的44px是示例高度，可根据实际设计调整 */
		line-height: 44px;
		background-color: #FFF;
		color: #fff;

		width: 100vw;
		padding-left: 30rpx;
		background-color: #d4b465;
	}

	.nav-box .home-btn {
		width: 60rpx;
		height: 60rpx;
		border-radius: 60rpx;
		/* border:2rpx solid #ccc; */
		display: flex;
		align-items: center;
		justify-content: center;

	}

	.nav-box .title {
		font-weight: bold;
		font-size: 32rpx;
		color: #080A09;
		text-align: center;
		width: calc(100vw - 140px);
	}
	.header-scroll{
		 transition: scroll-left 0.5s ease;
	}
	.time-list {
		background: linear-gradient(0, #eacf8d, #d4b465);
		width: 100%;
	}
	.time-list .time-item {
		padding: 22rpx 33rpx;
		font-size: 24rpx;
		color: #111;
		line-height: 1;
		text-align: center;
		border-radius: 16rpx;
		position: relative;
		min-width: 148rpx;
	}

	.time-list .time-item::after {
		position: absolute;
		display: block;
		right: 0;
		width: 1px;
		height: 60%;
		top: 20%;
		content: ' ';
		background-color: #FFFFFF33;
	}
	.time-list .time-item.more::before{
		position: absolute;
		left: -10rpx;
		width: 10rpx;
		top: 0;
		bottom: 0;
		background-image: url('https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Upload/Goods/638753830279837045.png');
		background-size: auto 100%;
		display: block;
		content: ' ';
	}
	.time-list .time-item.active {
		background-color: #e7d9b2;
		font-weight: bold;
		margin-left: -1px;
	}
	
	.time-list .time-item.active::after,
	.time-list .time-item:last-child::after {
		display: none;
	}
	
	.filter-list{
		background-color: #eacf8d;
		border-top: 1px solid #ffffff2b;
		display: flex;
		padding: 12rpx;
	}
	.filter-list .filter-items{
		/* background: #F5F5F5; */
		border-radius: 8rpx;
		padding:12rpx;
		font-size: 24rpx;
		color: #111111;
		margin-right: 12px;
		text-align: center;
	}
	.filter-list .filter-items:last-child{
		margin-right: 0;
	}
	.filter-list .filter-items.active{
		background-color: #e7d9b2;
	}
	.flight-card{
		background-color: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		
	}
	.flight-card .flight-status{
		background: #E1C278;
		border-radius: 8rpx;
		font-size: 24rpx;
		color: #111111;
		font-weight: 400;
		padding: 14rpx 4rpx;
		text-orientation: mixed;
		writing-mode: tb;
		
	}
	.flight-card .flight-time{
		font-weight: bold;
		font-size: 36rpx;
		color: #000000;
		line-height: 1;
		margin:0 20rpx;
		position: relative;
		
	}
	.flight-card .flight-time .day-diff{
		position: absolute;
		top: -35rpx;
		line-height: 1;
		font-size: 22rpx;
		color: #FF5858;
		left: 4rpx;
	}
	.flight-card .flight-time .thin{
		line-height: 1;
		margin-top: 16rpx;
		font-weight: 400;
		font-size: 22rpx;
		color: #000000;
		max-width: 45px;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	.flight-card .used-time{
		margin-top: -16rpx;
	}
	.flight-card .used-time .how-time{
		height: 24rpx;
		font-size: 20rpx;
		color: #9999A5;
	}
	.flight-card .used-time .other-status{
		background: #ECF1F4;
		border-radius: 4rpx;
		height: 24rpx;
		font-size: 18rpx;
		color: #111111;
		padding: 0 7rpx;
		margin-left: 14rpx;
		font-weight: 500;
	}
	.flight-card .used-time .line{
		height: 4rpx;
		background: #ECF1F4;
		position: relative;
		margin-top: 6rpx;
	}
	.flight-card .used-time .line::before,
	.flight-card .used-time .line::after{
		position: absolute;
		left: 0;
		top:-4rpx;
		width: 12rpx;
		height: 12rpx;
		border-radius: 12rpx;
		display: block;
		content: ' ';
		background: #ECF1F4;
	}
	.flight-card .used-time .line::after{
		left: unset;
		right: 0;
	}
	.flight-card .used-time .t-cities{
		font-size: 19rpx;
		color: #111111;
		margin-top: 8rpx;
		text-align: center;
	}
	.flight-card .login-box{
		background: #FFFFFF;
		border-radius: 50%;
		border: 1px solid #ECF1F4;
		width: 36rpx;
		height: 36rpx;
		text-align: center
	}
	.flight-card .login-box image{
		width: 26rpx;
		height: 26rpx;
	}
	.flight-card .login-text{
		font-size: 22rpx;
		color: #9999A5;
		margin-right: 36rpx;
		margin-left: 10rpx;
	}
	.flight-card .price{
		margin-left: 25rpx;
		color:#FF3166;
		font-weight: bold;
		font-size: 20rpx;
		line-height: 1;
	}
	.flight-card .price .big{
		font-size: 36rpx;
	}
	.flight-card .num{
		margin-top: 24rpx;
		border-radius: 7rpx;
		background-color: #080A09;
		font-size: 22rpx;
		font-weight: 400;
		color: #FFF;
		overflow: hidden;
		padding: 0;
		line-height: 1;
	}
	.flight-card .buy-button{
		background-color: #080A09;
		border-radius: 8rpx;
		height: 50rpx;
		line-height: 50rpx;
		color: #EEF1F4;
		text-align: center;
		margin-top: 16px;
		font-size: 25rpx;
		font-weight: 400;
	}
	/* .nav-box .home-btn:active{
		background-color: #ccc;
	} */
</style>