<template>
	<page-meta :page-style="themeColor"></page-meta>
	<view class="order-container">
		<view class="cate-search">
			<view class="search-box">
				<input class="uni-input" maxlength="50" v-model="searchText" confirm-type="search"
					placeholder="请输入商品名称/订单编号" @confirm="search()" />
				<text class="iconfont icon-sousuo3" @click="search()"></text>
			</view>
			<image class="filter" :src="$util.img(`/upload/weapp/pageSalesman/filter.png`)" mode="" @click="filterBtn">
			</image>
		</view>
		<view class="order-nav" v-if="token">
			<view v-for="(statusItem, statusIndex) in statusList" :key="statusIndex" class="uni-tab-item"
				:id="statusItem.id" :data-current="statusIndex" @click="ontabtap">
				<text class="uni-tab-item-title" :class="
						statusItem.status == orderStatus
							? 'uni-tab-item-title-active color-base-border  color-base-text'
							: ''
					">
					{{ statusItem.name }}
				</text>
			</view>
		</view>

		<mescroll-uni ref="mescroll" @getData="getListData" top="220rpx" v-if="token">
			<block slot="list">
				<view class="order-list" v-if="orderList.length > 0">
					<view class="order-item" v-for="(orderItem, orderIndex) in orderList" :key="orderIndex">
						<view class="order-header">

							<text class="font-size-base">订单号：{{ orderItem.order_no }}</text>
              <text class="status-name color-base-text" v-if="orderStatusName">
                {{ orderStatusName }}
              </text>
							<text class="status-name color-base-text" v-else>
								{{ orderItem.order_status_name }}
							</text>
						</view>
						<view class="order-body" @click="orderDetail(orderItem)">
							<view class="goods-wrap" v-for="(goodsItem, goodsIndex) in orderItem.order_goods"
								:key="goodsIndex">
								<view class="goods-img">
									<image :src="$util.img(goodsItem.sku_image, { size: 'mid' })"
										@error="imageError(orderIndex, goodsIndex)" mode="aspectFill" :lazy-load="true">
									</image>
								</view>
								<view class="goods-info">
									<view class="pro-info">
										<view class="goods-name" v-if="goodsItem.goods_class == 2">
											{{ goodsItem.goods_name }}
										</view>
										<view class="goods-name" v-else>
											{{ goodsItem.sku_name }}
										</view>
										<view class="sku" v-if="goodsItem.sku_spec_format">
											<view class="goods-spec">
												<block v-for="(x, i) in goodsItem.sku_spec_format" :key="i">
													{{ x.spec_value_name }}
													{{
														i < goodsItem.sku_spec_format.length - 1
															? '; '
															: ''
													}}
												</block>
											</view>
										</view>
									</view>
									<view class="goods-sub-section">
										<text class="goods-price">
											<text class="unit price-style small">
												{{ $lang('common.currencySymbol') }}
											</text>
											<text class="price-style large">
												{{
													parseFloat(goodsItem.price)
														.toFixed(2)
														.split('.')[0]
												}}
											</text>
											<text class="unit price-style small">
												.{{
													parseFloat(goodsItem.price)
														.toFixed(2)
														.split('.')[1]
												}}
											</text>

										</text>
