<template>
    <view class="uni-container">
        <u-navbar :autoBack="true" :bgColor="bgColor">
        	<view slot='center' style="font-size: 36rpx; font-weight: bold;">
        		票务订单
        	</view>
        </u-navbar>
        <view class="menu" :style="'top: ' + navHeight + 'px;'">
            <view :class="{ active: menuIndex === '' }" @click="tabMenu('')">全部</view>
            <view :class="{ active: menuIndex === '0' }" @click="tabMenu('0')">待付款</view>
            <view :class="{ active: menuIndex === '1' }" @click="tabMenu('1')">待使用</view>
            <view :class="{ active: menuIndex === '2' }" @click="tabMenu('2')">已核销</view>
            <view :class="{ active: menuIndex === '3' }" @click="tabMenu('3')">退款</view>
        </view>
        <mescroll-body @init="mescrollInit" @down="downCallback" @up="upCallback" :down="downOption" :up="upOption" :top="paddingTop + 'px'">
            <view class="list_waper" v-if="menuIndex < 3">
                <navigator hover-class="none" class="list" v-for="(item, index) in list " :key="index" :url="'/pages/my/unpaid?id=' + item.id">
                    <view class="title">
                        <view class="text">订单编号：{{item.orderCode}}</view>
                        <view class="status" :style="{'color': getStatusColor(item)}">{{getStatusName(item)}}</view>
                    </view>
                    <view class="info" v-if="item.orderItemList">
                        <view class="img">
                            <image :src="$utils.setImgUrl(item.orderItemList[0].image11)" mode=""></image>
                        </view>
                        <view class="cont">
                            <view class="col col1">{{item.orderItemList[0].ticketName}}</view>
                            <view class="col col2">下单：{{item.createTime}}</view>
                            <view class="col col3" v-if="item.orderItemList[0].ticketOrderDetailList[0].availableStartTime && item.orderItemList[0].ticketOrderDetailList[0].availableEndTime">
                                <template v-if="item.orderItemList[0].ticketOrderDetailList[0].availableStartTime.split(' ')[0] == item.orderItemList[0].ticketOrderDetailList[0].availableEndTime.split(' ')[0]">
                                    <text>{{item.orderItemList[0].ticketOrderDetailList[0].availableStartTime.split(' ')[0]}}</text>
                                    当日有效
                                </template>
                                <template v-else>
                                    <text>{{item.orderItemList[0].ticketOrderDetailList[0].availableStartTime.split(' ')[0]}}</text>
                                    至
                                    <text>{{item.orderItemList[0].ticketOrderDetailList[0].availableEndTime.split(' ')[0]}}</text>
                                    有效
                                </template>
                            </view>
                            <view class="col col3" v-else>
                                {{item.orderItemList[0].ticketValidityPeriod == '2' ? '购买后' : '激活后'}}{{item.orderItemList[0].buyPeriodDay}}天有效
                            </view>
							<view class="price">
								<view>￥{{item.orderItemList[0].totalPrice}}</view>
								<view>共{{item.orderItemList[0].buyQuantity}}张</view>
							</view>
                        </view>
                    </view>
                    <view class="btns" v-if="item.paymentType == '0' || item.showRefund">
                        <view class="btn default" v-if="item.paymentType == '0'" @click.stop="cancelOrder(item.orderCode)">取消订单</view>
                        <view class="btn active" v-if="item.paymentType == '0'" @click.stop="payOrder(item)">立即支付</view>
                        <view class="btn default" v-if="item.showRefund" @click.stop="goRefund(item)">申请退款</view>
                    </view>
                </navigator>
            </view>
            <view class="list_waper" v-else>
                <navigator hover-class="none" class="list" v-for="(item, index) in list " :key="index" :url="'/pages/my/refundDetail?id=' + item.id">
                    <view class="title">
                        <view class="text">退款编号：{{item.refundCode}}</view>
                        <view class="status" :style="'color: ' + ((item.refundStatus == '2' || item.refundStatus == '200') ? '#03AE80' : '#FF5833')">{{item.refundStatusName}}</view>
                    </view>
                    <view class="info" v-if="item.orderRefundItemList">
                        <view class="img">
                            <image :src="$utils.setImgUrl(item.orderRefundItemList[0].zdyTicket.image11)" mode=""></image>
                        </view>
                        <view class="cont">
                            <view class="col col1">{{item.orderRefundItemList[0].ticketName}}</view>
                            <view class="col col2">下单：{{item.orderTime}}</view>
                            <view class="col col3">申请：{{item.createTime}}</view>
                			<view class="price">
                				<view>￥{{item.orderRefundItemList[0].totalPrice}}</view>
                				<view>共{{item.orderRefundItemList[0].refundQuantity}}张</view>
                			</view>
                        </view>
                    </view>
                </navigator>
            </view>
        </mescroll-body>
    </view>
