<template>
	<view>
		<!--pages/order/order.wxml-->
		<view class="tab">
			<view v-for="(item, index) in TabList" :key="index" :class="'li ' + (item.active ? 'active' : '')"
				:data-index="index" @tap="switchTab">{{item.label}}</view>
		</view>
		<view style="height: 100rpx;"></view>
		<view class="search ddflex" v-if="index == 0">
			<image src="../../static/pages/images/ssico.png"></image>
			<input v-model="search" placeholder="输入关键词搜索" placeholder-class="placeholder" class="ipt fflex" @confirm="confirmSearch" />
		</view>
		<block v-if="pageList.length > 0">
			<view v-for="(item, index) in pageList" :key="index" class="lists">
				<view class="ddbh">
					<view class="ddid dflex ">
						{{item.payTime ? item.payTime : item.createDate}} 下单
						<!-- <block v-if="item.state == 1 || item.state == 8">
						<image src="/mine/static/mine/images/ioc_hwg.png" class="ioc" v-if="item.orderType==10">
						</image>编号：{{item.id}}<text class="copy" @tap="copy(item.id)">复制</text>
						</block>
						<block v-else>{{item.payTime}} 下单</block> -->
					</view>
					<view class="tihuoma" v-if="item.mode == 1 && item.state < 8 && item.state > 1">
						提货码：<text>{{item.code}}</text></view>
					<block>
						<image src="/static/pages/images/jishida.png" class="type" v-if="item.orderType == 5">
						</image>
						<image src="/mine/static/mine/images/tuangou.png" class="type" v-if="item.orderType == 2">
						</image>
						<image src="/mine/static/mine/images/pingtuan.png" class="type" v-if="item.orderType == 4">
						</image>
						<image src="/mine/static/mine/images/kanjia.png" class="type" v-if="item.orderType == 7">
						</image>
						<image src="/mine/static/mine/images/seckill.png" class="type" v-if="item.orderType == 3">
						</image>
						<image src="/mine/static/mine/images/newbornZone.png" class="type"
							v-if="item.orderType == 6"></image>
					</block>
				</view>
				<view @tap="showOrder" :data-code="item.code" :data-id="item.id" :data-state="item.state">
					<view v-for="(itempro, index2) in item.products" :key="index2" class="li">
						<image :src="itempro.pic + '?x-oss-process=style/w160'" mode="aspectFill" class="cimg"></image>
						<view class="zhinfo">
							<view class="zhtit ddflex">
								<view class="fflex tover">{{itempro.title}}</view>
								<view class="zhjia" v-if="item.orderType!=11">￥{{itempro.salePrice}}</view>
								<view class="zhjia" v-if="item.orderType==11">
									{{itempro.integral}}积分+￥{{itempro.salePrice}}
								</view>
							</view>
							<view class="gg ddflex">
								<view v-if="itempro.propertiesList" class="guigecontent fflex">规格：
									<text v-for="(itemGuige, index) in itempro.propertiesList" :key="index" class="guige"
										decode="true">{{itemGuige.value}}&nbsp;
									</text>
								</view>
								<view class="num">×{{itempro.quantity}}</view>
							</view>
							<view class="yuji" v-if="itempro.estimatedDeliveryTime">{{itempro.estimatedDeliveryTimeStr}}前发货</view>
						</view>
					</view>
					<view class="total dflex">
						<!-- <view>共{{item.count}}件商品</view> -->
						<view v-if="item.orderType!=11">
							总金额：<text>￥{{item.money}}</text>
						</view>
						<view v-if="item.orderType==11">
							合计：<text>{{item.discountMoney}}积分+￥{{item.money}}</text>
						</view>
						<view v-if="item.discountMoney>0&&item.orderType!=11">
							优惠金额：<text>￥{{item.discountMoney}}</text>
						</view>
					</view>
				</view>
				<view class="status">
					<block v-if="item.mode == 1 && item.state == 3">
						<view class="flex">待配货</view>
					</block>
					<block v-else>
						<view class="flex">{{item.stateName}}</view>
					</block>
					<!-- <block v-if="item.orderType==4">

					</block>
					<block v-else>
						<view class="sta-btn" @tap="refund" :data-id="item.id" :data-index="index"
							v-if="item.refund>0&&item.state>=2&&item.state<=6 && isrefund==1&&(item.orderType!=4)&&item.payTime!=null ||(item.state >=20&&item.state <30&&item.isOtc=='1'&& isrefund==1&&item.payTime!=null)">
							申请售后</view>
					</block> -->
					<view class="sta-btn" @tap="cancelOrder" :data-index="index" v-if="item.state == 1">取消订单</view>
				    <!-- <view class="sta-btn" @tap="cancelOrder" :data-index="index" v-if="item.state == 3">提醒发货</view> -->
					<view class="sta-btn" @tap="txOrder" :data-index="index" v-if="item.state == 3&&item.isReminder==1">提醒发货</view>
					<block v-if="isOpenInvoice == 1 && (item.state == 2 || item.state == 3 || item.state == 4 || item.state == 5 || item.state == 6 || item.state == 7)">
					<view class="sta-btn" @tap="applyInvoice(item)" v-if="item.invoiceState == 0">申请开票</view>
					<view class="sta-btn" @tap="toInvoice()" v-else>查看发票</view>
					</block>
					<!-- <navigator class="sta-btn" url="/mine/orderDet/orderDet?id={{item.id}}" hover-class="none">查看详情</navigator> -->
					<view class="sta-btn red" @tap="confirmOrder" :data-index="index" v-if="item.state == 5 || item.state == 6">确认收货</view>
					<view @tap="payOrder(item,index)" class="sta-btn red" v-if="item.state == 1">立即付款</view>
					<view @tap="scoreOrder" :data-index="index" class="sta-btn red"
						v-if="item.state == 7 && isOpenComments==1 && item.isEvaluate == 0">立即评价</view>
					<navigator v-if="item.state ==22||item.state ==20||item.state==27" hover-class="none"
						:url="'/prescription/Consultation/index?orderId='+item.id" class="sta-btn red">
						重新开方</navigator>
				</view>
			</view>
		</block>
		<view class="nodata" v-if="ishow">
			<image :src="picUrlss+'empty_dd.png'"></image>
			<text>还没有订单哦</text>
		</view>
	</view>
