<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.name }}
							</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.coverImageList && item.coverImageList.length>0" :src="item.coverImageList[0].url" alt="" />
							</view>
							<view class="jz_XiaDan">
								<view>下单时间：{{ item.createTime }}</view>
								<view style="margin-top: 22rpx">订单总额：¥{{ item.totalPrice }},
									<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.income?item.income: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="govisa_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 class="jz_Zailai" style="width: 110rpx; margin-right: 10rpx" @click.stop="goZhifuAli(item)">付款</view> -->
							<!-- #endif -->
							<!-- #ifdef MP-DI -->
							<!-- v-if="item.visaOrderStatus==1" -->
								<button v-if="item.visaOrderStatus==3" class="jz_Zailai"
								style="width: 110rpx" @click.stop="goCancelZK(item)"
								:disabled="submitCancel">取消</button>
								<button v-if="item.visaOrderStatus==3" class="jz_Zailai"
								style="width: 150rpx;margin-left: 10rpx;" @click.stop="goOrderDetail(item)"
								:disabled="submitCancel">立即支付</button>
							<!-- #endif -->
							<!-- #ifdef MP-AG -->
								<view v-if="item.visaOrderStatus==3" class="jz_Zailai"
								style="width: 110rpx" @click.stop="goCancel(item)">取消</view>
							<!-- #endif -->
						</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, //每页显示条数
					VisaOrderStatus: 0, //1 正常 2 取消 3 待付款
					ClientType: 0, //1 同业 2 直客
				},
				showCoupons:false,
				couponMessage:[],
				mainColor: "",
				list: [{
						name: "全部",
						Id: 0,
					},
					{
						name: "已付款",
						Id: 1,
					},
					{
						name: "待付款",
						Id: 3,
					},
					{
						name: "已取消",
						Id: 2,
					},
				],
				current: 0,
				dataList: [],
				page_count: 0,
				loadText: {
					loadmore: "轻轻上拉，加载更多",
					loading: "努力加载中",
					nomore: "没有更多了",
				},
				status: "加载中",
				price: 0,
				showBar: true,
				b2b_user_info: {},
				userInfo: {},
				showAuth: false,
				submitCancel: false,
			};
		},
		created() {
			// #ifdef MP-ALIPAY
			this.showBar = false;
			// #endif
		},
		onLoad(option) {
			//#ifdef MP-DI
				this.msg.ClientType = 2
			//#endif
			//#ifdef MP-AG
				this.msg.ClientType = 1
			//#endif
			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.visaOrderStatus == 1&&(item.income+item.platformTax)<item.totalPrice) {
					str = "正常"
				} else if (item.visaOrderStatus == 1&&(item.income+item.platformTax)==item.totalPrice) {
					str = "已付款"
				} else if (item.visaOrderStatus == 2) {
					str = "已取消"
				} else if (item.visaOrderStatus == 3) {
					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) {
				// #ifdef MP-DI
					uni.navigateTo({
						url: `/pages/visa/visa_SureOrder?orderId=${item.id}&OrderTypeStr=Visa`,
					});
				// #endif
				// #ifdef MP-AG
					uni.navigateTo({
						url: `/pages/visa/visa_SureOrder?orderId=${item.id}`,
					});
				// #endif
				
			},
			change(i) {
				this.current = i;
				this.msg.VisaOrderStatus = 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();
			},
			//跳转
			govisa_List() {
				uni.navigateTo({
					url: "/pages/visa/visaList",
				});
			},
			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.apipost(
					"b2c_get_GetB2BOrderVisaOrderList",
					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) {
				let that = this
				if(that.submitCancel) return
				wx.showModal({
					title: '提示',
					content: '确定取消订单？',
					success: (tip) => {
						if (tip.confirm) {
							that.submitCancel = true
							that.apipost(
								"b2c_get_SetB2BOrderCancel", {
									OrderId: item.id,
									OrderSource: 5
								},
								(res) => {
									that.submitCancel = false
									if (res.resultCode == 1) {
										uni.showToast({
											title: "操作成功",
											icon: "success",
										});
										that.research();
									}
								},
								(err) => {
									that.submitCancel = false
									uni.showToast({
										title: err.message,
										icon: "none",	
									})
								}
							);
						}
					}
				})
				
			},
			goCancelZK(item) {
				let that = this
				if(this.submitCancel) return
				this.submitCancel = true
				wx.showModal({
					title: '提示',
					content: '确定取消订单？',
					success: (tip) => {
						if (tip.confirm) {
							that.apipost(
								"GetCancelOrder_post", {
									OrderNo: '',
									ErpOrderId: item.id,
					    			OrderTypeStr: 'Visa',
								},
								(res) => {
									if (res.resultCode == 1) {
										uni.showToast({
											title: "操作成功",
											icon: "success",
										});
										that.research();
									}
									that.submitCancel = false
								},
								(err) => {
									uni.showToast({
										title: err.message,
										icon: "none",
									});
								}
							);
						}else that.submitCancel = false
					}
				})
				
			},
			//付款
			// #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>
