<template>
    <view class="TicketOrderDetailsBg height100vh">
        <scroll-view
            scroll-y="true"
            style="height: 100%; flex: 1; box-sizing: border-box"
            @scroll="scroll"
            >
        <NavigationHeader :title="title" :titleStyle="titleStyle"></NavigationHeader>
        <!--  :style="{top:topheight+'px'}" -->
        <view class="TicketOrderDetailsC overflow PT123 PB260" v-if="orderData&&orderData.model">
            <view class="PX53">
                <view class="row-sb-n MT20">
                    <view class="flexS row-aic-n">
                        <img class="inlineblock MR20" mode="widthFix" style="width: 44rpx;height: 44rpx;"
                            :src="orderStatus.icon"/>
                            <!-- 已付款 待付款 已取消 -->
                        <text class="fz36 fontBold"
                        :class="[orderStatus.code==-1?'colorC6C1BC':'']">{{orderStatus.text}}</text>
                    </view>
                    <view @click="getDetail">
                        <text class="fz26 colorC09D4F">¥</text>
                        <text class="fz36 colorC09D4F fontBold ML15"> {{dataModel.PreferPrice}}</text>
                        <img class="inlineblock ML10 relative" mode="widthFix" style="width: 18rpx;height: 12rpx;top:-8rpx"
                            :src="statusImg[3]"/>
                    </view>
                </view>
                <view class="TicketOrderDetailsCard MT45 bgFFF hidden">
                    <TicketOrderDetails :DetailsList="NewDetailsList"></TicketOrderDetails>
                    <view class="PX50">
                    <view class="height-dashed1 DashedECF1F4 relative MT30" v-if="GuestList&&GuestList.length>0">
                        <!-- <view class="TicketOrderDetailsBor-LR TicketOrderDetailsBor-L absolute z-index2 bgF2EEE5"></view>
                        <view class="TicketOrderDetailsBor-LR TicketOrderDetailsBor-R absolute z-index2 bgF2EEE5"></view> -->
                    </view>
                    <view class="MT38">
                        <view class="TicketOrderDetailsN-box" v-for="(item,index) in GuestList">
                            <view class="row-sb-n ">
                                <view class="TicketOrderDetails-Name MR40 fz26 color9999A5 textRight flexS">
                                    <text>{{index+1>=10?index:'0'+(index+1)}}</text>
                                    <text class="ML15">乘机人</text>
                                </view>
                                <view class="flexG row-sb-n">
                                    <text class="fz26 fontBold color1D1D20">{{item.SurName}}</text>
                                    <text class="fz22 color9999A5">{{item.MobilePhone}}</text>
                                </view>
                                <view class="fz22 color9999A5 flexS">
                                    <!-- ¥{{item.Unit_Price}} -->
                                </view>
                            </view>
                            <view class="row-sb-n MT25">
                                <view class="TicketOrderDetails-Name MR40 fz26 color9999A5 textRight flexS">
                                    <text></text>
                                    <text class="ML15">护照号</text>
                                </view>
                                <view class="fz26 fontBold color1D1D20 flexG">
                                    {{item.IdCard?item.IdCard:item.PassportNo}}
                                </view>
                            </view>
                        </view>
                        
                    </view>
                    </view>
                </view>
                
            </view>
        </view>
        </scroll-view>
        <view class="airTicketDetailsFooter fixedFooter bgFFF fixed z-index2">
            <view class="TicketOrderDetailsFooter row-sbs-n"
            v-if="dataModel.OrderState==1||dataModel.OrderState==2||dataModel.OrderState==3">
                <view v-if="dataModel.OrderState==1||dataModel.OrderState==2||dataModel.OrderState==3"
                class="airTicketDetailsFooter-order row-ajc-w fontBold ML50"
                :class="[loading?'bgF5':'bgF5 colorDEBF7B']"
                @click="cancelOrder(dataModel)">
                    <text class="fz32">取消订单</text>
                </view>
                <view v-if="dataModel.OrderState==1||dataModel.OrderState==2"
                class="airTicketDetailsFooter-order row-ajc-w fontBold MR50"
                :class="[loading?'bgF5':'bgDEBF7B']"
                @click="queren(orderMsg.ID)">
                    <text class="fz32">立即支付</text>
                </view>
            </view>
            <view class="TicketOrderDetailsFooter row-ajc-n" v-if="dataModel.OrderState==5||dataModel.OrderState==4">
                <view
                class="airTicketDetailsFooter-order row-ajc-w fontBold"
                :class="[loading?'bgF5 colorDEBF7B':'bgDEBF7B']"
                @click="goUndOrder(dataModel.TCID)">
                    <text class="fz32">重新下单</text>
                </view>
            </view>
        </view>
        <u-popup
        v-model="showDetailPreviwe"
        mode="bottom"
        border-radius="50"
        :safe-area-inset-bottom="true">
            <view class="TicketOrderDetailsGet-box relative">
                <uni-icons class="TicketOrderDetailsGet-close absolute" 
                color="#9999A5" type="closeempty" size="24"
                @click="showDetailPreviwe=false"></uni-icons>
                <view class="fz30 fontBold textCenter">金额明细</view>
                <view class="MT75 TicketOrderDetailsGetC">
                    <view class="TicketOrderDetailsGet-Num MB52" v-for="(item,index ) in NewGuestList">
                        <view class="row-sb-n">
                            <text class="flexS">
                                人数
                                <!-- {{item.text}} -->
                            </text>
                            <view class="TicketOrderDetailsGet-NumA flexS ML30">
                                <view class="height-line1 lineC8C8CF"></view>
                            </view>
                            <view class="TicketOrderDetailsGet-NumR row-aic-n">
                                <view class="fz30 fontBold ML60 MR60 textRight" v-if="item.Unit_Price&&item.Unit_Price>=0">
                                    ¥{{item.Unit_Price}}
                                </view>
                                <view class="fz30 fontBold textRight flexS" v-if="item.Nums">
                                    ×{{item.Nums?item.Nums:''}}人
                                </view>
                            </view>
                        </view>
                        <!--
                        <view class="fz24 color9999A5 MT25" v-if="index!=2">
                            <template v-if="index==0">(14岁及以上的顾客)</template>
                            <template v-if="index==1">(2岁及14岁以下的顾客)</template>
                            <template v-if="index==2">(2岁以下的顾客)</template>
                        </view>  -->
                    </view>
                </view>
                <view class="absolute TicketOrderDetailsGet-Footer bgFFF row-sb-n">
                    <view>
                        <view class="fontBold">
                            <text class="fz32 color111">¥ </text>
                            <text class="fz52">{{dataModel.PreferPrice}}</text>
                        </view>
                        <view class="fz26 color9999A5 MT5">共 {{dataModel.GuestNum}} 人</view>
                    </view>
                    <view class="row-aic-n">
                        <view v-if="dataModel.OrderState==1||dataModel.OrderState==2||dataModel.OrderState==3" 
                        class="fz32 relative TicketOrderListCard-PrQx MR20"
                        :class="[loading?'color9999A5':'colorDEBF7B']"
                        @click="cancelOrder(dataModel)">取 消</view>
                        <view v-if="dataModel.OrderState==1||dataModel.OrderState==2" 
                        class="airTicketDetailsFooter-order PXY2463 row-ajc-w fontBold"
                        :class="[loading?'bgF5':'bgDEBF7B']"
                        @click="queren(orderMsg.ID)">
                            <text class="fz32">立即支付</text>
                        </view>
                        <view v-if="dataModel.OrderState==5||dataModel.OrderState==4" 
                        class="airTicketDetailsFooter-order PXY2463 row-ajc-w fontBold bgDEBF7B borderDEBF7B"
                        @click="goUndOrder(dataModel.TCID)">
                            <text class="fz32">重新下单</text>
                        </view>
                    </view>
                </view>
            </view>
        </u-popup>
    </view>
