<template>
	<view class="container">
		<view class="tab-box">
			<u-tabs :list="tabList" lineHeight="0" :current="currentTab" @click="onChangeTab"
				:scrollable="true" lineColor="#FFF" :inactiveStyle="{'font-size': '28rpx'}"
				:activeStyle="{'font-size': '32rpx', 'color': '#EB7318'}"></u-tabs>
		</view>

		<view class="order-list">
			<u-loading-icon :show="loadingIcon" size="30" mode="semicircle"></u-loading-icon>
			<!--  v-if="!loadingIcon" -->
			<view style="height: 100%;">
				<scroll-view scroll-y class="scroll-view" @scrolltolower="scrolltolower"
					style="height: 100%;">
					<view v-for="(item, index) in 10" :key="index" @click="toDetails(item)" class="item">
						<view class="title">
							<view class="fs-28 flex flex-align-center">
								<text>订单编号：14451</text>
							</view>
							<!-- 物流订单 -->
							<view>
								<text v-if="item.status === '0'" style="color: #EB7318;">待付款</text>
								<text v-else-if="item.status === '1'" style="color: #EB7318;">待发货</text>
								<text v-else-if="item.status === '2'" style="color: #FFBB00;">待收货</text>
								<text v-else-if="item.status === '3'" style="color: #FFBB00;">已完成</text>
								<text v-else-if="item.status === '4'" style="color: #999999;">交易关闭</text>
							</view>
						</view>
						<view class="mt-20">
							<view v-for="(goods, goodsIndex) in 2" :key="goodsIndex" class="order-info">
								<image class="w-200 h-200 mr-20 br-16" 
									src="@/static/logo.png"></image>
								<view class="right">
									<view class="flex flex-column">
										<text>商品名称</text>
										<text class="fs-28 mt-20">规格：白色</text>
									</view>
									<text class="fw-600 fs-36" style="color: #EB7318;">￥200</text>
								</view>
							</view>
						</view>
						
						<view class="pay-money">
							<text class="fs-28">共2件商品</text>
							<text class="ml-20 fs-36">应付款：¥200</text>
						</view>
						
						<!-- 待付款 -->
						<view v-if="index == '0'" class="order-btn-box">
							<view @click.stop="cancelOrder(item)" class="minor-btn">
								<text>取消订单</text>
							</view>
							<view @click.stop="orderPay(item)" class="main-btn ml-32">
								<text>去付款</text>
							</view>
						</view>
						
						<!-- 待发货 -->
						<view v-else-if="index == '1' && item.iszt == '0'" class="order-btn-box">
							<view @click.stop="$wskj.to('/pages/chatmsg')" class="minor-btn">
								<text>联系客服</text>
							</view>
							<view @click.stop="onRemind(item)" class="main-btn ml-32">
								<text>提醒发货</text>
							</view>
						</view>
						
						<!-- 待自提 -->
						<view v-else-if="item.status === '1' && item.iszt == '1'"  class="order-btn-box">
							<view @click.stop="$wskj.to('/pages/chatmsg')" class="minor-btn">
								<text>联系客服</text>
							</view>
						</view>
						
						<!-- 待收货 -->
						<view v-else-if="item.status === '2' && item.iszt == '0'" class="order-btn-box">
							<view @click.stop="$wskj.to('/pages/chatmsg')" class="minor-btn">
								<text>联系客服</text>
							</view>
							<view v-if="item.iszt == '0'" @click.stop="$wskj.to('/pages/my/order/logistics?orderId=' + item.id)" class="order-btn-grey">
								<text>查看物流</text>
							</view>
							<view @click.stop="onShouHuo(item)" class="main-btn ml-32">
								<text>确认收货</text>
							</view>
						</view>
						
						<!-- 待自提 -->
						<view v-else-if="item.status === '2' && item.iszt == '1'"  class="order-btn-box">
							<view @click.stop="$wskj.to('/pages/chatmsg')" class="minor-btn">
								<text>联系客服</text>
							</view>
							<view @click.stop="getQrCode(item)" class="main-btn ml-32">
								<text>核销码</text>
							</view>
						</view>
						
						<!-- 已完成 -->
						<view v-else-if="item.status === '3'" class="order-btn-box">
							<view @click.stop="delOrder(item)" class="minor-btn">
								<text>删除订单</text>
							</view>
							<view v-if="item.iszt == '0'" @click.stop="$wskj.to('/pages/my/order/logistics?orderId=' + item.id)" class="order-btn">
								<text>查看物流</text>
							</view>
						</view>
						
						<!-- 交易关闭 -->
						<view v-else-if="item.status === '4'" class="order-btn-box">
							<view @click.stop="delOrder(item)" class="minor-btn">
								<text>删除订单</text>
							</view>
						</view>
					</view>
				</scroll-view>
				
				<!-- 订单列表为空 -->
				<!-- <emptydata v-else></emptydata> -->
			</view>
		</view>
		
		<!-- 取消订单弹窗 -->
		<u-popup :show="cancelShow" round="10" @close="cancelShow = false">
			<view class="cancel-box">
				<view class="title">
					<text @click="cancelShow = false" class="fs-26" style="color: #999;">取消</text>
					<text class="fs-30" style="color: #333333;">取消订单</text>
					<text @click="onConfirmCancelOrder" class="fs-26" style="color: #FF5811;">确定</text>
				</view>
				<view class="fs-30 mt-30 mb-30" style="color: #333333;">
					<text>请选择取消原因</text>
				</view>
				<view class="reson-list">
					<view v-for="(item, index) in cancelResonList" :key="index" class="reson-item">
						<text>{{ item.title }}</text>
						<image v-if="currentReson === item.id" src="@/static/is-select.png"></image>
						<image v-else @click="currentReson = item.id" src="@/static/select.png"></image>
					</view>
				</view>
			</view>
		</u-popup>
		
		<!-- 支付弹窗 -->
		<wskj-modal :show="orderPayShow" confirmText="确定" confirmColor="#EB7318" :showCancelButton="true"
			@close="orderPayShow = false" @cancel="orderPayShow = false" @confirm="onConfirmOrderPay">
			<view style="padding: 40rpx 0;width: 100%;">
				<view class="center fs-45">
					<text>￥{{ payMoney }}</text>
				</view>
				<!-- 支付方式 -->
				<view class="pay-type-box">
					<view class="title" style="padding: 0;">
						<text>选择支付方式：</text>
					</view>
					<view class="item">
						<view>
							<image src="@/static/balance.png"></image>
							<text>我的钱包（余额：¥{{ user.userInfo.money }}）</text>
						</view>
						<image v-if="currentPayMtd === 'balance'" src="@/static/is-select.png"></image>
						<image v-else @click="currentPayMtd = 'balance'" src="@/static/select.png"></image>
					</view>
					<view class="item">
						<view>
							<image src="@/static/wechatpay.png"></image>
							<text>微信支付</text>
						</view>
						<image v-if="currentPayMtd === 'wechat'" src="@/static/is-select.png"></image>
						<image v-else @click="currentPayMtd = 'wechat'" src="@/static/select.png"></image>
					</view>
				</view>
			</view>
		</wskj-modal>
		
		<lyy-pass-input ref="passInput" title="金额" :money="payMoney" @confirm="onPayPassConfirm"> </lyy-pass-input>
		
		<!-- 删除订单弹窗 -->
		<wskj-modal :show="delOrderShow" confirmText="删除" confirmColor="#EB7318" :showCancelButton="true"
			@close="delOrderShow = false" @cancel="delOrderShow = false" @confirm="onConfirmDelOrder">
			<view class="center" style="padding: 40rpx 0;">
				<text>删除后订单不可恢复，确认删除该订单？</text>
			</view>
		</wskj-modal>
		
		<!-- 确认收货弹窗 -->
		<wskj-modal :show="shouhuoShow" confirmText="确定" confirmColor="#EB7318" :showCancelButton="true"
			@close="shouhuoShow = false" @cancel="shouhuoShow = false" @confirm="onConfirmShouHuo">
			<view>
				<view class="center">
					<image class="w-200 h-200" :src="currentGoodImage"></image>
				</view>
				<view class="mt-40 center">
					<text>确认收到这{{ goodsNumber }}件货了吗？</text>
				</view>
			</view>
		</wskj-modal>
		
	</view>