</template>

<script>
import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
export default {
    mixins: [MescrollMixin],
    data () {
        return {
            navHeight: 0,
            paddingTop: 0,
            bgColor: '#fff',
            menuIndex: '',
            list: [],
            downOption: { auto: false }
        }
    },
    onLoad (options) {
        if (options.index) this.menuIndex = options.index;
        this.navHeight = this.$paddingTop;
        this.paddingTop = this.$paddingTop + uni.upx2px(105);
    },
	onShow () {
		this.mescroll && this.mescroll.resetUpScroll();
	},
    methods: {
        getStatusName (item) {
            let str = '';
            if (item.paymentType <= '2') {// 状态大于2代表已支付
                str = item.paymentTypeName;
            } else {
                if (item.refundStatus == 0) {
                    str = item.verificationTypeName;
                } else {
                    str = item.refundStatusName;
                }
            }
            return str;
        },
		getStatusColor(item) {
            let color = '';
            if (item.paymentType <= '2') {// 状态大于2代表已支付
                color = item.paymentType == '0' ? '#FF5833' : '#999999'
            } else {
                if (item.refundStatus == 0) {
                    color = item.verificationType == '0' ? '#03AE80' : '#999999'
                } else {
                    color = '#999999'
                }
            }
            return color;
		},
        async cancelOrder (orderCode) {
            let info = await this.$http.cancelTicketOrderPrepay(orderCode);
            if (info.code == 200) {
                uni.showToast({ mask: true, title: '操作成功', icon: 'success' })
                this.mescroll.resetUpScroll();
            } else  uni.showToast({ mask: true, title: info.msg, icon: 'none' })
        },
        async payOrder (item) {
            let parmas = {
				orderItemList: [{
					ticketName: item.orderItemList[0].ticketName,
					totalPrice: item.orderItemList[0].totalPrice
				}],
				id: item.id
			};
			uni.navigateTo({
			    url: `/pages/my/payment?parmas=${JSON.stringify(parmas)}`
			})
			
			
            // if (item.paymentMethod == '7') {
            //     let info = await this.$http.continuePayment(item.id);
            //     if (info.code == 200) {
            //         uni.showToast({ mask: true, title: '支付成功', icon: 'success' });
            //         this.mescroll.resetUpScroll();
            //     }
            // } else {
            //     let info = await this.$http.getTicketOrderSession({ orderId: item.id });
            //     uni.showLoading({ mask: true });
            //     const prepayId = JSON.parse(info.msg);
            //     uni.requestPayment({
            //     	provider: 'wxpay',
            //     	timeStamp: prepayId.timeStamp,
            //     	nonceStr: prepayId.nonceStr,
            //     	package: prepayId.packageValue,
            //     	signType: prepayId.signType,
            //     	paySign: prepayId.paySign,
            //     	success: (res) => {
            //     		uni.hideLoading();
            //     		this.mescroll.resetUpScroll();
            //     	},
            //     	fail: (err) => {
            //     		uni.hideLoading();
            //     		uni.showToast({ mask: true, title: '支付取消', icon: 'none' })
            //     	}
            //     });
            // }
            
        },
		goRefund(e) {
			uni.navigateTo({
				url: `/pages/my/refund?id=${e.id}`
			})
		},
        tabMenu (index) {
            this.menuIndex = index;
			this.list = [];
            this.mescroll.resetUpScroll();
        },
        async upCallback (page) {
            let obj = { pageNum: page.num, pageSize: page.size };
            let info = null;
            if (this.menuIndex == '3') {
                info = await this.$http.getRefundList(obj);
            } else {
                if (this.menuIndex !== '') {
                    switch (this.menuIndex) {
                        case '0':
                            obj.paymentType = '0';
                            break;
                        case '1':
                            obj.paymentType = '200';
                            obj.verificationType = '0';
                            break;
                        case '2':
                            obj.verificationType = '200';
                            break;
                    }
                }
                info = await this.$http.getTicketOrderPrepay(obj);
            }
            if(page.num == 1) this.list = [];
            // 判断是否包含可退票的门票
            if (this.menuIndex != '3') {
                info.rows.forEach((waper, waperIndex) => {
                    if (waper.orderItemList[0].totalPrice > 0) {
                        let list = [];
                        waper.orderItemList[0].ticketOrderDetailList.forEach((item, itemIndex) => {
                            if (waper.orderItemList[0].refundRule != '0' && item.paymentType == '200' && item.verificationType == '0' && (item.refundStatus == '0' || item.refundStatus == '100')) {
                                if (item.verificationMun == 0) {
                                    let creaetd = parseInt(new Date(this.$utils.formatDate('Y-M-D', item.paymentTime) + ' 00:00:00').getTime() / 1000);
                                    if (waper.orderItemList[0].classify == '1') {// 普通票
                                        // 判断是否再有效期
                                        switch (waper.orderItemList[0].refundRule) {
                                            case '3':// 有效期可退
                                                // let startTime = parseInt(new Date(this.$utils.formatDate('Y-M-D', item.availableStartTime) + ' 00:00:00').getTime() / 1000);
                                                let endTime = parseInt(new Date(this.$utils.formatDate('Y-M-D', item.availableEndTime) + ' 23:59:59').getTime() / 1000);
                                                let nowdate = parseInt(new Date().getTime() / 1000);
                                                // 当前日期大于等于开始时间并且当前日期小于等于结束时间，门票可退
                                                if (nowdate <= endTime) list.push(item);
                                                break;
                                            case '4':// 几天内可退
                                                let nowtime = parseInt(new Date().getTime() / 1000);
                                                console.log(nowtime - creaetd)
                                                // 当前时间减下单时间如果小于等于后台设定天数。门票可退
                                                if (((nowtime - creaetd) / 60 / 60 / 24) <= waper.orderItemList[0].refundDay) list.push(item);
                                                break;
                                        }
                                    } else if (waper.orderItemList[0].classify == '2') {// 套票
                                        // 判断是否再有效期
                                        let num = 0;// 大于0代表已经使用过
                                        switch (waper.orderItemList[0].refundRule) {
                                            case '3':// 有效期可退
                                                item.orderDetailChildList.forEach((child, childIndex) => {
                                                    if (child.verificationNum > 0) num ++;
                                                })
                                                if (num == 0) {
                                                    // let startTime = parseInt(new Date(this.$utils.formatDate('Y-M-D', item.availableStartTime) + ' 00:00:00').getTime() / 1000);
                                                    let endTime = parseInt(new Date(this.$utils.formatDate('Y-M-D', item.availableEndTime) + ' 23:59:59').getTime() / 1000);
                                                    let nowdate = parseInt(new Date().getTime() / 1000);
                                                    // 当前日期大于等于开始时间并且当前日期小于等于结束时间，门票可退
                                                    if (nowdate <= endTime) list.push(item);
                                                }
                                                break;
                                            case '4':// 几天内可退
                                                item.orderDetailChildList.forEach((child, childIndex) => {
                                                    if (child.verificationNum > 0) num ++;
                                                })
                                                if (num == 0) {
                                                    let nowtime = parseInt(new Date().getTime() / 1000);
                                                    console.log(nowtime - creaetd)
                                                    // 当前时间减下单时间如果小于等于后台设定天数。门票可退
                                                    if (((nowtime - creaetd) / 60 / 60 / 24) <= waper.orderItemList[0].refundDay) list.push(item);
                                                }
                                                break;
                                        }
                                    } else if (waper.orderItemList[0].classify == '4') {// 年卡
										if (item.activationStatus == '0') {
											list.push(item)
										}
									}
                                } else info.rows[waperIndex].showRefund = false;
                            } else info.rows[waperIndex].showRefund = false;
                        })
                        if (list.length > 0) info.rows[waperIndex].showRefund = true;
                    } else info.rows[waperIndex].showRefund = false;
                })
            }
            
            this.list = this.list.concat(info.rows);
            this.mescroll.endBySize(info.rows.length, info.total); 
        }
    }
}
</script>