<!--										<text v-if="goodsItem.delivery_status">-->
<!--											{{goodsItem.delivery_status_name}}-->
<!--										</text>-->

                    <!--支付状态-->
                    <text v-if="orderItem.pay.pay_status == 2">
                      已支付
                    </text>
                    <text v-else-if="orderItem.pay.pay_status == 0 && orderItem.pay.pay_money > 0 && orderItem.pay.received_money == 0">
                      未支付
                    </text>
                    <text v-else-if="orderItem.pay.pay_status == 0 && orderItem.pay.pay_money > 0 && orderItem.pay.received_money > 0">
                      部分支付
                    </text>



										<text class="goods-num">

											<text class="iconfont icon-close"></text>
											{{ goodsItem.num }}

										</text>
									</view>
									<view class="goods-action">
										<!-- <view class="action-btn">加购物车</view> -->
									</view>
								</view>
							</view>
						</view>
						<view class="order-footer">
							<view class="order-base-info">
								<view class="total">
									<text class="font-size-sub">
										共{{ orderItem.goods_num }}件商品
									</text>
									<text class="align-right font-size-base">
                    <!--订单支付了->展示"总计",订单没支付->展示"实付款"-->
                    <span v-if="orderItem.pay_status == 0">实付款：</span>
                    <span v-else>总计：</span>
										<text class="font-size-base price-font" v-if="Number(orderItem.sales_money)">
											{{ $lang('common.currencySymbol')
											}}{{ orderItem.sales_money }}
										</text>
										<text class="font-size-base price-font"
											v-else-if="!Number(orderItem.sales_money)">
											{{ $lang('common.currencySymbol')
											}}{{ orderItem.order_money }}
										</text>

									</text>
								</view>
							</view>
              <view class="order-action" v-if="orderItem.action.length > 0">
                <view class="order-time" v-if="orderItem.order_status == 0 && auto_close > 0" id="action-date">
                  <image :src="$util.img('public/uniapp/order/time.png')"></image>
                  剩余时间：
                  <uni-count-down :day="orderItem.discountTimeMachine.d"
                                  :hour="orderItem.discountTimeMachine.h"
                                  :minute="orderItem.discountTimeMachine.i"
                                  :second="orderItem.discountTimeMachine.s" color="#FF4644"
                                  splitorColor="#FF4644" />
                </view>
              </view>
							<view class="order-action" v-if="orderItem.action.length > 0">
								<view class="order-box-btn" v-if="
										evaluateConfig.evaluate_status == 1 &&
											orderItem.is_evaluate == 1
									" @click="operation('memberOrderEvaluation', orderItem)">
									<text v-if="orderItem.evaluate_status == 0">评价</text>
									<text v-else-if="orderItem.evaluate_status == 1">追评</text>
								</view>
								<view class="order-box-btn" :class="{
										'color-base-border color-base-text':
											operationItem.action == 'orderPay'
									}" v-for="(operationItem, operationIndex) in orderItem.action" :key="operationIndex"
									@click="operation(operationItem.action, orderItem)">
									{{ operationItem.title }}
								</view>
								<view class="order-box-btn color-base-border color-base-text" v-if="!orderItem.is_invoice"
									@click="openInvoice(orderItem)">
									申请开票 
								</view>


							</view>
							<view class="order-action" v-else-if="
									orderItem.action.length == 0 &&
										orderItem.is_evaluate == 1 &&
										evaluateConfig.evaluate_status == 1
								">
								<view class="order-box-btn" v-if="orderItem.is_evaluate == 1"
									@click="operation('memberOrderEvaluation', orderItem)">
									<text v-if="orderItem.evaluate_status == 0">评价</text>
									<text v-else-if="orderItem.evaluate_status == 1">追评</text>
								</view>
								<view class="order-box-btn color-base-border color-base-text" v-if="!orderItem.is_invoice"
									@click="openInvoice(orderItem)">
									申请开票 
								</view>
								<!-- <view class="order-box-btn color-base-border color-base-text"
									@click="getInvoice(orderItem)"
									v-if="orderItem.is_invoice&&orderItem.invoice_status">
									查看发票
								</view> -->
								<view class="order-box-btn" v-if="orderItem.is_invoice&& !orderItem.invoice_status">
									发票审核中
								</view>
							</view>
							<view class="order-action" v-else>
								<view v-if="orderItem.order_status == -1"
									class="order-box-btn color-base-border color-base-text"
									@click="orderDel(orderItem)">
									删除订单
								</view>
								<view class="order-box-btn color-base-border color-base-text"
									@click="orderDetail(orderItem)">
									查看详情
								</view>

                <view class="order-box-btn color-base-border color-base-text"
									@click="getInvoice(orderItem)"
									v-if="orderItem.is_invoice && orderItem.invoice_status">
									查看发票
								</view>

								<view class="order-box-btn color-base-border color-base-text" v-if="!orderItem.is_invoice"
									@click="openInvoice(orderItem)">
									申请开票 
								</view>


							</view>
						</view>
					</view>
				</view>
				<view v-else>
					<ns-empty :isIndex="false" :text="$lang('emptyTips')"></ns-empty>
				</view>
			</block>
		</mescroll-uni>

		<!-- 	<view
			class="order-batch-action"
			:class="{ 'bottom-safe-area': isIphoneX }"
			v-if="mergePayOrder.length"
		>
			<view class="action-btn color-base-text color-base-border" @click="mergePay()">
				合并付款
			</view>
		</view> -->

		<!-- 选择支付方式弹窗 -->
		<ns-payment ref="choosePaymentPopup"></ns-payment>
		<ns-payment ref="choosePaymentMergePopup"></ns-payment>

		<ns-login ref="login"></ns-login>
		<loading-cover ref="loadingCover"></loading-cover>

		<u-popup :show="filterShow" @close="filterClose" @open="filterOpen" mode="top" :closeable="true"
			:closeOnClickOverlay="true">
			<view class="filterPopup">
				<view class="title color-tip">筛选</view>
				<!-- 价格区间 -->
				<view class="item-wrap">
					<view class="label"><text>价格区间(元)</text></view>
					<view class="price-wrap">
						<input class="uni-input" type="digit" v-model="minPrice" placeholder="最低价" />
						<view class="h-line"></view>
						<input class="uni-input" type="digit" v-model="maxPrice" placeholder="最高价" />
					</view>
				</view>

				<!-- 下单时间 -->
				<view class="item-wrap">
					<view class="label"><text>下单时间</text></view>
					<view class="price-wrap">
						<input inputmode="none" class="uni-input" type="text" v-model="startDate" placeholder="开始时间"
							@click="timeShow('start')" />
						<view class="h-line"></view>
						<input inputmode="none" class="uni-input" type="text" v-model="endDate" placeholder="结束时间"
							@click="timeShow('end')" />
					</view>
				</view>

				<view class="btnBox">
					<view :throttleTime="3" class="btn1" @click="reset">重置</view>
					<view :throttleTime="3" class="btn2" @click="screen">筛选</view>
				</view>
			</view>
		</u-popup>
		<u-datetime-picker :show="dateShow" v-model="valueDate" mode="date" @confirm="confirmDate"
			@cancel="cancelDate"></u-datetime-picker>

		<u-modal :show="showInvoice" :showCancelButton="true" cancelText="取消" confirmText="确认"
			@cancel="showInvoice=false" @confirm="confirmDoInvoice()">
			<view class="content">是否申请开票</view>
		</u-modal>
	</view>
