<template>
	<zj-page-layout :hasFooter="true" :isScroll="true" :refresherTriggered="refresherTriggered"
		@refresherrefresh="refresherrefresh" @scrolltolower="scrolltolower">
		<template slot="header">
			<view class="search-container">
				<u-search shape="round" :showAction="false" placeholder="输入分类名称进行搜索" v-model="keyword"
					@search="refreshList" @clear="clearSearch">
				</u-search>
			</view>
				<u-tabs :scrollable="true" :list="tabList" :current="curTab" @click="changeTab" lineColor="#3D8FFD"
					:activeStyle="{color: '#3D8FFD'}" :inactiveStyle="{color: '#666666'}" itemStyle="height: 88rpx;">
				</u-tabs>
			</view>
		</template>

		<view class="list-container">
			<view v-for="(item, index) in orderList" :key='index' class="item" @tap="toOrderDetail(item.id)">
				<view class="top">
					<view class="left">{{item.id}}</view>
					<view class="right" :style="{'color': filterStatus(item,'color')}">{{filterStatus(item,'name')}}</view>
				</view>
				<view class="content">
					<image :src="item.categoryUrl" mode="aspectFill"></image>
					<view class="right">
						<view class="name">{{item.goodsLeaseName}}</view>
						<view class="name remark">{{item.repairRemark}}</view>
						<view class="text">下单日期 {{item.createTime}}</view>
						<view class="text date" v-if="item.startDate  && (item.realEndDate || item.endDate)">租赁时间 {{item.startDate.substring(0,10) + ' 至 ' + (item.realEndDate?item.realEndDate.substring(0,10):item.endDate.substring(0,10))}}</view>
					</view>
				</view>
				<view class="btn" @tap.stop>
					<view v-if="!item.payStatus">
						<u-button type="primary" style="width: 180rpx;" size="small" shape="circle" color="#428dff" text="去支付" @click="payOrder(item.id)"></u-button>
					</view>
					<view class="flex" v-else>
						<u-button type="primary" size="small" v-if="item.status == 'LEASE' || item.status == 'OVER'" style="width: 210rpx;margin-right: 20rpx" shape="circle" color="#428dff" text="我要续租" @click="toRelet(item.id)"></u-button>
						<u-button type="primary" size="small" style="width: 210rpx;" shape="circle" color="#428dff" text="我要报修" v-if="item.status == 'LEASE'" @click="toRepair(item.id)"></u-button>
					</view>
				</view>
			</view>
		</view>

		<Loading :loadStatus="loadStatus" :dataList="orderList" />
	</zj-page-layout>
</template>