</template>

<script>
	import { mapState } from "vuex"
	export default {
		data() {
			return {
				tabList: [{
						name: '全部',
					}, {
						name: '待付款',
					},
					{
						name: '待发货',
					},
					{
						name: '待自提',
					},{
						name: '待收货'
					},
					{
						name: '已完成'
					}
				],
				currentTab: 0,
				
				orderList: [],
				currentPage: 1,
				isEmpty: false,
				
				currentOrderId: '',
				
				loadingIcon: false,
				
				orderPayShow: false, // 支付弹窗
				currentPayMtd: 'balance', // 支付方式
				payMoney: 0,

				delOrderShow: false,
				
				cancelResonList: [], // 取消订单原因
				currentReson: '',
				cancelShow: false,
				
				shouhuoShow: false,
				currentGoodImage: '',
				goodsNumber: 0,
				
				qrCodeShow: false 
			}
		},
		onLoad(options) {
			// console.log(options)
			if(options.currentTab) {
				this.currentTab = Number(options.currentTab)
			} else {
				this.currentTab = 0
			}
			this.getOrderList('init') // 获取订单列表
			this.getCancelOrderResonList() // 获取取消订单原因
			
			uni.$on('delOrder', () => {
				this.orderList = []
				this.currentPage = 1
				this.isEmpty = false
				this.getOrderList('init') // 获取订单列表
			})
		},
		computed: {
			...mapState(['user']),
			getStatus(){
				let status = ''
				if(this.currentTab == '0'){
					status = 'all'
				} else if(this.currentTab == '1'){
					status = '0'
				} else if(this.currentTab == '2'){
					status = '1'
				} else if(this.currentTab == '3'){
					status = '4'
				} else if(this.currentTab == '4'){
					status = '2'
				} else if(this.currentTab == '5'){
					status = '3'
				}
				return status
			}
		},
		methods: {
			onChangeTab(e) {
				this.currentTab = e.index
				
				this.orderList = []
				this.currentPage = 1
				this.isEmpty = false
				this.getOrderList('init')
			},
			// 获取订单列表
			getOrderList(type) {
				if(type === 'init') {
					this.loadingIcon = true
				}
				const params = {
					url: '/api/userinfo/myorderlist',
					data: {
						page: this.currentPage,
						status: this.getStatus
					}
				}
				this.$request(params).then(res => {
					// console.log(res)
					this.orderList = this.orderList.concat(res.data)
					if (res.data.length === 0) {
						this.isEmpty = true
					}
					this.loadingIcon = false
				}).catch(err => {
					this.loadingIcon = false
				})
			},
			// 获取取消订单原因
			getCancelOrderResonList(){
				const params = {
					url: '/api/userinfo/getcanclereason',
					data: {
						
					}
				}
				this.$request(params).then(res => {
					this.cancelResonList = res.data
				}).catch(err => {
					
				})
			},
			scrolltolower(e) {
				if (!this.isEmpty) {
					this.currentPage += 1
					this.getOrderList()
				}
			},
			// 去详情页
			toDetails(item) {
				uni.navigateTo({
					url: '/pages/my/order/orderdetails?orderId=' + item.id
				})
			},
			// 取消订单
			cancelOrder(item) {
				this.currentOrderId = item.id
				this.cancelShow = true
			},
			// 确定取消订单
			onConfirmCancelOrder(){
				if(this.currentReson === '') {
					return this.$u.toast('请选择取消原因')
				}
				this.cancelShow = false
				const params = {
					url: '/api/userinfo/usercancle',
					loadingTip: '',
					data: {
						orderid: this.currentOrderId,
						canclereason: this.cancelResonList.filter(item => item.id === this.currentReson)[0].title
					}
				}
				this.$request(params).then(res => {
					this.orderList = []
					this.currentPage = 1
					this.isEmpty = false
					
					this.getOrderList('init')
				}).catch(err => {
					this.$u.toast(err.msg || '取消失败')
				})
			},
			orderPay(item){
				this.currentOrderId = item.id
				
				const index = this.orderList.findIndex(item => item.id === this.currentOrderId)
				this.payMoney = this.orderList[index].paymoney
				
				this.orderPayShow = true
			},
			// 选择支付方式弹窗确定
			onConfirmOrderPay(){
				this.orderPayShow = false
				
				if(this.currentPayMtd === 'balance') {
					if(!this.user.userInfo.paypassword) {
						uni.showModal({
							content: '请先设置支付密码',
							confirmText: '去设置',
							confirmColor: '#EB7318',
							success: (res) => {
								if (res.confirm) {
									this.$wskj.to('/pages/my/setting/checkmobile')
								}
							}
						})
						return false
					}
					this.$refs['passInput'].open()
				} else {
					this.requestOrderPay()
				}
			},
			// 支付密码输入完成
			onPayPassConfirm(e){
				this.$refs['passInput'].close()
				this.requestOrderPay(e.pass)
			},
			requestOrderPay(payPassword){
				const params = {
					url: '/api/userinfo/payorder',
					loadingTip: '',
					data: {
						orderid: this.currentOrderId,
						paytype: this.currentPayMtd === 'balance'? '1' : '3'
					}
				}
				if(this.currentPayMtd === 'balance'){
					params.data.password = payPassword
				}
				this.$request(params).then(payRes => {
					if (payRes.code === 1) {
						if(this.currentPayMtd === 'wechat'){
							uni.requestPayment({
								provider: 'wxpay',
								appid: payRes.data.appId, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
								nonceStr: payRes.data.nonceStr, // 随机字符串
								package: payRes.data.package, // 固定值
								timeStamp: payRes.data.timeStamp, // 时间戳（单位：秒）
								paySign: payRes.data.paySign ,// 签名，这里用的 MD5/RSA 签名
								signType: 'MD5',
								success: (res) => {
									this.$u.toast('支付成功')
									
									this.orderList = []
									this.currentPage = 1
									this.isEmpty = false
									this.getOrderList('init')
								},
								fail: (err) => {
									console.log(err);
								}
							});
						} else {
							this.$u.toast('支付成功')
							
							this.orderList = []
							this.currentPage = 1
							this.isEmpty = false
							this.getOrderList('init')
						}
					} else {
						this.$u.toast(res.msg || '支付失败')
					}
				}).catch(err => {
					this.$u.toast(err.msg || '支付失败')
				})
			},
			delOrder(item){
				this.currentOrderId = item.id
				this.delOrderShow = true
			},
			// 确认删除订单
			onConfirmDelOrder(){
				this.delOrderShow = false
				const params = {
					url: '/api/userinfo/delorder',
					loadingTip: '',
					data: {
						orderid: this.currentOrderId
					}
				}
				this.$request(params).then(res => {
					const index = this.orderList.findIndex(key => key.id === this.currentOrderId)
					this.orderList.splice(index, 1)
					this.$u.toast('删除成功')
				}).catch(err => {
					this.$u.toast(err.msg || '操作失败')
				})
			},
			// 提醒发货
			onRemind(item){
				const params = {
					url: '/api/userinfo/tixing',
					loadingTip: '',
					data: {
						orderid: item.id
					}
				}
				this.$request(params).then(res => {
					this.$u.toast('提醒成功')
				}).catch(err => {
					this.$u.toast(err.msg || '操作失败')
				})
			},
			onShouHuo(item){
				this.currentOrderId = item.id
				this.goodsNumber = item.goods.length
				this.currentGoodImage = item.goods[0].goodsimage
				
				this.shouhuoShow = true
			},
			// 确认收货
			onConfirmShouHuo(){
				this.shouhuoShow = false
				const params = {
					url: '/api/userinfo/makeorder',
					loadingTip: '',
					data: {
						orderid: this.currentOrderId
					}
				}
				this.$request(params).then(res => {
					const index = this.orderList.findIndex(key => key.id === this.currentOrderId)
					this.orderList.splice(index, 1)
					this.$u.toast('收货成功')
				}).catch(err => {
					this.$u.toast(err.msg || '操作失败')
				})
			},
			onSave() {
				uni.canvasToTempFilePath({
						canvasId: 'qrcode',
						width: 150,
						height: 150,
						success: res => {
							// console.log(res);
							uni.saveImageToPhotosAlbum({
							    filePath: res.tempFilePath,
							    success: res => {
							        console.log(res);
									this.$u.toast('保存成功')
							    },
							    fail: err => {
									this.$u.toast('保存失败')
							        console.log(err);
							    }
							});
						},
						fail: err => {
							this.$u.toast('保存失败')
							console.log(err);
						}
					},
				);
			},
		}
	}