</template>

<script>
	import orderMethod from './public/js/orderMethod.js';
	import nsPayment from '@/components/payment/payment.vue';
	export default {
		data() {
			return {
				scrollInto: '',
				orderStatus: 'all',
				orderStatusName: '',
				statusList: [],
				orderList: [],
				contentText: {},
				mergePayOrder: [],
				isIphoneX: false,
				evaluateConfig: {
					evaluate_audit: 1,
					evaluate_show: 0,
					evaluate_status: 1
				},
				orderData: {},
				payMoney: 0,
				payMoneyMerge: 0,
				token: null,
				order_id: 0,
				searchText: '',
				pageText: '',
				filterShow: false, //筛选弹框
				minPrice: '',
				maxPrice: '',
				startDate: '',
				endDate: '',
				invoice: null, //是否查询开票 / 开票中订单 0 否 1 是
				invoice_status: null, //发票状态（ 0 待开票 1 已开票）
				valueDate: Number(new Date()),
				dateShow: false,
				dateType: undefined,
				invoiceItem: {},
				showInvoice: false,
        auto_close: 0,//配置项-订单自动关闭时间设置
			};
		},
		components: {
			nsPayment
		},
		mixins: [orderMethod],
		onLoad(option) {
			if (option.status) this.orderStatus = option.status;
			if (option.order_id) this.order_id = option.order_id;
		},
		onShow() {
			this.isIphoneX = this.$util.uniappIsIPhoneX();
			this.getEvaluateConfig();
			this.getOrderStatus();

			if (uni.getStorageSync('token')) {
				this.token = uni.getStorageSync('token');
				if (this.$refs.mescroll) this.$refs.mescroll.refresh();
			} else {
				setTimeout(() => {
					this.$refs.login.open('/pages/order/list?status=' + this.orderStatus);
				});
			}
		},

		methods: {
			ontabtap(e) {
				let index = e.target.dataset.current || e.currentTarget.dataset.current;
				if (index == 4) {
					this.invoice = 2
					this.invoice_status = 0
				} else {
					this.invoice = null
					this.invoice_status = null
				}
				if (this.orderStatus == '') this.mergePayOrder = [];
				this.orderStatus = this.statusList[index].status;

        let _findRes = this.findStatusItem(this.statusList, this.orderStatus);
        //如果tab的索引=all(全部),那么就展示订单原有的状态名称,否则展示当前tab的名称
        if (this.orderStatus == 'all'){
          this.orderStatusName = ''//当前订单卡片的状态名称
        }else{
          this.orderStatusName = _findRes.name//当前订单卡片的状态名称
        }

        this.$refs.loadingCover.show();
				this.$refs.mescroll.refresh();
			},
      //查找状态名称
      findStatusItem(statusArray, statusValue) {
        return statusArray.find(item => item.status === statusValue);
      },
			getListData(mescroll) {
				this.$api.sendRequest({
					url: '/api/order/lists',
					data: {
						page: mescroll.num,
						page_size: mescroll.size,
						order_status: this.invoice_status == 0 ? 'all' : this.orderStatus,
						order_id: this.order_id,
						searchText: this.pageText,
						minPrice: this.minPrice,
						maxPrice: this.maxPrice,
						startDate: this.startDate,
						endDate: this.endDate,
						invoice: this.invoice, //是否查询开票 / 开票中订单 0 否 1 是
						invoice_status: this.invoice_status, //发票状态（ 0 待开票 1 已开票）
					},
					success: res => {

						let newArr = [];
						let msg = res.message;
						let auto_close = 0;
						if (res.code == 0 && res.data) {
							newArr = res.data.list;
							auto_close = res.data.auto_close;
						} else {
							this.$util.showToast({
								title: msg
							});
						}
						this.auto_close = auto_close;//配置项-订单自动关闭时间设置
						mescroll.endSuccess(newArr.length);
						//设置列表数据
						if (mescroll.num == 1) {
							this.orderList = []; //如果是第一页需手动制空列表
							this.order_id = 0;
						}
						this.orderList = this.orderList.concat(newArr); //追加新数据
						let date = Date.parse(new Date()) / 1000;
						this.orderList.forEach(v => {
							v.discountTimeMachine = this.$util.countDown(
								v.create_time + auto_close - date
							);
							v.order_goods.forEach(vo => {
								if (vo.sku_spec_format) {
									try {
										vo.sku_spec_format = JSON.parse(vo.sku_spec_format);
									} catch (e) {
										vo.sku_spec_format = vo.sku_spec_format;
									}
								} else {
									vo.sku_spec_format = [];
								}
							});
						});
						if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
					},
					fail: res => {
						mescroll.endErr();
						if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
					}
				});
			},
			/**
			 * 获取订单状态
			 */
			getOrderStatus() {
				this.statusList = [{
						status: 'all',
						name: this.$lang('all'),
						id: 'status_0'
					},
					{
						status: 'waitpay',
						name: this.$lang('waitPay'),
						id: 'status_1'
					},
					{
						status: 'waitsend',
						name: this.$lang('readyDelivery'),
						id: 'status_2'
					},
					{
						status: 'waitconfirm',
						name: this.$lang('waitDelivery'),
						id: 'status_3'
					},
					{
						status: 'invoice',
						name: '待开票',
						id: 'invoice'
					},
					{
						status: 'waitrate',
						name: this.$lang('waitEvaluate'),
						id: 'status_4'
					},

				];
			},
			operation(action, orderData) {
				console.log(orderData);
				let index = this.status;
				switch (action) {
					case 'orderPay': // 支付
						this.orderData = orderData;
						if (Number(orderData.sales_money)) {
							this.payMoney = parseFloat(orderData.sales_money)
						} else {
							this.payMoney = parseFloat(orderData.pay_money);
						}
						this.orderPay(orderData);
						break;
					case 'orderClose': //关闭
						this.orderClose(orderData.order_id, () => {
							this.$refs.mescroll.refresh();
						});
						break;
					case 'memberTakeDelivery': //收货
						this.orderDelivery(orderData.order_id, () => {
							this.$refs.mescroll.refresh();
						});
						break;
					case 'trace': //查看物流
						this.$util.redirectTo('/pages_tool/order/logistics', {
							order_id: orderData.order_id
						});
						break;
					case 'memberOrderEvaluation': //评价
						this.$util.redirectTo('/pages_tool/order/evaluate', {
							order_id: orderData.order_id
						});
						break;
					case 'memberVirtualTakeDelivery':
						this.orderVirtualDelivery(orderData.order_id, () => {
							this.$refs.mescroll.refresh();
						});
						break;
				}
				console.log(this.payMoney);
			},
			orderDel(data) {
				this.$api.sendRequest({
					url: '/api/order/orderDelete',
					data: {
						order_id: data.order_id
					},
					success: res => {
						this.$refs.mescroll.refresh();
						this.$util.showToast({
							title: res.message
						});
					}
				})
			},
			orderDetail(data) {
				switch (parseInt(data.order_type)) {
					case 2:
						// 自提订单
						this.$util.redirectTo('/page_goods/detail_pickup', {
							order_id: data.order_id
						});
						break;
					case 3:
						// 本地配送订单
						this.$util.redirectTo('/pages/order/detail_local_delivery', {
							order_id: data.order_id
						});
						break;
					case 4:
						// 虚拟订单
						this.$util.redirectTo('/pages_tool/order/detail_virtual', {
							order_id: data.order_id
						});
						break;
					default:
						// console.log(data);
						if (data.order_goods.length == 1) {
							this.$util.redirectTo('/page_goods/orderDetail/orderDetail', {
								order_id: data.order_id,
								order: data.order_goods[0].order_goods_id
							});
							return;
						}
						this.$util.redirectTo('/page_goods/orderDetail/orderDetail', {
							order_id: data.order_id
						});
						break;
				}
			},
			/**
			 * 选择订单
			 * @param {Object} orderId
			 */
			selectOrder(orderId, pay_money) {
				// console.log(111);
				if (this.$util.inArray(orderId, this.mergePayOrder) != -1) {
					this.mergePayOrder.splice(this.$util.inArray(orderId, this.mergePayOrder), 1);
					this.payMoneyMerge -= parseFloat(pay_money);
				} else {
					this.payMoneyMerge += parseFloat(pay_money);
					this.mergePayOrder.push(orderId);
				}
			},
			/**
			 * 合并支付
			 */
			mergePay() {
				if (this.mergePayOrder.length) {
					this.$api.sendRequest({
						url: '/api/order/pay',
						data: {
							order_ids: this.mergePayOrder.toString()
						},
						success: res => {
							if (res.code >= 0) {
								this.$refs.choosePaymentMergePopup.getPayInfo(res.data);
							} else {
								this.$util.showToast({
									title: res.message
								});
							}
						}
					});
				}
			},
			imageError(orderIndex, goodsIndex) {
				this.orderList[orderIndex].order_goods[
					goodsIndex
				].sku_image = this.$util.getDefaultImage().goods;
				this.$forceUpdate();
			},
			getEvaluateConfig() {
				this.$api.sendRequest({
					url: '/api/goodsevaluate/config',
					success: res => {
						if (res.code == 0) {
							var data = res.data;
							this.evaluateConfig = data;
							console.log('qq',this.evaluateConfig);
						}
					}
				});
			},
			search() {
				this.pageText = this.searchText;
				this.$refs.mescroll.refresh();
			},
			// 打开筛选弹框
			filterBtn() {
				this.filterShow = true;
			},
			filterOpen() {
				console.log('open');
			},
			filterClose() {
				this.filterShow = false;
				this.dateShow = false;
				console.log('close');
			},
			timeShow(type) {
				this.dateShow = true;
				this.dateType = type;
			},

			confirmDate(e) {
				const timeFormat = uni.$u.timeFormat;
				if (this.dateType == 'start') {
					this.startDate = timeFormat(e.value, 'yyyy-mm-dd');
				} else if (this.dateType == 'end') {
					this.endDate = timeFormat(e.value, 'yyyy-mm-dd');
				}
				this.dateShow = false;
			},
			cancelDate() {
				this.dateShow = false;
			},
			reset() {
				this.minPrice = '';
				this.maxPrice = '';
				this.startDate = '';
				this.endDate = '';
			},
			screen() {
				this.orderList = [];
				// this.getListData(this.$refs.mescroll.mescroll);
				this.$refs.mescroll.refresh();
				this.filterShow = false;
			},
			getInvoice(item) {
				console.log(item);
				uni.navigateTo({
					url: `/pages_tool/invoice/detail?order_id=${item.order_id}`
				})
			},
			openInvoice(item) {
				this.showInvoice = true
				this.invoiceItem = item
			},
			confirmDoInvoice() {
				let that = this
				that.$api.sendRequest({
					url: "/api/order/doInvoice",
					data: {
						order_id: that.invoiceItem.order_id
					},
					success: res => {
						that.$util.showToast({
							title: res.message
						});
						that.showInvoice = false;
						that.$refs.mescroll.refresh();
					}
				})
			},
		},
		computed: {
			mpOrderList() {
				if (!this.orderList[this.status]) return;
				return this.orderList[this.status].list || [];
			},
			storeToken() {
				return this.$store.state.token;
			}
		},
		watch: {
			storeToken: function(nVal, oVal) {
				if (nVal) {
					this.token = nVal;
					this.$refs.mescroll.refresh();
				}
			}
		}
	};
