<template>
    <view class="bgF5 height100vh">
        <view class="airTicketDetailsBg airTicketDetailsBgF fixed height1057"></view>
        <scroll-view
        scroll-y="true"
        style="height: 100%; flex: 1; box-sizing: border-box"
        @scroll="scroll"
        >
        <NavigationHeader :title="title" :titleStyle="titleStyle"></NavigationHeader>
        <view class="PT123 PB260">
            <view class="row-ajc-n MT45 MB30 fz40 fontBold" v-if="NewDetailsList.length>0">
                <view>{{NewDetailsList[0].DepartureName}}</view>
                <img class="inlineblock ML50 MR50" mode="widthFix" style="width: 79rpx;height: 38rpx"
                    src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/1696990221000_663.png"/>
                <view>
                    {{NewDetailsList[0].FlightList[NewDetailsList[0].FlightList.length-1].ArrivalCityName}}
                </view>
            </view>
            <AirTicketDetails v-if="NewDetailsList.length>0" :DetailsList="NewDetailsList"></AirTicketDetails>
            <template v-if="orderMsg.Unit_Price>0&&B2BSellNum>0">
            <view class="PX50 MT20 MB30 row-aic-n">
                <img class="inlineblock MR10" mode="widthFix" style="width: 167rpx;height: 31rpx"
                    src="https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/1697021959000_719.png"/>
                <view class="fz26 color1D1D20 ML31" v-if="orderMsg.ManNum>0||orderMsg.BabyNum>0||orderMsg.ChirdNum>0">
                    <text>已选：
                        <!-- {{orderMsg.GuestNum}} <text class="fz22">人</text> -->
                    </text>
                    <text v-if="orderMsg.ManNum>0">{{orderMsg.ManNum}} <text class="fz22">成人</text></text>
                    <text class="ML30" v-if="orderMsg.BabyNum>0">{{orderMsg.BabyNum}} <text class="fz22">婴儿</text></text>
                    <text class="ML30" v-if="orderMsg.ChirdNum>0">{{orderMsg.ChirdNum}} <text class="fz22">儿童</text></text>
                </view>
            </view>
            <view class="PX50">
                <view class="airTicketDetailsAdd-box bgFFF">
                    <view class="PX4" v-if="GuestList.length>0">
                        <template v-for="(item,index) in GuestList">
                            <u-swipe-action
                            :index="index" :key="item.Id"
                            :options="options"
                            :show="item.show"
                            :auto-close="false"
                            @click="bindClick" 
                            @open="open">
                                <view>
                                    <view class="fz30 fontBold">{{item.SurName}}</view>
                                    <view class="fz26 color9999A5 MT25">
                                        <text>证件号</text>
                                        <text class="ML10">{{item.IdCard?item.IdCard:item.PassportNo}}</text>
                                    </view>
                                </view>
                            </u-swipe-action>
                            <view v-if="GuestList.length-1!=index" class="MB50"></view>
                        </template>
                        
                        <view class="height-line1 MT40 MB35"></view>
                        <view class="row-ajc-n MB70">
                            <text class="flexS fz30">联系电话</text>
                            <view class="airTicketDetailsAddMobile flexG ML30">
                                <input class="fz30" type="number" v-model="orderMsg.ContactMobile" placeholder="用于接收通知" />
                            </view>
                        </view>
                    </view>
                    <view v-if="B2BSellNum>=orderMsg.YSeatNum" class="airTicketDetailsAdd bgDEBF7B fz32 fontBold textCenter"
                    @click="AddPassengers">
                        添加乘机人
                    </view>
                    <view v-if="GuestList.length==0" class="MB255"></view>
                </view>
            </view>
            </template>
        </view>
        </scroll-view>
        <view class="airTicketDetailsFooter fixedFooter bgFFF fixed row-sb-n z-index2"
        v-if="orderMsg.Unit_Price>0&&B2BSellNum>0&&orderMsg.OrderId==0">
            <view class="row-aic-n">
                <text class="airTicketDetailsFooter-text fz32 relative">
                    <!-- 价格 -->
                    合计
                </text>
                <text class="airTicketDetailsFooter-text fz32 ML10 relative"> ¥ </text>
                <text class="ML10 fz52">
                    <!-- {{orderMsg.Unit_Price}} -->
                    {{orderMsg.PreferPrice}}
                </text>
                <text class="airTicketDetailsFooter-text fz26 ML10 relative" v-if="orderMsg.GuestNum>0">
                     共 {{orderMsg.GuestNum}} 人
                </text>
            </view>
            <view class="row-acje">
                <view class="airTicketDetailsFooter-order row-ajc-w fontBold" @click="SubmitOrder"
                :class="[
                loading
                ||!orderMsg.ManNum
                ||!orderMsg.ContactMobile
                ||orderMsg.ContactMobile.length>11
                ||11>orderMsg.ContactMobile.length?'bgF5':'bgDEBF7B']">
                    <text class="fz32">立即下单</text>
                </view>
            </view>
        </view>
    </view>
