<template>
	<view>
		<!-- 顶部操作条 -->
		<cu-custom :bgColor="'bg-main-color'" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">我的订单</block>
		</cu-custom>
		<!-- tab -->
		<view class="sticky-bar" :style="[{top: stickyTop + 'px'}]">
			<scroll-view scroll-x class="bg-white nav text-center" :scroll-with-animation="true"
				:scroll-left="scrollLeft">
				<view class="cu-item" :class="index==tabCur?'text-main-color cur':''"
					v-for="(item,index) in tabHeaderList" :key="index" @tap="tabSelect" :data-id="index">
					{{item.name}}
				</view>
			</scroll-view>
		</view>

		<!-- tab content -->
		<view class="margin-lr-sm margin-bottom-xl">
			<view class="margin-top-sm padding-bottom-sm bg-white" v-for="(shopOrder, index) in myOrders">
				<view class="cu-bar solid-bottom">
					<view class="action bar-first-action">
						<text class="cuIcon-shopfill text-main-color"></text>
						{{shopOrder.workerName}}
						<view>
							<view class="cuIcon-right"></view>
						</view>
					</view>
					<view class='cu-tag line-main-color radius margin-right-sm' v-if="shopOrder.payType == 0">在线支付单</view>
					<view class='cu-tag line-main-color radius margin-right-sm' v-else-if="shopOrder.payType == 1">上门到付单</view>
				</view>
				<view class="padding-lr">
					<view class="margin-top-sm" @click="showServDetail(shopOrder)">
						<product-picked :product="shopOrder" :pickedList="shopOrder.standardList"></product-picked>
					</view>
					<view class="flex justify-end align-end padding-bottom-sm" @click="showServDetail(shopOrder)">
						<view class="margin-right-sm"><text>总价</text><text class="text-price text-red">{{shopOrder.totalMoney}}</text>
						</view>
						<view class="margin-right-sm"><text>优惠</text><text class="text-price text-red">{{shopOrder.discountMoney}}</text>
						</view>
						<view class="margin-right-sm" v-if="shopOrder.changeMoney"><text>加价</text><text class="text-price text-red">{{shopOrder.changeMoney}}</text>
						</view>
						<view class="text-lg"><text>需付款</text><text
								class="text-price text-red text-lg text-bold">{{shopOrder.payMoney}}</text></view>
					</view>
					<view v-if="orderType === 0" class="padding-tb-sm">
						<view class="flex justify-end">
							<button v-if="[0,1].indexOf(shopOrder.orderStatus) >= 0" class="cu-btn bg-gray margin-right-sm shadow-blur" @click="showModalByRef('confirmModal', shopOrder)">取消订单</button>
							<button v-if="shopOrder.payStatus === 0" class="cu-btn bg-main-color shadow-blur margin-right-sm" @click="wxpay(shopOrder)">付款</button>
							<button class="cu-btn bg-main-color shadow-blur" @click="showServDetail(shopOrder)">查看</button>
						</view>
					</view>
					<view v-if="orderType === 0 && shopOrder.orderStatus === 4"
						class="padding-tb-sm solid-top">
						<view>师傅已提交完成，请验收。</view>
						<!-- <view>服务保障权益期：</view> -->
						<view class="flex justify-between align-end">
							<!-- <view>{{shopOrder.finishOrder.finishWaitUntil}}</view> -->
							<view>
								<button class="cu-btn sm bg-yellow margin-right-sm"
									@click="updateFinisheStatus(shopOrder, 5, false)">确认完单</button>
								<button class="cu-btn sm bg-yellow margin-right-sm" @click="showModalByRef('applyAfterService', shopOrder, {afterServiceType: 2, toUpdateStatus: true})">拒绝完单</button>
							</view>
						</view>
					</view>
					<view
						v-if="orderType === 0"
						class="padding-tb-sm solid-top">
						<view>约定服务时间：</view>
						<view class="flex justify-between align-end">
							<view>{{shopOrder.expectTimeStart + '~' + shopOrder.expectTimeEnd}}</view>
							<view>
								<button v-if="shopOrder.agreedServTime.customerAgreeStatus === 1"
									class="cu-btn sm bg-yellow margin-right-sm"
									@click="updateAgreeStatus(2, index)">同意</button>
								<button v-if="shopOrder.agreedServTime.customerAgreeStatus === 1"
									class="cu-btn sm bg-yellow margin-right-sm"
									@click="updateAgreeStatus(-1, index)">不同意</button>
								<button v-if="shopOrder.agreedServTime.customerAgreeStatus === 2"
									class="cu-btn sm bg-yellow margin-right-sm" disabled type="">已同意</button>
								<button v-if="shopOrder.agreedServTime.customerAgreeStatus === -1"
									class="cu-btn sm bg-yellow margin-right-sm" disabled type="">已否决</button>
							</view>
						</view>
					</view>
					<view v-else-if="orderType === 0 && shopOrder.subProcessStatus === 1"
						class="padding-tb-sm solid-top text-orange">
						路途遥远？服务内容稍难？时间紧迫？您可以试试追加赏金，重金之下必有勇夫噢！
					</view>
				</view>
			</view>
		</view>
		<load-status-bar ref="loadStatusBar" @loadMore="loadOrderPage"></load-status-bar>
		<confirm-modal ref="confirmModal" :content="'是否确定取消订单？'" @confirm="cancelOrder" @cancel="blurCurOrder"></confirm-modal>
		<apply-after-service ref="applyAfterService" :data="curOrder" @confirmFeedback="reloadOrderPage" @cancel="blurCurOrder"></apply-after-service>
	</view>