</template>

<script>
	// pages/order/order.js
	const app = getApp();
	const req = require("../../utils/request.js");
	const requsetmessage = require("../../utils/requestmessage.js");

	export default {
		data() {
			return {
				picUrlss: req.public.picUrls,
				TabList: [{
					label: '全部',
					active: true
				}, {
					label: '待付款',
					state: 1
				}, {
					label: '待发货',
					state: 3
				}, {
					label: '待收货',
					state: 5
				}, {
					label: '已完成',
					state: 7
				}],
				form: {
					page: 1,
					limit: 10
				},
				pageList: [],
				isLoad: true,
				index: "",
				ishow: false,
				isrefund: "",
				isOpenComments: "",
				isOpenInvoice: '',
				search: ''
			};
		},

		components: {},
		props: {},
		onLoad: function(options) {
			let that = this;
			let title = "";
			this.isrefundFun();
			this.isOpenCommentsFun();

			if (options.orderType) {
				this.form.orderType = options.orderType;
				if (options.orderType == 2) title = '团购订单';
				if (options.orderType == 4) title = '拼团订单';
				if (options.orderType == 7) title = '砍价订单';
				uni.setNavigationBarTitle({
					title: title
				});
			}

			const index = that.TabList.findIndex(it => it.state == options.state);
			if (options && options.state > 0) that.switchTab({
				currentTarget: {
					dataset: {
						index: index
					}
				}
			});
			else that.getList();
			this.setData({
				index: index
			});
		},

		onShow() {
			this.switchTab({
				currentTarget: {
					dataset: {
						index: this.index
					}
				}
			});
		},

		onReachBottom() {
			this.form.page++;
			this.getList();
		},

		methods: {
			switchTab(event) {
				let index = event.currentTarget.dataset.index;
				// console.log(index);
				let def = this.TabList.findIndex(it => it.active);
				let d = {};
				d['TabList[' + def + '].active'] = false;
				d['TabList[' + index + '].active'] = true;
				this.isLoad = true;
				this.form.page = 1;
				this.search = '';
				d['pageList'] = []; // this.data.form.states=this.data.TabList[index].state.toString();

				this.form.state = this.TabList[index].state;
				this.setData({
					index: index
				});
				this.setData(d);
				this.getList();
			},
			confirmSearch(){
				this.isLoad = true;
				this.form.page = 1;
				this.getList();
			},

			getList() {
				let isShowLoading = false;

				if (this.form.page == 1 && !isShowLoading) {
					req.loadIng('加载中');
					isShowLoading = true;
				}

				// console.log(!this.isLoad);
				if (!this.isLoad) return false;
				this.isLoad = false;
				let that = this;
				let form = this.form;
				if(this.search){
					form.search = this.search;
				}else{
					delete form.search
				}
				req.getRequest('/api/order/list', form, data => {
					// console.log(data);
					if (data && data.length == 10) this.isLoad = true;
					if (that.form.page > 1) data = that.pageList.concat(data);
					data.map(el => {
						el.refund = el.products.filter(it => it.quantity - (it.refundStock?it.refundStock:0) > 0).length
						return el
					})
					// console.log(data)
					that.setData({
						pageList: data
					});

					// console.log(data);

					if (data.length <= 0) {
						that.setData({
							ishow: true
						});
					} else {
						that.setData({
							ishow: false
						});
					}

					if (isShowLoading) {
						uni.hideLoading();
						isShowLoading = false;
					}
				});
			},

			showOrder(e) {
				let id = e.currentTarget.dataset.id;
				let code = e.currentTarget.dataset.code;
				let state = e.currentTarget.dataset.state; // if(state!=8){

				app.globalData.openPage('mine/orderDet/orderDet?id=' + id + '&isrefund=' + this.isrefund + '&code=' +
					code); // }else{
				//   req.msg("订单已取消")
				// }
			},
			
			txOrder(event){
				let index = event.currentTarget.dataset.index;
				let page = this.pageList[index];
				let that = this;
				req.postRequest('/api/order/reminderOrder', {
					orderId: page.id
				},() => {
					req.msg('发货提醒成功');
				});
			},

			cancelOrder(event) {
				//取消订单
				let index = event.currentTarget.dataset.index;
				let page = this.pageList[index];
				let that = this;
				req.msgConfirm('确定取消该订单？', () => {
					req.postRequest('/api/order/cancel', {
						id: page.id
					}, () => {
						let d = {};
						d['pageList[' + index + '].stateName'] = '订单取消';
						d['pageList[' + index + '].state'] = 8;
						that.setData(d);
						that.switchTab({
							currentTarget: {
								dataset: {
									index: this.index
								}
							}
						});
					});
				});
			},

			confirmOrder(event) {
				//确认收货
				let index = event.currentTarget.dataset.index;
				let page = this.pageList[index];
				let that = this;
				// console.log(that.index);
				req.msgConfirm('确认执行该操作？', () => {
					req.postRequest('/api/order/receiving', {
						id: page.id
					}, () => {
						let d = {};
						d['pageList[' + index + '].stateName'] = '订单完成';
						d['pageList[' + index + '].state'] = 7;
						that.setData(d);
						that.switchTab({
							currentTarget: {
								dataset: {
									index: this.index
								}
							}
						});
					});
				});
			},

			payOrder: async function(item) {
				let _ts = this;
				let mode = item.mode;
				if (item.mode == 2 && item.orderType == 5) {
					mode = 3;
				}
				if (item.isOtc == 1) {
					await requsetmessage.recipel(mode).then(res => {
						
					});
				} else if (mode == 1) {
					await requsetmessage.selfRaising().then(res => {
						// console.log("自提", res);
						
					});
				} else if (mode == 2) {
					await requsetmessage.distribution().then(res => {
						// console.log("配送", res);
						
					});
				} else {
					await requsetmessage.jisda().then(res => {
						// console.log("及时达", res);
						
					});
				}
				
				//支付订单
				req.payOrder(item.id, success => {
					// console.log(success);

					if (success) {
						if (item.isOtc == 1) {
							app.globalData.redirectTab('product/pay/pay?isSuccess=true&orderId=' + item.id +
								'&isRx=1');
						} else {
							app.globalData.redirectTab('product/pay/pay?isSuccess=true');
						}
						//支付成功
						// let d = {};
						// d['pageList[' + index + '].stateName'] = '待发货';
						// d['pageList[' + index + '].state'] = 3;
						// that.setData(d);
						// that.switchTab({
						// 	currentTarget: {
						// 		dataset: {
						// 			index: this.index
						// 		}
						// 	}
						// });
					}
				});
			},

			refund(event) {
				//申请退款
				let id = event.currentTarget.dataset.id;
				uni.navigateTo({
					url: '/mine/refund/refundType/refundType?id=' + id
				}); // let id = event.currentTarget.dataset.id;
				// req.postRequest('/api/order/refund',{id:id},res=>{
				//   req.msg('退款审核中')
				// })
			},

			isrefundFun() {
				//是否开启售后
				let isrefund = JSON.parse(req.getStorage('configRes'));

				if (isrefund.isRefund) {
					this.setData({
						isrefund: isrefund.isRefund
					});
				} // if(isrefund.isRefund==1){
				//   req.getRequest('/api/orderRefund/refundReason','',data=>{
				//     req.setStorage('isrefund',data)
				//   })
				// }

			},

			isOpenCommentsFun() {
				//是否开启评论
				let isOpenComments = JSON.parse(req.getStorage('configRes'));

				if (isOpenComments.is_open_comments) {
					this.setData({
						isOpenComments: isOpenComments.is_open_comments
					});
				}
				if (isOpenComments.is_open_invoice) {
					this.setData({
						isOpenInvoice: isOpenComments.is_open_invoice
					});
				}
			},

			scoreOrder(event) {
				//评价订单
				let index = event.currentTarget.dataset.index;
				let page = this.pageList[index];
				let that = this;
				app.globalData.openPage('mine/comments/comments?id=' + page.id);
			},
			copy(id){
				uni.setClipboardData({
					data: id,
					complete() {
						req.msg('复制成功')
					}
				})
			},
			// 申请开票
			applyInvoice(item){
				uni.navigateTo({
					url: '/invoice/apply/apply?orderId=' + item.id + '&money=' + item.money
				})
			},
			toInvoice(){
				uni.navigateTo({
					url: '/mine/invoice/invoice'
				})
			}

		}
	};
</script>
<style>
	@import "./order.css";
</style>
