<style>
	.jz_MyOrder {
		height: 100vh;
		background-color: #ecf1f4;
		display: flex;
		flex-direction: column;
	}

	.jz_OrderList:first-child{
		margin-top: 15px;
	}
	.jz_OrderList {
		width: 100%;
		min-height: 334rpx;
		background-color: #fff;
		border-radius: 20px;
		padding: 30px;
		margin-bottom: 15px;
		position: relative;
	}

	.jz_OrderList:first-child {
		border-top-left-radius: 0;
		border-top-right-radius: 0;
	}

	.jz_OrderTop {
		display: flex;
		align-items: center;
		position: relative;
		padding-bottom: 27rpx;
		border-bottom: 1px solid #e6e6e6;
	}

	.jz_Oleft {
		color: #111111;
		font-size: 32rpx;
		font-weight: bold;
		width: 70%;
		height: 40rpx;
		overflow: hidden;
	}

	.jz-Oright {
		color: #111111;
		font-size: 24rpx;
		position: absolute;
		right: 0;
	}

	.jz_MyOrder_img {
		width: 100rpx;
		height: 100rpx;
		margin-top: 20px;
		border-radius: 20rpx;
		overflow: hidden;
		background: rgba(0, 0, 0, .05)
	}

	.jz_MyOrder_img img {
		width: 100%;
		height: 100%;
	}

	.jz_XiaDan {
		margin-left: 25rpx;
		color: #333333;
		font-size: 24rpx;
		margin-top: 20px;
	}

	.jz_Zailai {
		background-color: #111111;
		border-radius: 16px;
		width: 150rpx;
		height: 60rpx;
		text-align: center;
		color: #fff;
		line-height: 60rpx;
		font-size: 24rpx;
	}

	.isShowAll {
		height: auto;
	}

	.jz_BtnContent {
		margin-top: 15px;
		display: flex;
		align-items: center;
	}
</style>
<template>
	<view class="jz_MyOrder">
		<u-tabs :list="list" :is-scroll="false" :current="current" :active-color="mainColor" :show-bar="showBar" @change="change"
		 bar-height="4" height="100"></u-tabs>
		<u-empty v-if="dataList.length == 0" text="暂无数据" mode="data"></u-empty>
		<template v-else>
			<view class="jz_MyOrderMain" style="height: 1px; flex: 1; overflow: hidden">
				<scroll-view :scroll-y="true" :enable-back-to-top="true" :enable-flex="true" @scrolltolower="lower" :style="{ height: '100%' }">
					<view class="jz_OrderList" v-for="(item, index) in dataList" :key="index" @click="goOrderDetail(item)">
						<view class="jz_OrderTop">
							<view class="jz_Oleft" :class="{ isShowAll: !item.isShowHalf }">
								{{ item.title }}
							</view>
							<view style="margin-left: 10px">
								<u-icon name="arrow-down" @click.native.stop="getShow(item)" v-if="item.isShowHalf" color="#2979ff" size="28"></u-icon>
								<u-icon name="arrow-up" @click.native.stop="getShow(item)" v-else color="#2979ff" size="28"></u-icon>
							</view>
							<view class="jz-Oright">
								{{getOrderStateName(item)}}
							</view>
						</view>
						<view style="display: flex">
							<view class="jz_MyOrder_img">
								<img mode="aspectFill" v-if="item.imgCover && item.imgCover.length>0" :src="item.imgCover[0].url" alt="" />
							</view>
							<view class="jz_XiaDan">
								<view>下单时间：{{ item.createDate }}</view>
								<view style="margin-top: 22rpx">订单总额：¥{{ item.preferPrice }},
									<text v-if="item.discountMoney&&item.discountMoney>0" style="margin-left: 15px;">优惠金额：￥<text style="color:indianred">{{item.discountMoney}}</text></text>
									<text style="margin-left: 15px;">已付款金额：￥<text style="color:indianred">{{item.customerPayMoney?item.customerPayMoney:0}}</text></text>
								</view>
							</view>
						</view>
						<view v-if="item.isApplyForCancel == 1" style="color: red; font-size: 24rpx; margin-left: 122rpx">订单取消，正在确认中！</view>
						<view class="jz_BtnContent">
							<view style="width: 1px;flex: 1;">
								<u-tag mode="plain" border-color="#DFBE6E" color="#DFBE6E" text="待发放优惠券" size="mini" v-if="item.autoCouponId==0"></u-tag>
								<u-tag mode="plain" border-color="#1d1d1d" color="#1d1d1d" text="已发放优惠券" size="mini" v-else-if="item.autoCouponId==1"></u-tag>
							</view>
							<view class="jz_Zailai" style="margin-right: 10rpx" @click.stop="gojz_List">再来一单</view>
							<!-- #ifdef MP-WEIXIN -->

							<!-- <button v-if="item.orderState == 2" class="jz_Zailai" @click.stop="goZhifu(item)" style="width: 110rpx; margin-right: 10rpx; margin-left: 0rpx">
								付款
							</button> -->
							<!-- #endif -->
							<!-- #ifdef MP-ALIPAY -->
							<view v-if="item.orderState == 2" class="jz_Zailai" style="width: 110rpx; margin-right: 10rpx" @click.stop="goZhifuAli(item)">付款</view>
							<!-- #endif -->
							<view v-if="item.isApplyForCancel != 1 && item.orderState != 4 && item.customerPayMoney==0" class="jz_Zailai"
							 style="width: 110rpx" @click.stop="goCancel(item)">取消</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</template>
		<!-- #ifdef MP-ALIPAY -->
		<subscribe-msg />
		<!-- #endif -->
		<!-- <tabbars></tabbars> -->
		<auth v-if="showAuth" @changeuserinfo="reloadUserinfo" @gbAuth="gbAuth"></auth>
		<coupons v-if="showCoupons" :coupon-message="couponMessage" @goLook="()=>showCoupons=false" @closeBtn="()=>showCoupons=false"></coupons>
	</view>
