<template>
	<view class="my-order">
		<custom-nav noback="noback" transparent="transparent" ref="ltm" title=" " />
		<view class="content">
			<view class="swiper-nav">
				<view v-for="(item, index) in typeList" :key="index" class="item" :class="{ active: MIXIN_ActiveIndex === index }" @tap="switchSwiper(index)">{{ item }}</view>
				<view class="moveBar" :style="{ left: MIXIN_MoveBarLeft + 'px', width: 100 / typeList.length + '%' }"><text></text></view>
			</view>
			<view class="swiper-area">
				<swiper class="swiper" :current="MIXIN_NowIndex" :duration="234" @transition="MIXIN_transition" @change="MIXIN_change" @animationfinish="MIXIN_animationfinish">
					<swiper-item v-for="(typeValue, typeKey) in lists" :key="typeKey">
						<scroll-view scroll-y :style="{ height: MIXIN_ScrollViewHeight + 'px' }" @scrolltolower="MIXIN_scrolltolower">
							<view class="order-item" v-for="(orderItem) in lists[typeKey]" :key="orderItem.order_num" @click="toDetail(orderItem)">
								<view class="order-num">
									<text>订单编号：{{ orderItem.order_num }}</text>
									<text class="fsdfsd" :class="orderItem | orderStatus | orderStatusClass">{{ orderItem | orderStatus }}</text>
								</view>
								<view class="good-item">
									<view class="imgs">
										<image v-for="(item, index) in orderItem.order" :key="index" :src="item.main_img"></image>
									</view>
									<view class="info">
										<text class="name">种类：{{ orderItem.type }}{{ '， ' }}</text>
										<text class="num">数量：{{ orderItem.total }}{{ '， ' }}</text>
										<text class="price">共计金额：<text class="basecolor">￥{{ orderItem.money }}</text></text>
									</view>
								</view>
								<view class="bottom-bar">
									<text class="time">{{ orderItem.created_at }}</text>
									<!-- <view class="btn" v-if="!orderItem.is_deleted && !orderItem.pay_status" @click.stop="changeOrder(orderItem)">修改订单</view> -->
									<view class="btns">
										<view class="btn" @click.stop="buyAgain(orderItem)">再次购买</view>
										<view v-if="orderItem.express_num && orderItem.express_code" class="btn" @click.stop="express(orderItem.express_num, orderItem.express_code)">查看物流</view>
										<view class="btn bg" v-if="!orderItem.is_deleted && !orderItem.pay_status" @click.stop="payNow(orderItem)">立即付款</view>
										<view class="btn border" v-if="!orderItem.is_deleted && orderItem.pay_status && orderItem.status == 3" @click.stop="received(orderItem)">确认收货</view>
									</view>
								</view>
							</view>
							<custom-reach-bottom v-if="lists[typeKey].length" :nomore="page[typeKey] === 0" />
							<swiper-status v-else :page="page[typeKey]" />
						</scroll-view>
					</swiper-item>
				</swiper>
			</view>
		</view>
	</view>
</template>