</script>

<style lang="scss">
	@import './public/css/list.scss';

	.cate-search {
		width: 100%;
		height: 100rpx;
		background: #ffffff;
		padding: 10rpx 30rpx;
		box-sizing: border-box;
		/* #ifdef H5 */
		padding-top: 30rpx;
		/* #endif */
		position: relative;
		z-index: 998;
		display: flex;

		.filter {
			// margin-left: 32rpx;
			width: 48rpx;
			height: 48rpx;
			padding: 10rpx 20rpx;
		}

		.search-box {
			width: 90%;
			height: 100%;
			background: $color-bg;
			display: flex;
			justify-content: center;
			align-items: center;
			border-radius: 40rpx;

			input {
				font-size: $font-size-base;
				height: 76rpx;
				padding: 0 25rpx 0 30rpx;
				line-height: 60rpx;
				width: calc(100% - 120rpx);
			}

			text {
				font-size: 32rpx;
				color: $color-tip;
				width: 120rpx;
				text-align: center;
			}
		}
	}

	.filterPopup {
		width: 100vw;
		position: relative;
		height: 50vh;

		.title {
			font-size: $font-size-tag;
			padding: $padding;
			background: #f6f4f5;
		}

		.item-wrap {
			border-bottom: 1px solid #f0f0f0;

			.label {
				font-size: $font-size-tag;
				padding: $padding;

				view {
					display: inline-block;
					font-size: 60rpx;
					height: 40rpx;
					vertical-align: middle;
					line-height: 40rpx;
				}
			}

			.list {
				margin: $margin-updown $margin-both;
				overflow: hidden;

				>view {
					display: inline-block;
					margin-right: 25rpx;
					margin-bottom: 25rpx;
				}

				.uni-tag {
					padding: 0 $padding;
					font-size: $font-size-goods-tag;
					background: #f5f5f5;
					height: 52rpx;
					line-height: 52rpx;
					border: 0;
				}
			}

			.price-wrap {
				display: flex;
				justify-content: center;
				align-items: center;
				padding: $padding;

				input {
					flex: 1;
					background: #f5f5f5;
					height: 52rpx;
					width: 182rpx;
					line-height: 50rpx;
					font-size: $font-size-goods-tag;
					border-radius: 50rpx;
					text-align: center;

					&:first-child {
						margin-right: 10rpx;
					}

					&:last-child {
						margin-left: 10rpx;
					}
				}
			}
		}

		.btnBox {
			position: absolute;
			bottom: 20rpx;
			width: 100%;
			display: flex;
			justify-content: space-around;

			view {
				width: 200rpx;
				text-align: center;
				height: 40rpx;
				line-height: 40rpx;
				padding: 10rpx;
				border-radius: 50rpx;

			}

			.btn1 {
				border: 1rpx solid $base-color;
			}

			.btn2 {
				background: $base-color;
				color: #ffffff;
			}
		}
	}
</style>
<style scoped>
	/deep/ .uni-page {
		overflow: hidden;
	}

	/deep/ .mescroll-upwarp {
		padding-bottom: 100rpx;
	}
</style>