</template>
<script>
	import tabbars from "@/components/tabbar/index";
	import auth from "@/components/auth/index.vue";
	import coupons from "@/components/coupons/coupons.vue";
	export default {
		components: {
			tabbars,
			auth,
			coupons
		},
		data() {
			return {
				pageTitle: "线路订单",
				msg: {
					pageIndex: 1, //当前页
					pageSize: 15, //每页显示条数
					orderState: 0, //订单状态
					GroupType: 1, //线路订单
					queryDays: 0, //根据天数查询订单【几天前】
					CustomerId: 0, //同行Id
					MiniAppUserId: 0, //旅小友小程序用户Id，
					DirectCustomerId: 0, //直客Id
				},
				showCoupons:false,
				couponMessage:[],
				mainColor: "",
				list: [{
						name: "全部",
						Id: 0,
					},
					{
						name: "待付款",
						Id: 1,
					},
					{
						name: "待发团",
						Id: 3,
					},
					{
						name: "已完成",
						Id: 5,
					},
					{
						name: "已取消",
						Id: 4,
					},
				],
				current: 0,
				dataList: [],
				page_count: 0,
				loadText: {
					loadmore: "轻轻上拉，加载更多",
					loading: "努力加载中",
					nomore: "没有更多了",
				},
				status: "加载中",
				price: 0,
				showBar: true,
				b2b_user_info: {},
				userInfo: {},
				showAuth: false,
			};
		},
		created() {
			// #ifdef MP-ALIPAY
			this.showBar = false;
			// #endif
		},
		onLoad(option) {
			this.current = option.status || 0;
			this.mainColor = this.$uiConfig.mainColor;
			let currentPages = getCurrentPages();
			let u = "/" + currentPages[currentPages.length - 1].route;
			let pages = wx.getStorageSync("basedata") ?
				wx.getStorageSync("basedata").bar_title : [];
			pages.forEach((x) => {
				if (x.value == u) {
					this.pageTitle = x.new_name ? x.new_name : x.name;
				}
			});
			uni.setNavigationBarTitle({
				title: this.pageTitle,
			});
			this.userInfo = uni.getStorageSync("mall_UserInfo");
			this.b2b_user_info = uni.getStorageSync('b2b_user');
			if (!this.b2b_user_info) {
				this.showAuth = true;
			} else {
				this.getOrderInfo();
			}
			//同行联系人绑定的优惠卷
			if (uni.getStorageSync('coupons')) {
				this.showCoupons = true;
				this.couponMessage = uni.getStorageSync('coupons');
			}
		},
		methods: {
			//获取订单状态名称
			getOrderStateName(item) {
				var str = "待付款";
				if (item.orderState == 1) {
					str = "已付款"
				} else if (item.orderState == 4) {
					str = "已取消"
				}
				return str;
			},
			//关闭登录窗口
			gbAuth() {
				this.showAuth = false;
			},
			//重新加载用户信息
			reloadUserinfo() {
				this.userInfo = uni.getStorageSync("mall_UserInfo");
				this.b2b_user_info = uni.getStorageSync('b2b_user');
				if (this.b2b_user_info) {
					this.getOrderInfo();
				}
			},
			goOrderDetail(item) {
				uni.navigateTo({
					url: "/pages/jiuzhai/jz_SureOrder?orderId=" + item.orderId,
				});
			},
			change(i) {
				this.current = i;
				this.msg.orderState = this.list[i].Id;
				this.research();
			},
			//获取第一张图
			getFirstImg(obj) {
				if (obj) {
					let objArr = JSON.parse(obj);
					return objArr[0].Url;
				}
			},
			getShow(item) {
				item.isShowHalf = !item.isShowHalf;
				this.$forceUpdate();
			},
			//跳转
			gojz_List() {
				uni.navigateTo({
					url: "/pages/jiuzhai/jz_Line",
				});
			},
			lower(e) {
				if (this.msg.pageIndex < this.page_count) {
					this.msg.pageIndex++;
					this.status = "loading";
					this.getOrderInfo();
				} else {
					this.status = "nomore";
				}
			},
			research() {
				this.msg.pageIndex = 1;
				this.getOrderInfo(1);
			},
			getOrderInfo(type) {
				uni.showLoading({
					title: "加载中",
					icon: "none",
				});
				if (type == 1) {
					this.dataList = [];
				}
				this.msg.MiniAppUserId = this.userInfo.UserId;
				this.msg.CustomerId = this.b2b_user_info.customerId;
				this.msg.DirectCustomerId = this.b2b_user_info.directCustomerId
				this.apipost(
					"sellorder_post_GetTravelOrderAppletList",
					this.msg,
					(res) => {
						uni.hideLoading();
						if (res.resultCode == 1) {
							if (type == 1) {
								this.dataList = res.data.pageData;
							} else {
								this.dataList = this.dataList.concat(res.data.pageData);
							}
							this.dataList.forEach((x) => {
								x.isShowHalf = true;
							});
							this.page_count = res.data.pageCount;
						} else {}
					},
					null
				);
			},
			//取消订单
			goCancel(item) {
				//未付款-调用后台取消
				if (
					(item.paymentTime == null || item.paymentTime == "") &&
					(item.orderState == 2 || item.orderState == 3)
				) {
					this.apipost(
						"sellorder_post_B2BRemoveOrder", {
							ID: item.orderId,
						},
						(res) => {
							if (res.resultCode == 1) {
								uni.showToast({
									title: "操作成功",
									icon: "success",
								});
								this.research();
							}
						},
						(err) => {}
					);
				} 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",
								});
								this.research();
							} else {}
						},
						null
					);
				}
			},
			//付款
			// #ifdef MP-WEIXIN
			goZhifu(item) {
				let url = "/api/WeChatPay/GetTravlePayInfo";
				let GoodsName = item.title;
				GoodsName = GoodsName.slice(0, 10);
				this.price = item.preferPrice;
				this.request2({
						url: url,
						data: {
							OrderId: item.orderId,
							GoodsName: GoodsName,
							OrderPayType: 1,
							OpenId: uni.getStorageSync("mall_UserInfo").OpenId,
						},
					},
					(res) => {
						try {
							let orderInfo = JSON.parse(res.data);
							this.subscribeMsg(orderInfo);
						} catch (e) {
							uni.showToast({
								title: '无法正常拉取微信支付，你可以稍后重试或联系销售人员线下转款',
								icon: 'none'
							})
						}
					}
				);
			},
			subscribeMsg(orderInfo) {
				const that = this;
				var basedata = uni.getStorageSync("basedata");
				let tempObj = [];
				if (basedata && basedata.mall && basedata.mall.wechatmessage && basedata.mall.wechatmessage.length > 0) {
					tempObj = 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.goPay(orderInfo);
					},
				});
			},
			goPay(orderInfo) {
				let that = this;
				uni.requestPayment({
					provider: "wxpay",
					timeStamp: orderInfo.timeStamp,
					nonceStr: orderInfo.nonceStr,
					package: orderInfo.package,
					signType: orderInfo.signType,
					paySign: orderInfo.sign,
					success: function(res) {
						console.log("goPay_success", res);
						uni.showToast({
							title: "支付成功",
						});
						uni.redirectTo({
							url: "/pages/jiuzhai/paysuccess?PreferPrice=" +
								that.price +
								"&isFrom=1",
						});
					},
					fail: function(err) {
						console.log("goPay_fail:", err);
						uni.showToast({
							title: "支付失败",
						});
					},
				});
			},
			// #endif
			// #ifdef MP-ALIPAY
			goZhifuAli(item) {
				let that = this;
				uni.showLoading({
					title: "支付中",
				});
				let url = "/api/WeChatPay/GetTravlePayInfo";
				this.price = item.preferPrice;
				this.request2({
						url: url,
						data: {
							OrderId: item.orderId,
							GoodsName: item.title,
							OrderPayType: 2,
							OpenId: uni.getStorageSync("mall_UserInfo").OpenId,
						},
					},
					(res) => {
						if (res.data) {
							this.$utils.SubscribeMsgAli(() => {
								that.goPayAli(res.data, item);
							});
						} else {
							uni.hideLoading();
							uni.showToast({
								title: "获取交易号失败",
								duration: 2000,
							});
						}
					}
				);
			},
			goPayAli(tradeNO, item) {
				let that = this;
				my.tradePay({
					tradeNO: tradeNO,
					success: function(res) {
						console.log("goPayAli_success", res);
						const list = ["9000"];
						if (list.includes(res.resultCode)) {
							let obj = {
								TradeNo: tradeNO,
								OrderNo: item.orderNo,
								OrderId: item.orderId,
								preferPrice: item.preferPrice,
							};
							that.payAliCallback(obj);
						} else {
							uni.hideLoading();
							uni.showToast({
								title: "支付失败",
								icon: "none",
							});
						}
					},
					fail: function(err) {
						console.log("goPayAli_fail:", err);
						uni.hideLoading();
						uni.showToast({
							title: "支付失败",
							icon: "none",
						});
					},
				});
			},
			payAliCallback(obj) {
				this.request2({
						url: "/api/AliPay/ALiPayCallBackDmcNotify",
						data: {
							OrderNo: obj.OrderNo,
							OrderId: obj.OrderId,
							UserId: uni.getStorageSync("mall_UserInfo").UserId,
							TradeNo: obj.TradeNo,
							ProjectType: 2,
							PreferPrice: obj.preferPrice,
						},
					},
					(res) => {
						console.log("payAliCallback_1", res);
						uni.redirectTo({
							url: "/pages/jiuzhai/paysuccess?PreferPrice=" +
								obj.preferPrice +
								"&isFrom=1",
						});
						uni.hideLoading();
					},
					(err) => {
						console.log("payAliCallback_2", err);
						uni.hideLoading();
						uni.showToast({
							title: "支付失败",
							icon: "none",
						});
					}
				);
			},
			// #endif
		},
	};
</script>