<script>
	import { _API_GoodList } from '@/apis/good.js'
	import { deepClone } from '@/common/util/index.js'
	import MIXIN from '@/mixin/swiper-list.js'
	import swiperStatus from '@/components/public/swiper-status.vue'
	import pulldownRefresher from '@/components/public/pulldown-refresher.vue'
	import customReachBottom from '@/components/public/custom-reach-bottom.vue'
	// import { _API_OrderMyExamine, _API_OrderMySended, _API_OrderMyCompleted, _API_OrderReceiveGoods } from '@/apis/order.js'
	import { _API_OrderMy1, _API_OrderMy2, _API_OrderMy3, _API_OrderMy4, _API_OrderMy5, _API_OrderAgain, _API_OrderDel, _API_OrderDetail1, _API_OrderCancel, _API_OrderReceiveGoods1 } from '@/apis/order.js'
	export default {
		mixins: [MIXIN],
		components: { swiperStatus, customReachBottom, pulldownRefresher },
		data() {
			return {
				title: '我的订单',
				page: [1, 1, 1, 1, 1], // 每种类型的页数 当页数为 0 时表示当前类型没有更多了 -1 表示请求失败
				lists: { 0: [], 1: [], 2: [], 3: [], 4: {} }, // 数据
				typeList: ['全部', '待付款', '待审核', '待收货', '已完成'],
				apis: [_API_OrderMy1, _API_OrderMy2, _API_OrderMy3, _API_OrderMy4, _API_OrderMy5]
			}
		},
		filters: {
			orderStatus(orderItem) { // 计算订单总金额过滤器
				if (orderItem.is_deleted) {
					return '已作废'
				} else if (!orderItem.pay_status) {
					return '待支付订单'
				} else if (orderItem.status == 3) {
					return '待收货'
				} else if (orderItem.status == 4) {
					return '已完成'
				} else {
					return '待审核订单'
				}
			},
			orderStatusClass(status) {
				if (status == '已完成') {
					return ''
				} else {
					return 'basecolor'
				}
			}
		},
		onLoad(opt) {
			if (this.$store.state.userinfo.level !== '代理公司') {
				uni.navigateBack()
				setTimeout(() => uni.$emit('noopening'))
				return
			}
			if (opt.type === '1') {
				this.MIXIN_NowIndex = this.MIXIN_ActiveIndex = this.MIXIN_FinishedIndex = 1
				this.MIXIN_MoveBarLeft = this.MIXIN_NowIndex * (this.MIXIN_ScreenWidth / this.typeList.length)
			} else if (opt.type === '2') {
				this.MIXIN_NowIndex = this.MIXIN_ActiveIndex = this.MIXIN_FinishedIndex = 2
				this.MIXIN_MoveBarLeft = this.MIXIN_NowIndex * (this.MIXIN_ScreenWidth / this.typeList.length)
			} else if (opt.type === '3') {
				this.MIXIN_NowIndex = this.MIXIN_ActiveIndex = this.MIXIN_FinishedIndex = 3
				this.MIXIN_MoveBarLeft = this.MIXIN_NowIndex * (this.MIXIN_ScreenWidth / this.typeList.length)
			} else if (opt.type === '4') {
				this.MIXIN_NowIndex = this.MIXIN_ActiveIndex = this.MIXIN_FinishedIndex = 4
				this.MIXIN_MoveBarLeft = this.MIXIN_NowIndex * (this.MIXIN_ScreenWidth / this.typeList.length)
			}
			this.MIXIN_request()
		},
		onPullDownRefresh() {
			this.page[this.MIXIN_NowIndex] = 1
			this.MIXIN_request()
		},
		created() {
			uni.$on('PAYSUCCESS', (order_num) => {
				this.lists[0].splice(this.lists[0].findIndex(e => e.order_num == order_num), 1)
				this.lists[1].splice(this.lists[1].findIndex(e => e.order_num == order_num), 1)
			})
		},
		methods: {
			confirmReceive(order_num, index) { // 点击确认收货
				this.$refs.ltm.modal('提示', ['确定收到商品？']).then(() => {
					uni.showLoading({ mask: true })
					_API_OrderReceiveGoods({ order_num }).then(res => {
						if (res.code === 200) {
							const list1 = deepClone(this.lists[1])
							list1.splice(index, 1) // 把当前订单从待收货列表删除
							this.$set(this.lists, 1, list1)
							uni.toast('收货成功')
						} else {
							uni.toast('收货失败，请稍后重试')
						}
					})
				}).catch(() => {
					uni.toast('取消确认')
				})
			},
			MIXIN_requestHandle(res) { // 请求 handler
				console.log(res)
				uni.stopPullDownRefresh()
			},
			toDetail(goodItem) { // 点击查看订单
				const { order_num, order_id, is_deleted, pay_status, money, created_at } = goodItem
				let str = ''
				if (!is_deleted && !pay_status) {
					str = '&nopay=1'
				}
				uni.navigateTo({ url: `../order-detail1/order-detail1?created_at=${created_at}&status=${this.$options.filters.orderStatus(goodItem)}&order_id=${order_id}&order_num=${order_num}${str}&money=${money}` })
			},
			changeOrder({ order_num }) { // 取消订单
				uni.showModal({
					title: '',
					content: '修改订单后会作废此订单，然后复制此订单的商品到购物车中重新下单，确定作废？',
					success: (res) => {
						if (res.confirm) {
							uni.loading()
							_API_OrderCancel({ order_num }).then(({ code, message }) => {
								if (code != 200) {
									uni.toast(message)
								} else {
									uni.loading()
									_API_GoodList().then(({ data: { list: list1 } }) => {
										uni.loading()
										list1.forEach(e => e.cart = Array(e.size.length).fill(0))
										_API_OrderDetail1({ order_num }).then(({ data: { list: list2 } }) => {
											uni.loading()
											this.$store.commit('cart/CLEAR')
											list1.forEach((item, index) => {
												const findRes = list2.find(e => e.attr_id == item.attr_id)
												if (findRes) {
													findRes.size.forEach((size, sizeIndex) => {
														const goodItemSizeIndex = list1[index].size.findIndex(e => e === size)
														list1[index].cart[goodItemSizeIndex] = findRes.num[sizeIndex]
													})
													item.choosed = true
													item.sizeChoosed = Array(item.size.length).fill(true)
													this.$store.commit('cart/ADD', item)
													uni.switchTab({ url: '../shop-car1/shop-car1' })
												}
											})
										})
									})
								}
							})
						}
					}
				})
			},
			buyAgain({ order_num }) { // 点击再次购买
				uni.showModal({
					title: '提示',
					content: '确定要再次购买？',
					success: (res) => {
						if (res.confirm) {
							uni.loading()
							_API_GoodList().then(({ data: { list: list1 } }) => {
								uni.loading()
								list1.forEach(e => e.cart = Array(e.size.length).fill(0))
								_API_OrderDetail1({ order_num }).then(({ data: { list: list2 } }) => {
									this.$store.commit('cart/CLEAR')
									list1.forEach((item, index) => {
										const findRes = list2.find(e => e.attr_id == item.attr_id)
										if (findRes) {
											findRes.size.forEach((size, sizeIndex) => {
												const goodItemSizeIndex = list1[index].size.findIndex(e => e === size)
												list1[index].cart[goodItemSizeIndex] = findRes.num[sizeIndex]
											})
											item.choosed = true
											item.sizeChoosed = Array(item.size.length).fill(true)
											this.$store.commit('cart/ADD', item)
											uni.switchTab({ url: '../shop-car1/shop-car1' })
										}
									})
								})
							})
						}
					}
				})
			},
			express(expCode, expNo) {
				KDNWidget.run({ serviceType: "A", expCode, expNo })
			},
			payNow({ order_num, money, order_id }) { // 点击立即付款
				// console.log(order_id)
				uni.navigateTo({ url: `../pay-order/pay-order?order_num=${order_num}&money=${money}&order_id=${order_id}` })
			},
			received({ order_num }) { // 点击确认收货
				uni.showModal({
					title: '提示',
					content: '确认收到货物？',
					success: (res) => {
						if (res.confirm) {
							uni.loading()
							_API_OrderReceiveGoods1({ order_num }).then(() => {
								uni.startPullDownRefresh()
							})
						}
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	.my-order {
		@include page();
		.content {
			@include flex(column);
			.swiper-area {
				scroll-view {
					.order-item {
						background: #FFFFFF;
						> view {
							padding: 0 30rpx;
							box-sizing: border-box;
						}
						.order-num {
							@include flex();
							height: 90rpx;
							font-size: 28rpx;
							font-weight: bold;
							justify-content: space-between;
							border-top: 20rpx solid $app-base-bg;
							border-bottom: 1rpx solid $app-base-bg;
						}
						.good-item {
							min-height: 240rpx;
							padding: 0 30rpx;
							background: #FFFFFF;
							box-sizing: border-box;
							border-bottom: 1rpx solid $app-base-bg;
							.imgs {
								min-height: 140rpx;
								width: 100%;
								margin-top: 28rpx;
								image {
									width: 140rpx;
									height: 140rpx;
									margin-right: 10rpx;
									border-radius: 6rpx;
								}
							}
							.info {
								margin-top: 4rpx;
								text-align: right;
								height: 64rpx;
								line-height: 64rpx;
								font-size: 24rpx;
								font-weight: bold;
							}
						}
						.bottom-bar {
							@include flex();
							height: 90rpx;
							font-size: 26rpx;
							justify-content: space-between;
							background: #FFFFFF;
							> text {
								font-size: 12rpx;
								font-weight: bold;
							}
							.btns {
								@include flex();
								.btn {
									@include flex();
									width: 140rpx;
									height: 54rpx;
									font-size: 28rpx;
									margin-left: 10rpx;
									color: #181818;
									border-radius: 54rpx;
									border: 1px solid rgba(24,24,24,1);
									&.bg {
										color: #FFFFFF;
										border-color: $app-base-color;
										background: $app-base-color;
									}
									&.border {
										color: $app-base-color;
										border-color: $app-base-color;
									}
								}
							}
						}
					}
				}
			}
		}
	}
</style>