<script>
	import {
		weixinPay,
		mini_env
	} from '@/common/utils/util.js';

	export default {
		data() {
			return {
				configInfo: {},
				tabList: [{
						key: '',
						status: {
							payStatus: '',
							status: ''
						},
						name: '全部'
					},
					{
						key: '',
						status: {
							payStatus: false,
							status: ''
						},
						name: '待付款'
					},
					{
						key: '',
						status: {
							payStatus: true,
							status: 'WAIT'
						},
						name: '待审核'
					},
					{
						key: '',
						status: {
							payStatus: true,
							status: 'WAIT_START'
						},
						name: '待开始'
					},
					{
						key: '',
						status: {
							payStatus: true,
							status: 'LEASE'
						},
						name: '租赁中'
					},
					{
						key: '',
						status: {
							payStatus: true,
							status: 'OVER'
						},
						name: '已到期'
					},
				],
				tabCurrent: '', // 当前tab状态
				tabStatus: {
					payStatus: '',
					status: ''
				},
				orderList: [], // 订单列表
				loadStatus: 0,
				refresherTriggered: false, // 下拉刷新状态
				pageNum: 1,
				keyword: ''
			}
		},

		computed: {
			curTab() {
				return this.tabList.map(item => item.key).indexOf(this.tabCurrent) || 0;
			},
			filterStatus(){
				return function(item,type){
					if(!item.payStatus){
						return {name: '待付款',color: '#ce68ff'}[type]
					}else{
						if(item.status == 'WAIT'){
							return {name: '待审核',color: '#ff5300'}[type]
						}
						else if(item.status == 'WAIT_START'){
							return {name: '待开始',color: '#64c842'}[type]
						}else if(item.status == 'LEASE'){
							return {name: '租赁中',color: '#1281ff'}[type]
						}else if(item.status == 'OVER'){
							return {name: '待回收',color: '#9c84fe'}[type]
						}else if(item.status == 'RECOVER'){
							return {name: '已回收',color: '#817f7f'}[type]
						}
					}
				}
			}
		},

		async onLoad() {
			this.getOrderList();
			this.configInfo = await this.$getConfigInfo();
			this.crossPage.$on('refreshOrderList', (data) => {
				this.refreshList();
			})
		},

		onUnload() {
			this.crossPage.$off('refreshOrderList');
		},

		methods: {
			getOrderList() {
				this.loadStatus = 1;
				let url = '/lease/order/list/page';
				this.$api.post(url, {
					pageNum: this.pageNum,
					pageSize: 10,
					keyword: this.keyword,
					userId: this.$store.state.user.userId,
					...this.tabStatus,
				}).then(res => {
					this.loadStatus = 0;
					let list = res.data.records;
					if (list.length < 10) {
						this.loadStatus = 2;
					}
					this.orderList = this.orderList.concat(list);
				}).catch(() => {
					this.loadStatus = 2;
				}).finally(res => {
					this.refresherTriggered = false;
				})
			},

			// 滚动到底部
			scrolltolower(e) {
				if (this.loadStatus === 0) {
					this.pageNum++;
					this.getOrderList();
				}
			},

			// 触发下拉刷新
			async refresherrefresh(e) {
				this.refresherTriggered = true;
				this.refreshList();
			},

			refreshList() {
				this.orderList = [];
				this.pageNum = 1;
				this.getOrderList();
			},

			getRefundNum(orderDetails) {
				let refundNum = 0;
				orderDetails.forEach(item => {
					if (item.refund) {
						refundNum = refundNum + item.refundNum;
					}
				})
				return refundNum;
			},

			// 搜索
			clearSearch() {
				this.keyword = ''
				this.refreshList();
			},

			// 切换类型
			changeTab(item) {
				this.tabCurrent = item.key;
				this.tabStatus = item.status
				this.refreshList();
			},

			// 去订单详情
			toOrderDetail(id) {
				this.$navToPage({
					url: '/packageWorkorder/pages/tenancyOrderDetail?id='+id
				})
			},

			//去续租
			toRelet(id){
				this.$navToPage({
					url: '/packageWorkorder/pages/tenancyReletOrder?id=' + id
				})
			},

			//去报修
			toRepair(id){
				this.$navToPage({
					url: '/packageWorkorder/pages/tenancyRepairOrder?id=' + id
				})
			},

			// 立即付款
			payOrder(id) {
				mini_env((bool) => {
					let that = this;
					this.$api.post('/lease/order/pay', {
						userId: this.$store.state.user.userId,
						id,
						...(() => {
							if (bool) {
								return {
									miniPay: true,
									openId: this.$store.state.user.miniOpenId
								}
							}
							return {}
						})()
					}).then(res => {
						if (bool) {
							uniWebview.navigateTo({
								url: `/pages/pay/pay?${Object.entries({
                ...res.data,
                payPackage: res.data.payPackage.split("=")[0] || "",
                payPackageVal: res.data.payPackage.split("=")[1] || ""
              }).map(item => item.join("=")).join("&")}`
							})
						} else {
							weixinPay(res.data, function(res) {
								that.$successToast('支付成功');
								that.pageNum = 1;
								that.getOrderList();
								that.requestMessage();
							})
						}
					})
				})
			},

			// 消息推送
			requestMessage() {
				let that = this;
				uni.showModal({
					title: '温馨提示',
					content: '为更好的促进您与买家的交流，需要在您的订单成交时向您发送消息',
					confirmText: "同意",
					cancelText: "拒绝",
					success: function(res) {
						if (res.confirm) {
							let tmplIds = [that.configInfo.template];
							uni.requestSubscribeMessage({
								tmplIds: tmplIds,
								success(res) {
									let status = null;
									tmplIds.map((item, index) => {
										if (res[item] == 'accept') {
											status = 'accept';
										}
									})
									if (status == 'accept') {
										that.$successToast('订阅成功');
									} else {
										that.$toast('订阅取消');
									}
								},
								fail(res) {
									console.log(res);
									that.$toast('订阅失败');
								}
							})
						} else if (res.cancel) {
							uni.showModal({
								title: '温馨提示',
								content: '拒绝后您将无法获取实时的与卖家（买家）的交易消息',
								confirmText: "知道了",
								showCancel: false,
								success: function(res) {

								}
							});
						}
					}
				});
			},

			navToPage(url) {
				this.$navToPage({
					url
				})
			},
		}
	}