</template>
<script>
    import NavigationHeader from "./components/NavigationHeader.vue";
    import TicketOrderDetails from "./components/TicketOrderDetails.vue";
    import { getDateWeek } from "./dates.js";
    export default {
        components: {
            NavigationHeader,
            TicketOrderDetails
        },
        data() {
            return {
                orderInfo: {},
                loading: false,
                dataModel:{},
                NewGuestList: [],
                GuestList: [],
                NewDetailsList: [],
                DetailsList: [],
                orderStatus: {},
                showPayBtn: '',
                orderData:{},
                orderMsg:{
                    ID: 0,
                    IsGetGuest: 1
                },
                showDetailPreviwe: false,
                topheight:0,
                titleStyle:{},
                boxOption: 0,
                statusImg:[
                    'https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/1696906390000_78.png',
                    'https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/1696906393000_283.png',
                    'https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/1696906397000_762.png',
                    'https://viitto-1301420277.cos.ap-chengdu.myqcloud.com/Test/Upload/Goods/1696906709000_896.png'
                ],
                title:'订单详情'
            }
        },
        onLoad(options){
            this.orderMsg.ID = options.orderId
            this.getOrderDetails()
            let that = this;
            uni.getSystemInfo({
                success(res) {
                    that.titleStyle = {
                        height: "45px",
                        paddingTop: `${res.statusBarHeight}px`,
                        opacity: 0,
                    };
                    that.topheight = 55+res.statusBarHeight
                },
            });
        },
        created() {},
        mounted() {
            
        },
        methods: {
            goUndOrder(TCID){
                uni.navigateTo({
					url: `/pages/airTicket/airTicketDetails?TCID=${TCID}&Price=${this.dataModel.Unit_Price}`
				});
            },
            TicketDetails(){

            },
            getDetail(){
                this.showDetailPreviwe = true
            },
            getOrderDetails(){
                uni.showLoading()
                this.apipost(
                "sellorder_post_GetOrderEntity",
                this.orderMsg,
                (res) => {
                    if(res.resultCode==1){
                        this.GuestList = []
                        this.NewGuestList = []
                        console.log(res.data,'=======')
                        this.orderData = res.data;
                        // IsChargeLossOrders 1是收损单 2否
                        // IsApplyForCancel 1是小程序端发起取消 2否
                        this.dataModel = res.data.model
                        this.orderData.model.GuestList.forEach(x=>{
                            let obj = {
                                SurName:x.SurName+x.Name,
                                PassportNo:x.PassportNo,
                                IdCard:x.IdCard,
                                MobilePhone:x.MobilePhone,
                                ageType: '',
                                Unit_Price: 0,
                                NewUnit_Pric: 0,
                            }
                            this.GuestList.push(obj)
                        })
                        let num = 0
                        let Unit_Price = 0
                        let Nums = 0
                        if(this.dataModel.ManNum>0) {
                            num = 1;
                            Unit_Price = this.dataModel.Unit_Price*this.dataModel.ManNum;
                            Nums = this.dataModel.ManNum
                        }
                        if(this.dataModel.BabyNum>0) {
                            num += 1;
                            Unit_Price = (this.dataModel.Unit_Price*this.dataModel.BabyNum)*(this.dataModel.BabyPrecent/100);
                            Nums = this.dataModel.BabyNum
                        }
                        if(this.dataModel.ChirdNum>0) {
                            num += 1;
                            Unit_Price = (this.dataModel.Unit_Price*this.dataModel.ChirdNum)*(50/100);
                            Nums = this.ChirdNum
                        }
                        for(let i=0;i<num;i++){
                            let text = '成人'
                            if(i==1) text = '儿童'
                            if(i==2) text = '婴儿'
                            let obj = {
                                text: text,
                                Unit_Price: Unit_Price,
                                Nums: Nums
                            }
                            this.NewGuestList.push(obj)
                        }
                        this.formatStatus(
                            this.orderData.model.OrderState,
                            this.orderData.model.IsChargeLossOrders,
                            this.orderData.model.IsApplyForCancel
                        );
                        if(this.NewDetailsList&&this.NewDetailsList.length==0){
                            this.getAirDetails(this.orderData.model.TCID)
                        }else{
                            uni.hideLoading()
                        }
                    }else{
                        uni.hideLoading()
                    }
                })
            },
            getAirDetails(TCID){
                this.apipost("AirTicket_get_GetTicketDetails",{
                    TCID: 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.show = true
                            });
                        }
                        arr(res.data.FlightList)
                        this.DetailsList = 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=>{
                            let date =  y.FlightDate.split('-')
                            y.time = `${date[1]}-${date[2]}`
                            y.week = getDateWeek(y.FlightDate)
                            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.length-1!=i&&this.DetailsList[i].FlightSubType!=3){
                                FlightList.push(this.DetailsList[i])
                            }else{
                                FlightList2.push(this.DetailsList[i])
                                NewFlightList2.push(this.DetailsList[i]) 
                            }
                        }

                        for(let i=0;i<FlightList2.length;i++){
                            let DetailsList = JSON.parse(JSON.stringify(this.DetailsList))
                            DetailsList.forEach((x,index)=>{
                                if(x.Arrival_time&&FlightList2[i].Arrival_time){
                                    DetailsList.slice(0,index)
                                }
                            })
                        }
                        NewFlightList = [FlightList[0],FlightList[FlightList.length-1]]
                        if(FlightList.length>0){
                            let obj = {
                                FlightList: FlightList,
                                NewFlightList: NewFlightList,
                                frequency: FlightListZ.length-1,
                                ...this.DetailsList[0]
                            }
                            this.NewDetailsList.push(obj)
                            
                        }
                        if(FlightList2.length>0){
                            let obj = {
                                FlightList: FlightList2,
                                NewFlightList: NewFlightList2,
                                frequency: FlightListZ2.length-1,
                                ...this.DetailsList[this.DetailsList.length-1]
                            }
                            this.NewDetailsList.push(obj)
                        }
                        this.NewDetailsList.forEach((y,index)=>{
                            if(y.FlightList.length>1){
                                y.show = false
                            }
                            if(index){
                                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 ':''}`
                            }
                        })
                    }
                    uni.hideLoading()
                })
            },
            
            formatStatus(status, loss, isCancel) {
                loss = loss ? loss : -1;
                //1、已申请；!=1未申请
                if (loss == 1 || status == 4) {
                    this.orderStatus.code = -1;
                    this.orderStatus.text = "已取消";
                    this.orderStatus.icon = this.statusImg[2];
                    this.showPayBtn = false;
                } else if (status == 2 && isCancel != 1) {
                    this.orderStatus.code = 0;
                    this.orderStatus.text = "待付款";
                    this.orderStatus.icon = this.statusImg[1];
                    this.showPayBtn = true;
                } else if (status == 2 && isCancel == 1) {
                    this.orderStatus.code = -2;
                    this.orderStatus.text = "审核中";
                    this.orderStatus.icon = this.statusImg[1];
                    this.showPayBtn = false;
                } else if (status == 1) {
                    this.orderStatus.code = 1;
                    this.orderStatus.text = "待付款";
                    this.orderStatus.icon = this.statusImg[1];
                    this.showPayBtn = false;
                } else if (status == 3) {
                    this.orderStatus.code = 3;
                    this.orderStatus.text = "已付款";
                    this.orderStatus.icon = this.statusImg[0];
                    this.showPayBtn = false;
                }
            },
            cancelOrder(item){
                let that = this
                if(this.loading){
                    return
                }
                //未付款-调用后台取消
                uni.showLoading({
                    title: "请稍等片刻...",
                })
                this.loading = true
                if (
                    (item.PaymentTime == null || item.PaymentTime == "") &&
                    (item.OrderState == 1||item.OrderState == 2)
                ) {
                    this.apipost(
                    "sellorder_post_B2BRemoveOrder",
                    {
                        ID: item.OrderId,
                    },
                    (res) => {
                        if (res.resultCode == 1) {
                            uni.showToast({
                                title: "操作成功",
                                icon: "success",
                            });
                            that.getOrderDetails()
                        }
                        uni.hideLoading()
                        this.loading = false
                    },
                    (err) => {
                        uni.hideLoading()
                        this.loading = false
                    }
                    );
                } else {
                    let msg = {
                        OrderId: item.OrderId,
                        UserId: uni.getStorageSync("mall_UserInfo").UserId,
                    };
                    //已付款取消申请
                    this.apipost(
                    "sellorder_post_AppletUserCancelOrder",
                    msg,
                    (res) => {
                        if (res.resultCode == 1) {
                            uni.showToast({
                                title: "操作成功",
                                icon: "success",
                            });
                            that.getOrderDetails()
                        } else {
                        }
                        uni.hideLoading()
                        this.loading = false
                    },
                    (err)=>{
                        uni.hideLoading()
                        this.loading = false
                    }
                    );
                }
            },
            //微信支付
            queren(OrderId) {
                if(this.loading){
                    return
                }
                uni.showLoading({
                    title: "请稍等片刻...",
                })
                this.loading = true
                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}`;
                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.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: "支付成功",
                    });
                    that.getOrderDetails()
                },
                fail: function (err) {
                    that.loading = false
                    uni.hideLoading()
                    console.log("fail:", err);
                    uni.showToast({
                        title: "支付失败",
                        icon: "none",
                    });
                },
                });
            },
            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) / 10
                this.$forceUpdate();
            },
        }
    }
</script>
<style scoped>
@import url("@/asset/css/flex.css");
@import url("./style.css");
.TicketOrderDetailsC{
    
}
.TicketOrderDetailsCard{
    border-radius: 50rpx;
    padding: 30rpx 0 37rpx 0;
    margin-bottom: 90rpx;
}
.TicketOrderDetailsCard-Time{
    
}
.TicketOrderDetails-Name{
    width: 122rpx;
}
.TicketOrderDetailsN-box{
    margin-bottom: 47rpx;
}
.TicketOrderDetailsN-box:last-child{
    margin-bottom: 0;
}
.TicketOrderDetailsFooter{
    padding: 38rpx 0 67rpx 0;
}
.TicketOrderDetailsGet-box{
    margin: 46rpx 53rpx 51rpx 53rpx;
}
.TicketOrderDetailsGet-close{
    right: 0;
    top: 0;
}
.TicketOrderDetailsGetC{
    padding-bottom: 300rpx;
}
.TicketOrderDetailsGet-Num{
    
}
.TicketOrderDetailsGet-NumA{
    width: 295rpx;
}
.TicketOrderDetailsGet-NumR{
    /* width: 350rpx; */
}
.TicketOrderDetailsGet-Footer{
    left: 0;
    right: 0;
    bottom: 0;
}
.airTicketDetailsFooter-order.PXY2463{
    padding: 24rpx 63rpx;
}
.TicketOrderDetailsBor-LR{
    width: 50rpx;
    height: 50rpx;
    border-radius: 50%;
}
.TicketOrderDetailsBor-L{
    left: -78rpx;
    top: -25rpx;
}
.TicketOrderDetailsBor-R{
    right: -78rpx;
    top: -25rpx;
}
</style>