</script>

<style scoped>
	.container {
		height: 100%;
	}

	.tab-box {
		height: 60rpx;
		padding: 20rpx;
		background-color: #FFF;
	}


	.order-list {
		overflow: hidden;
		height: calc(100% - 60rpx);
		background-color: #F5F5F5
	}

	.scroll-view .item {
		background-color: #FFF;
		border-radius: 20rpx;
		margin-bottom: 20rpx;
		padding-bottom: 20rpx;
		position: relative;
	}
	.scroll-view .item:last-child {
		margin-bottom: 0;
	}

	.title {
		padding: 20rpx;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}

	.order-info {
		padding: 0 20rpx;
		margin-bottom: 40rpx;
		display: flex;
		align-items: center;
	}
	.order-info > .right {
		flex: 1;
		height: 200rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}
	
	.pay-money {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		margin-top: 40rpx;
		padding: 0 20rpx;
	}
	
	.order-btn-box {
		margin-top: 20rpx;
		padding: 0 20rpx 0;
		display: flex;
		justify-content: flex-end;
		align-items: center;
	}
	.order-btn-grey {
		color: #999999;
	}
	.order-btn {
		/* width: 160rpx;
		height: 64rpx;
		text-align: center;
		line-height: 64rpx;
		background-color: #EB7318;
		color: #FFF;
		border-radius: 8rpx;
		font-size: 28rpx;
		margin-left: 30rpx; */
	}
	
	
	
	
	.cancel-box {
		padding: 10rpx 20rpx;
	}
	.cancel-box > .title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 28rpx;
		color: #333333;
	}
	.reson-list {
		
	}
	.reson-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 30rpx;
		margin-bottom: 30rpx;
	}
	.reson-item > image {
		width: 32rpx;
		height: 32rpx;
	}
	
	
	
	.pay-type-box {
		margin-top: 50rpx;
	}
	.pay-type-box > .title {
		font-size: 32rpx;
	}
	.pay-type-box > .item {
		margin-top: 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.pay-type-box > .item > view{
		display: flex;
		align-items: center;
		font-size: 28rpx;
	}
	.pay-type-box > .item > view > image{
		width: 60rpx;
		height: 50rpx;
		margin-right: 30rpx;
	}
	.pay-type-box > .item >image {
		width: 40rpx;
		height: 40rpx;
	}
</style>