</template>
<script>
    import AirTicketHeader from "./components/airTicketHeader.vue";
    import NavigationHeader from "./components/NavigationHeader.vue";
    import AirTicketDetails from "./components/airTicketDetails.vue";
    import { gegerateDates,getBeforeDate,getDateWeek } from "./dates.js";
    export default {
        components: {
            AirTicketHeader,
            NavigationHeader,
            AirTicketDetails
        },
        data() {
            return {
                orderInfo: {},
                orderMsg:{
                    OrderId: 0,
                    TCID: 0,
                    CustomerId: 0,//同行Id
                    ManNum: 0,//成人
                    ChirdNum: 0,//儿童
                    BabyNum: 0,//婴儿
                    GuestNum: 0,//总人数
                    YSeatNum: 0,//经济舱
                    FSeatNum: 0,//头等舱
                    ESeatNum: 0,//商务舱
                    OrderSource: 5,
                    GroupType: 5,
                    Unit_Price: 0,
                    PreferPrice: 0,//应收
                    GuestList:[
                        // {SurName:'',PassportNo:'',IdCard:'',MobilePhone:''}
                    ],
                    ContactMobile: '',
                    PlaceOrderFrom: 2,
                    CreateBy: 0,//销售id
                },
                B2BSellNum: 0,
                BabyPrecent: 0,
                NewDetailsList:[],
                DetailsList:[],
                loading: false,
                Mobile: '',
                GuestList: [],
                topheight:0,
                titleStyle:{},
                boxOption: 0,
                title: '填写下单信息',
                isToken: false,
                U:{},
                Ub2b:{},
                options: [{
						text: '编辑',
						style: {
							backgroundColor: '#DEBF7B'
						}
					},
					{
						text: '删除',
						style: {
							backgroundColor: '#f5f5f5',
                            color:'#DEBF7B'
						}
					}
				],
                isOpened: 'right',
            }
        },
        onLoad(options){
            this.orderMsg.OrderId = options.OrderId?options.OrderId:0
            this.orderMsg.TCID = options.TCID
            this.orderMsg.Unit_Price = Number(options.Price)
            this.U = uni.getStorageSync("mall_UserInfo")
            this.Ub2b = uni.getStorageSync("b2b_user")
            if(this.U&&this.U.Token){
                this.isToken = true
            }
            if(this.Ub2b&&this.Ub2b.customerId){
                this.orderMsg.CreateBy = this.Ub2b.salesBaseInfo.employeeId
                this.orderMsg.CustomerId = this.Ub2b.customerId
            }
            this.getAirDetails()

            let that = this;
            uni.getSystemInfo({
                success(res) {
                    that.titleStyle = {
                        height: "45px",
                        paddingTop: `${res.statusBarHeight}px`,
                        opacity: 0,
                    };
                    that.topheight = 55+res.statusBarHeight
                },
            });
        },
        created() {
            
        },
        watch: {
            GuestList:{
                handler(newVal, oldval) {
                    this.orderMsg.GuestList = []
                    newVal.forEach(x=>{
                        let obj = {
                            SurName: x.SurName,
                            PassportNo: x.PassportNo,
                            IdCard: x.IdCard,
                            MobilePhone: x.MobilePhone
                        }
                        this.orderMsg.GuestList.push(obj)
                    })
                }
            },
            orderMsg:{
                handler(newVal, oldval) {

                },
                deep: true,
                immediate: true
            },
            "orderMsg.GuestNum":{
                handler(newVal, oldval) {
                    
                },
                deep: true,
                immediate: true
            },
            BabyPrecent:{
                handler(newVal, oldval) {
                    this.getPrice()
                },
                deep: true,
                immediate: true
            }
        },
        onShow() {
            this.getGuestList()
        },
        mounted() {
           
        },
        methods: {
            // 计算人数
            getGuestList(){
                let GuestList = uni.getStorageSync("GuestList")
                this.GuestList = GuestList?GuestList:[]
                let resultMan = this.GuestList.filter(x=>{
                    return x.GuestNum==1
                })
                let resultBab = this.GuestList.filter(x=>{
                    return x.GuestNum==2
                })
                this.orderMsg.ManNum = resultMan.length
                let BabyNum = resultBab.length
                this.orderMsg.GuestNum = this.orderMsg.ManNum+BabyNum
                let ChirdNum = this.orderMsg.ManNum-BabyNum
                if(ChirdNum<0){
                    this.orderMsg.ChirdNum = ChirdNum*-1
                }else{
                    this.orderMsg.ChirdNum = 0
                }
                this.orderMsg.BabyNum = BabyNum>0?(BabyNum-this.orderMsg.ChirdNum):0
                if(this.BabyPrecent>0){
                    this.getPrice()
                }
            },
            // 计算金额及座位
            getPrice(){
                this.orderMsg.PreferPrice = 0
                this.orderMsg.YSeatNum = 0
                let YSeatNum = this.orderMsg.ManNum
                let money = this.orderMsg.Unit_Price * this.orderMsg.ManNum;
                if(this.orderMsg.BabyNum>0||this.orderMsg.ChirdNum>0){
                    if(this.orderMsg.BabyNum>0) money += (this.orderMsg.Unit_Price * this.orderMsg.BabyNum)*(this.BabyPrecent/100)
                    if(this.orderMsg.ChirdNum>0) {
                        money += (this.orderMsg.Unit_Price*this.orderMsg.ChirdNum)*(50/100)
                        YSeatNum += this.orderMsg.ChirdNum
                    }
                }
                this.orderMsg.PreferPrice = money
                this.orderMsg.YSeatNum = YSeatNum
            },
            // 编辑删除
            bindClick(index,index1) {
                if(!index1){
                    uni.navigateTo({
                        url: `/pages/airTicket/AirplanePassengerAddEditing?editorIndex=${index}`
                    });
                }else{
                    this.GuestList.splice(index, 1)
                    uni.setStorageSync("GuestList",this.GuestList)
                    this.getGuestList()
                }
			},
            open(index) {
				// 先将正在被操作的swipeAction标记为打开状态，否则由于props的特性限制，
				// 原本为'false'，再次设置为'false'会无效
				this.GuestList[index].show = true;
				this.GuestList.map((val, idx) => {
					if(index != idx) this.GuestList[idx].show = false;
				})
				this.$forceUpdate();
			},
            SubmitOrder(){
                if(this.loading){
                    return
                }
                if(this.orderMsg.GuestList.length==0){
                    uni.showToast({
                        title: '添加乘机人',
                        icon: 'none',
                        mask: true
                    });
                    return
                }
                if(!this.orderMsg.ContactMobile||(this.orderMsg.ContactMobile.length>0&&this.orderMsg.ContactMobile.length!=11)){
                    uni.showToast({
                        title: '请输入正确联系电话',
                        icon: 'none',
                        mask: true
                    });
                    return
                }
                uni.showLoading({
                    title: "请稍等片刻...",
                })
                this.loading = true
                this.apipost("sellorder_post_SetOrderInfoForAirTicket",this.orderMsg,
                (res) => {
                    if(res.resultCode==1){
                        this.queren(res.data)
                    }
                },(err)=>{
                    this.loading = false
                    uni.hideLoading()
                })
            },
            //微信支付
            queren(OrderId) {
                let url = "/api/WeChatPay/GetTravlePayInfo";
                let DepartureName = this.NewDetailsList[0].DepartureName
                let ArrivalCityName = this.NewDetailsList[0].FlightList[this.NewDetailsList[0].FlightList.length-1].ArrivalCityName
                let FlightDate = this.NewDetailsList[0].FlightDate+'/'+this.NewDetailsList[0].Departure_time
                let GoodsName = `${DepartureName}-${ArrivalCityName}-${FlightDate}`;
                // GoodsName = GoodsName.slice(0, 10);
                this.request2(
                    {
                        url: url,
                        data: {
                            OrderId: OrderId,
                            GoodsName: GoodsName,
                            OrderPayType: 1,
                            OpenId: uni.getStorageSync("mall_UserInfo").OpenId,
                        },
                    },
                (res) => {
                    try{
                        this.orderInfo = JSON.parse(res.data);
                        // this.Pay(OrderId);
                        this.subscribeMsg(OrderId);
                    }catch(e){
                        uni.showToast({
                            title:'无法正常拉取微信支付，你可以稍后重试或联系销售人员线下转款',
                            icon:'none'
                        })
                    }
                },
                (err) => {
                    this.loading = false
                    uni.hideLoading()
                    console.log(err)
                });
            },
            subscribeMsg(OrderId) {
                const that = this;
                let tempObj = uni.getStorageSync("basedata")?.mall?.wechatmessage ?? [];
                let tmplIds = [];
                if (tempObj && tempObj.length > 0) {
                    tempObj.forEach((x) => {
                    if (x.Name == "下单成功提醒" || x.Name == "订单取消提醒") {
                        tmplIds.push(x.MessageId);
                    }
                    });
                }
                uni.requestSubscribeMessage({
                    tmplIds: tmplIds,
                    complete(res) {
                        that.Pay(OrderId);
                    },
                });
            },
            Pay(OrderId) {
                let that = this;
                uni.requestPayment({
                    provider: "wxpay",
                    timeStamp: this.orderInfo.timeStamp,
                    nonceStr: this.orderInfo.nonceStr,
                    package: this.orderInfo.package,
                    signType: this.orderInfo.signType,
                    paySign: this.orderInfo.sign,
                success: function (res) {
                    that.loading = false
                    uni.hideLoading()
                    console.log("success", res);
                    uni.showToast({
                        title: "支付成功",
                    });
                    uni.removeStorageSync("GuestList")
                    setTimeout(() => {
                        uni.redirectTo({
                            url:
                            "/pages/jiuzhai/paysuccess?PreferPrice=" +
                            that.orderMsg.PreferPrice +
                            "&isFrom=3",
                        });
                    }, 100);
                },
                fail: function (err) {
                    that.loading = false
                    uni.hideLoading()
                    console.log("fail:", err);
                    uni.showToast({
                        title: "支付失败",
                        icon: "none",
                    });
                    uni.removeStorageSync("GuestList")
                    setTimeout(() => {
                        uni.redirectTo({
                        url: "/pages/airTicket/TicketOrderList?orderState=1",
                        });
                    }, 100);
                },
                });
            },
            getAirDetails(){
                uni.showLoading()
                this.apipost("AirTicket_get_GetTicketDetails",{
                    TCID: this.orderMsg.TCID
                },
                (res) => {
                    if(res.resultCode==1){
                        this.B2BSellNum = res.data.B2BSellNum // 
                        this.BabyPrecent = Number(res.data.BabyPrecent) //婴儿 %费用
                        let that = this;
                        this.title = that.orderMsg.Unit_Price>0&&that.B2BSellNum>0?'填写下单信息':'机票信息'
                        let arr = function(list){
                            list.forEach(x => {
                                x.time = ''
                                x.week = ''
                                x.duration = ''
                                x.frequency = 0
                                x.show = true
                            });
                        }
                        arr(res.data.FlightList)
                        this.DetailsList = res.data.FlightList

                        let FlightListZ =this.DetailsList.filter(z=>{ 
                            return z.FlightSubType!=3
                        })
                        let FlightListZ2 = this.DetailsList.filter(z=>{ 
                            return z.FlightSubType==3
                        })

                        this.DetailsList.forEach((y,index)=>{
                            let date =  y.FlightDate.split('-')
                            y.time = `${date[1]}-${date[2]}`
                            y.week = getDateWeek(y.FlightDate)
                            if(index){
                                y.frequency = FlightListZ2.length-1
                                y.duration = `${y.ArrivalTime.Days>0?y.ArrivalTime.Days+'d ':''}${y.ArrivalTime.Hours>0?y.ArrivalTime.Hours+'h ':''}${y.ArrivalTime.Minutes>0?y.ArrivalTime.Minutes+'m ':''}`
                            }else{
                                y.frequency = FlightListZ.length-1
                                y.duration = `${y.DepartureTime.Days>0?y.DepartureTime.Days+'d ':''}${y.DepartureTime.Hours>0?y.DepartureTime.Hours+'h ':''}${y.DepartureTime.Minutes>0?y.DepartureTime.Minutes+'m ':''}`
                            }
                        })
                        
                        
                        
                       let FlightList = []
                       let NewFlightList = []
                       let FlightList2 = []
                       let NewFlightList2 = []
                       
                        for(let i=0;i<this.DetailsList.length;i++){
                            if(this.DetailsList[i].FlightSubType!=3){
                                FlightList.push(this.DetailsList[i])
                            }else{
                                FlightList2.push(this.DetailsList[i])
                                NewFlightList2.push(this.DetailsList[i]) 
                            }
                        }
                        NewFlightList = [FlightList[0],FlightList[FlightList.length-1]]
                        if(FlightList.length>0){
                            let obj = {
                                FlightList: FlightList,
                                NewFlightList: NewFlightList,
                                ...this.DetailsList[0],
                            }
                            this.NewDetailsList.push(obj)
                            
                        }
                        if(FlightList2.length>0){
                            let obj = {
                                FlightList: FlightList2,
                                NewFlightList: NewFlightList2,
                                ...this.DetailsList[this.DetailsList.length-1]
                            }
                            this.NewDetailsList.push(obj)
                        }
                        this.NewDetailsList.forEach(x=>{
                            if(x.FlightList.length>1){
                                x.show = false
                            }
                        })
                    }
                    uni.hideLoading()
                })
            },
            AddPassengers(){
                uni.navigateTo({
					url: `/pages/airTicket/AirplanePassengerAddEditing`///pages/airTicket/AirplanePassengerList
				});
            },
            scroll(e) {
                this.boxOption = Math.floor((e.detail.scrollTop - 50) / 1.5);
                this.titleStyle.opacity =
                e.detail.scrollTop - 100 < 0
                ? 0
                : Math.floor(e.detail.scrollTop - 100) / 100 > 1
                ? 1
                : 1;//Math.floor(e.detail.scrollTop - 100) / 100
                this.$forceUpdate();
            },
        }
    }
</script>
<style scoped>
@import url("@/asset/css/flex.css");
@import url("./style.css");
.airTicketDetailsAdd-box{
    padding: 46rpx 48rpx;
    border-radius: 50rpx;
}
.airTicketDetailsAdd{
    padding: 25rpx 0;
    border-radius: 40rpx;
}
.airTicketDetailsAddMobile>input{
    margin-top: 2rpx;
}

.airTicketDetailsFooter{
    padding: 38rpx 54rpx 67rpx 54rpx;
}
.airTicketDetailsFooter-text{
    top: 5rpx;
}
.airTicketDetailsBgF{
    left: 0;
    right: 0;
    top: 0;
}
</style>