</script>

<style lang="scss">
	.tab-container {
		background: #ffffff;
	}

	.search-container {
		background: #ffffff;
		padding: 20rpx;
		margin-bottom: 20rpx;
		::v-deep .u-search {
			height: 60rpx;

			input {
				background: #F7F8FF !important;
			}

			.u-search__content {
				background: #F7F8FF !important;
				height: 60rpx;
			}
		}
	}

	.list-container {
		padding: 1rpx 20rpx 0;

		.item {
			@include zj-card;
			margin-top: 20rpx;
			background: #FFFFFF;
			border-radius: 20rpx;
			padding: 20rpx;

			.top {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20rpx;
				.left {
					font-size: 28rpx;
					font-weight: 500;
				}

				.right {
					font-size: 30rpx;
				}
			}

			.goods {
				display: flex;
				justify-content: space-between;
				margin-top: 20rpx;

				&.goods0 {
					margin-top: 0;
				}

				image {
					width: 140rpx;
					height: 140rpx;
					display: block;
					flex-shrink: 0;
					margin-right: 20rpx;
				}

				.main {
					flex: 1;
					display: flex;
					justify-content: space-between;

					.left {
						.name {
							font-size: 28rpx;
							color: #333333;
							line-height: 36rpx;
						}

						.des {
							font-size: 28rpx;
							color: #999999;
							margin-top: 10rpx;
						}
					}

					.right {
						flex-shrink: 0;
						margin-left: 20rpx;
						text-align: right;

						.price {
							font-size: 28rpx;
							color: #333333;
							line-height: 28rpx;
							font-weight: 600;
							margin-top: 6rpx;
						}

						.num {
							font-size: 28rpx;
							color: #999999;
							line-height: 28rpx;
							margin-top: 16rpx;
						}
					}
				}
			}

			.total {
				display: flex;
				justify-content: space-between;
				height: 50rpx;
				align-items: center;

				.left {
					font-size: 24rpx;
					color: #666666;
				}

				.right {
					font-size: 24rpx;
					color: #666666;

					text {
						color: $minor-color;
						font-size: 32rpx;
						font-weight: 600;
						margin-left: 8rpx;
					}
				}
			}

			.btn-group {
				border-top: 1px solid #eaeaea;
				height: 100rpx;
				display: flex;
				justify-content: flex-end;
				align-items: center;

				&.btn-group2 {
					justify-content: space-between;

					.tips {
						font-size: 28rpx;
						color: $minor-color;
					}

					.btns {
						display: flex;
					}
				}

				.button {
					width: 140rpx;
					height: 48rpx;
					border-radius: 48rpx;
					text-align: center;
					line-height: 48rpx;
					font-size: 24rpx;
					margin-left: 20rpx;
					flex-shrink: 0;

					&:first-child {
						margin-left: 0;
					}

					&.gray {
						color: #999999;
						border: 1px solid #999999;
					}

					&.white {
						color: $theme-color;
						border: 1px solid $theme-color;
					}

					&.red {
						color: #FFFFFF;
						border: 1px solid $theme-color;
						background: $theme-color;
					}
				}
			}
		}
		.content{
			display: flex;
			align-items: center;
			border-bottom: 1rpx solid #eeeeee;
			box-sizing: border-box;
			image {
				width: 140rpx;
				height: 140rpx;
				margin-right: 20rpx;
			}
			.right{
				.name{
					font-weight: bold;
					color: #000000;
					font-size: 32rpx;
					line-height: 36rpx;
					margin-bottom: 20rpx;
				}
				.text{
					font-size: 26rpx;
					margin-bottom: 20rpx;
				}
				.date{
					color: #ff5300;
				}
				.remark{
					font-size: 26rpx;
					color: #59a7ff;
				}
			}
		}
		.btn{
			width: 100%;
			display: flex;
			justify-content: flex-end;
		}
	}
</style>