<style lang="scss">

.menu{
    width: 100%; height: 90rpx; margin-bottom: 15rpx; position: fixed; left: 0; box-sizing: border-box; padding: 0 32rpx; display: flex; justify-content: space-between; align-items: center; background: #FBFBFB; z-index: 11;
    view{
        line-height: 46rpx; color: #333; font-size: 32rpx;
        &.active{
            position: relative; color: #03AE80; font-weight: 500;
            &::after{ content: ""; width: 30rpx; height: 4rpx; background: #03AE80; position: absolute; left: 50%; transform: translateX(-50%); top: 52rpx; }
        }
    }
}
.list_waper{
    width: 100%; box-sizing: border-box; padding: 0 32rpx 24rpx;
    .list{
        width: 100%; box-sizing: border-box; padding: 32rpx 24rpx; background: #fff; border-radius: 10rpx; margin-bottom: 24rpx;
        &:last-child{ margin-bottom: 0; }
        .title{
            width: 100%; box-sizing: border-box; padding-right: 120rpx; position: relative;
            .text{color: #666; font-size: 28rpx; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
            .status{ width: 120rpx; color: #03AE80; font-size: 28rpx; position: absolute; right: 0; top: 0; text-align: right; }
        }
        .info{
            padding-left: 160rpx; margin-top: 24rpx; position: relative;
            .img{
                width: 140rpx; height: 140rpx; position: absolute; left: 0; top: 0;
                image{ width: 100%; height: 100%; vertical-align: top; border-radius: 10rpx; }
            }
            .cont{
                position: relative; width: 100%; box-sizing: border-box; padding-right: 100rpx; height: 140rpx;
                .col{ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}
				.col1{ color: #333; font-size: 28rpx; font-weight: 500; }
				.col2{ margin-top: 20rpx; color: #666; font-size: 24rpx; }
				.col3{ margin-top: 8rpx; color: #666; font-size: 24rpx; }
				.price {
					position: absolute;
					right: 0;
					top: 50%;
					transform: translateY(-50%);
					text-align: center;
					view {
						&:nth-child(1) {
							font-weight: 500;
							font-size: 28rpx;
							color: #333333;
						}
						&:nth-child(2) {
							font-weight: 400;
							font-size: 24rpx;
							color: #666666;
							margin-top: 4rpx;
						}
					}
				}
            }
        }
        .btns{ width: 100%; padding-top: 28rpx; margin-top: 32rpx; display: flex; justify-content: flex-end; align-items: center; border-top: 1rpx solid rgba(0,0,0,0.1);
            .btn{
                text-align: center; font-size: 28rpx; margin-right: 16rpx;
                &:last-child{ margin-right: 0; }
            }
            .active {
				width: 158rpx;
				height: 64rpx;
				background: linear-gradient( 141deg, #54C76E 0%, #03AE80 100%);
				border-radius: 100rpx;
				line-height: 64rpx;
				color: #FFFFFF;
			}
			.default {
				width: 156rpx;
				height: 61rpx;
				border-radius: 60rpx;
				line-height: 61rpx;
				border: 1rpx solid #A2A2A4;
				color: #A2A2A4;
			}
        }
    }
}
</style>