</template>

<script>
	import productPicked from '@/pages/my/components/product-picked.vue';
	import loadStatusBar from '@/components/custom-bar/load-status-bar.vue';
	import applyAfterService from '@/pages/my/components/modal/apply-after-service.vue';

	export default {
		components: {
			productPicked,
			loadStatusBar,
			applyAfterService
		},
		data() {
			return {
				curUserInfo: {},
				scrollLeft: 0,
				tabCur: 0,
				tabHeaderList: [],
				orderType: '',
				myOrders: [],
				pageParams: [],
				stickyTop: this.CustomBar,
				curOrder: null
			}
		},
		onLoad(options) {
			if (Boolean(options) && Boolean(options.tabInfo)) {
				let tabInfo = JSON.parse(decodeURIComponent(options.tabInfo));
				if (tabInfo.tabCur != null || tabInfo.tabCur != undefined) {
					this.tabCur = tabInfo.tabCur;
				}
				if (tabInfo.tabCur != null || tabInfo.tabCur != undefined) {
					this.orderType = tabInfo.orderType;
				}
				if (Array.isArray(tabInfo.tabHeaderList) && tabInfo.tabHeaderList.length > 0) {
					this.tabHeaderList = tabInfo.tabHeaderList;
					this.loadData();
				}
			}
		},
		methods: {
			loadData() {
				this.curUserInfo = this.$request.getCurUserInfo();
				for(let i = 0; i < this.tabHeaderList.length; i++) {
					this.pageParams.push({
						pageNum: this.$globalData.initPageNum
					});
				}
				// 真实对接口的时候使用
				// this.myOrders = await this.$api.data(this.orderType, mainProcess);
				// this.myOrders = await this.$api.data(mainProcess);
				this.loadOrderPage();
			},
			reloadOrderPage(params = {}) {
				this.pageParams = [];
				for(let i = 0; i < this.tabHeaderList.length; i++) {
					this.pageParams.push({
						pageNum: this.$globalData.initPageNum
					});
				}
				this.myOrders = [];
				this.$refs.loadStatusBar.showLoadMore();
				this.loadOrderPage(params);
			},
			async loadOrderPage(params = {}) {
				params.pageNum = this.pageParams[this.tabCur].pageNum;
				params.pageSize = this.$globalData.initPageSize;
				this.$refs.loadStatusBar.showLoading();
				try {
					params.customerId = this.curUserInfo.customerId;
					params.orderType = this.orderType;
					let orderStatus = this.tabHeaderList[this.tabCur].type;
					if (typeof orderStatus == 'string' && orderStatus.indexOf(",") > 0) {
						params.orderStatuses = orderStatus;
					} else {
						params.orderStatus = orderStatus;
					}
					if (this.tabCur === 0) {
						params.payStatus = 0;
						params.exceptOrderStatus = 6;
					}
					let res = null;
					if (this.tabCur === 3) {
						res = await this.$request.getAfterList({
							customerId: params.customerId
						});
					} else {
						res = await this.$request.qryOrderPage(params);
					}
					let rowsLength = res.rows.length;
					if (rowsLength > 0) {
						this.myOrders = this.myOrders.concat(res.rows);
						this.pageParams[this.tabCur].pageNum++;
						if (rowsLength === this.pageSize) {
							this.$refs.loadStatusBar.showLoadMore();
						}
					}
					this.$refs.loadStatusBar.showLoadOver();
				} catch (e) {
					console.error(e)
					this.$refs.loadStatusBar.showLoadErr();
				}
			},
			tabSelect(e) {
				this.tabCur = e.currentTarget.dataset.id;
				this.scrollLeft = (e.currentTarget.dataset.id - 1) * 60;
				this.reloadOrderPage();
			},
			updateAgreeStatus(status, index) {
				this.myOrders[index].agreedServTime.customerAgreeStatus = status;
			},
			async updateFinisheStatus(order, status, ifRollback) {
				let res = await this.$request.updateOrder({
					id: order.orderMasterId,
					orderStatus: status
				});
				if (res && res.code === 0) {
					this.reloadOrderPage();
					if (ifRollback) {
						uni.showToast({
							title: '订单已回滚至服务中状态，请联系师傅',
							icon: 'none',
							duration: 3000
						})
					}
				}
				return res;
			},
			showServDetail(order) {
				uni.navigateTo({
					url: '/pages/my/serv-detail?order=' + encodeURIComponent(JSON.stringify(order))
				})
			},
			showModalByRef(refName, curOrder, params) {
				this.$refs[refName].showModal(curOrder, params);
				this.curOrder = curOrder;
			},
			blurCurOrder() {
				this.curOrder = null;
			},
			async cancelOrder() {
				let res = await this.$request.cancelMasterOrder({
					orderMasterId: this.curOrder.orderMasterId
				});
				if (res && res.code === 0) {
					this.reloadOrderPage();
					uni.showToast({
						title: '取消成功',
						icon: 'success',
						duration: 2000
					})
				} else {
					uni.showToast({
						title: '取消失败',
						icon: 'error'
					})
				}
			},
			async wxpay(curOrder) {
				try {
					// 获取微信支付所需参数
					let wxPayParams = {
						code: this.$request.getCurUserInfo().openId,
						orderMasterCode: curOrder.orderMasterCode
					}
					let wxPayParamRes = await this.$request.getWxPayParams(wxPayParams);
					// 拉起微信支付窗口,支付成功跳转到支付成功页面
					let payInfo = JSON.parse(wxPayParamRes.data.expend.pay_info);
					let wxPayRes = await wx.requestPayment(payInfo);
					if (wxPayRes.errMsg === "requestPayment:ok") {
						uni.navigateTo({
							url: '/pages/order/pay-result?payResult=0'
						})
					} else {
						throw 'err';
					}
				} catch(e) {
					// 支付失败弹出提示并跳转到我的订单待支付页
					uni.navigateTo({
						url: '/pages/order/pay-result?payResult=1'
					})
				}
			}
		}
	}
</script>

<style scoped>
	.bar-first-action {
		margin-left: unset !important;
		padding-left: 40rpx;
		font-size: 30rpx !important;
	}

	.cu-btn.sm {
		padding: 0 20rpx;
		font-size: 23rpx;
		height: 48rpx;
	}
</style>
