<template>
	<!-- 商城订单 -->
	<!-- 商家查看自己店铺的订单 -->
	<!-- order 订单 -->
	<view class="storeOrder yocode">
		<view class="ordertab flex ali-c">
			<view
				class="tabitem flex1"
				@tap="taggletab"
				v-for="(item, index) in order_status_list"
				:key="index"
				data-current="1"
				:data-statusTab="item.status_id"
				:data-status="item.status"
				:data-is_dianping="item.is_dianping"
				:data-sale_status="item.sale_status"
			>
				<view class="title" :class="{ active: tabactive == item.status_id }">{{ item.status_name }}</view>
			</view>
		</view>

		<!-- v-if="tabactive==1" -->
		<!-- 正常订单 -->
		<view class="listorder">
			<view class="orderItem" v-for="(item, indexMax) in order" :key="indexMax">
				<view class="order_head flex ali-c jus-b">
					<view class="headl flex ali-c">
						<image class="storeicon" src="/static/news/storeicon.png" mode=""></image>
						<!-- <image class="storeicon" :src="staticUrl+item.photo" mode="" ></image> -->
						<view class="storename">{{ item.shop_name }}</view>
					</view>
					<view class="headr">
						<!-- 订单状态 -->
						<view>{{ item.order_status }}</view>
					</view>
				</view>
				<view class="cretime mt-10">下单时间：{{ item.create_time }}</view>
				<view>
					<!-- 列表 -->
					<view class="order_body    " v-for="(productList, index1) in item.products" :key="index1">
						<view class="flex mb-20" v-for="(product, index) in productList.orderGoods" :key="index">
							<!-- <image class="imgs" src="" mode=""></image> -->
							<image class="imgs" :src="staticUrl + product.photo" v-if="product.photo" mode=""></image>
							<image class="imgs" :src="staticUrl + item.photo" mode="" v-else></image>
							<view class="body_r flex1 ">
								<view class="title twoline">{{ product.goods_name }}</view>
								<view class="prices">
									<text class="text">价格{{ product.fprice }}元</text>
									<!-- <text class="text">充值价{{product.recprice}}元</text> -->
								</view>
								<view class="specs">
									<text class="text">规格:{{ product.sku_name }}</text>
									<!-- <text class="text">包装:2袋装</text> -->
									<view>数量: x {{ product.goodsnum }}</view>
								</view>
							</view>
						</view>
						<view v-if="productList.operation != ''" class="order_foot bodbod flex jus-e mb-20 mt-20">
							<block v-for="(action, index) in productList.operation" :key="index">
								<view
									class="btnss"
									:data-index="indexMax"
									:data-orderid="item.order_id"
									:data-vendor="index1"
									@tap.stop="operation"
									:data-action="action.way"
									:data-is_ld="item.buytype"
								>
									{{ action.name }}
								</view>
							</block>
						</view>
					</view>
				</view>
				<view class="order_foot  flex jus-e mb-20 ">
					<view class="heji">
						<text class="fuhao">{{ item.username_tel }}</text>
					</view>
				</view>
				<view class="pricebox flex ali-c jus-b" style="margin-top: 20upx;">
					<!-- 剩余时间 只有待支付的时候有 未付款的时候才有 -->
					<view class="titme oneline flex1" v-if="item.status == 4">退款原因:{{ item.refund_details }}</view>
					<view v-else></view>
					<view class="heji">
						合计
						<text class="fuhao">¥</text>
						<text class="shuzi">{{ item.total }}</text>
					</view>
				</view>
				<view class="order_foot flex jus-e">
					<!-- 已发货 -->
					<block v-for="(action, index) in item.order_operation" :key="index">
						<view class="btnss" :data-index="indexMax" :data-orderid="item.order_id" @tap.stop="operation" :data-action="action.way" :data-is_ld="item.buytype">
							{{ action.name }}
						</view>
					</block>
				</view>
			</view>
		</view>

		<!-- 售后/退款订单 -->
		<view class="listorder">
			<view class="orderItem" v-for="(item, indexMax) in refundOrder" :key="indexMax">
				<view class="order_head flex ali-c jus-b">
					<view class="headl flex ali-c">
						<image class="storeicon" src="/static/news/storeicon.png" mode=""></image>
						<!-- <image class="storeicon" :src="staticUrl+item.photo" mode="" ></image> -->
						<view class="storename">{{ item.shop_name }}</view>
					</view>
					<view class="headr">
						<!-- 订单状态 -->
						<view>{{ item.status_text }}</view>
					</view>
				</view>
				<view class="cretime mt-10">下单时间：{{ item.create_time }}</view>
				<view>
					<!-- 列表 -->
					<view class="order_body    " v-for="(product, index1) in item.ordergoods" :key="index1">
						<view class="flex mb-20">
							<!-- <image class="imgs" src="" mode=""></image> -->
							<image class="imgs" :src="staticUrl + product.photo" v-if="product.photo" mode=""></image>
							<image class="imgs" :src="staticUrl + item.photo" mode="" v-else></image>
							<view class="body_r flex1 ">
								<view class="title twoline">{{ product.goods_name }}</view>
								<view class="prices">
									<text class="text">价格{{ product.price }}元</text>
									<!-- <text class="text">充值价{{product.recprice}}元</text> -->
								</view>
								<view class="specs">
									<text class="text">规格:{{ product.sku_name }}</text>
									<!-- <text class="text">包装:2袋装</text> -->
									<view>数量: x {{ product.num }}</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="order_foot  flex jus-e mb-20 ">
					<view class="heji">
						<text class="fuhao">{{ item.username_tel }}</text>
					</view>
				</view>
				<view class="pricebox flex ali-c jus-e" style="margin-top: 20upx;">
					<!-- <view class="titme oneline flex1" v-if="item.status==4">退款原因:{{item.refund_details}}</view> -->
					<!-- <view v-else></view> -->
					<view class="heji">
						合计
						<text class="fuhao">¥</text>
						<text class="shuzi">{{ item.refund_price }}</text>
					</view>
				</view>
				<view class="order_foot flex jus-e">
					<!-- shop_button 按钮 -->
					<block v-for="(action, index) in item.shop_button" :key="index">
						<view
							class="btnss"
							:data-index="indexMax"
							:data-refundid="item.refund_id"
							@tap.stop="operation"
							:data-action="action.way"
							:data-name="action.name"
							:data-type="item.type"
						>
							{{ action.name }}
						</view>
					</block>
				</view>
			</view>
		</view>

		<pageScrollTo v-if="isshowtop"></pageScrollTo>
		<!-- 返回顶部 -->

		<!-- 拒绝退款弹窗填写拒绝原因 -->
		<uni-popup :show="showReasonRefusal" :mask-click="false" type="center">
			<view class="setSelect">
				<view class="titelsf">拒绝退款</view>
				<view class="inputfboxs flex ali-c"><textarea class="textarea" value="" placeholder="请填写拒绝退款原因" selection-start="-1" @input="HandleReasonRefusal" /></view>
				<view class="setbtns" @tap="saveReason">确定</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
// import { StoreorderStatus, orderGoodsList } from '@/utils/api/order.js';
import uniPopup from '@/components/uni-popup/uni-popup.vue';
import { orderStatus, orderList, oneKeyCancel, consentRefund, refuseRefund, getRefundOrderList, setReceivingGoods, shopExamine } from '@/utils/api/api.js';

import pageScrollTo from '@/components/pageScrollTo/pageScrollTo.vue';
export default {
	components: {
		pageScrollTo,
		uniPopup
	},
	data() {
		return {
			tabactive: 'all',
			statusTab: 'all',
			status: '',
			is_dianping: '',
			order_status_list: [],
			order: [], //正常订单
			refundOrder: [], //售后订单
			is_loading_done: false,
			pageNum: 0,
			currentTab: 0,
			sale_status: '',
			isshowtop: false,
			action: '',
			ReasonRefusal: '', //拒绝退款原因
			showReasonRefusal: false //拒绝退款弹窗
		};
	},
	computed: {
		staticUrl() {
			//静态资源地址
			return this.$store.state.staticUrl;
		}
	},
	//下拉刷新
	onPullDownRefresh() {
		this.is_loading_done = false;
		this.pageNum = 0;
		this.order = [];
		this.refundOrder=[];
		this.initializedata();
	},
	onUnload() {
		//页面卸载的时候
		uni.setStorageSync('obj', { order_id: '', index: -1 });
		uni.$off('isDelorder'); //取消监听
		uni.setStorageSync('scrollTop', 0);
	},
	onPageScroll(e) {
		//监听滚动
		uni.setStorageSync('scrollTop', e.scrollTop);
		//处理返回顶部
		if (e.scrollTop > 400) {
			this.isshowtop = true;
		} else {
			this.isshowtop = false;
		}
	},
	onReachBottom() {
		//滚动到最底部
		if (!this.is_loading_done) {
			this.initializedata();
		}
	},
	onLoad(options) {
		// console.log(options)
		var that = this;
		this.statusTab = options.current ? options.current : 'all'; // 订单状态
		this.status = options.status ? options.status : 'all';
		this.is_dianping = options.is_dianping ? options.is_dianping : 0;
		let params = {};
		orderStatus(params).then(res => {
			if (res.code == 0) {
				let order_status_list = res.data;
				this.order_status_list = order_status_list;
			}
		});
		this.initializedata();
	},
	onShow() {
		this.action = '';
		uni.$on('isDelorder', res => {
			let index = uni.getStorageSync('obj').index;
			let order = this.order;
			this.action = res.action;
			if (res.action == 'oneKeyShipments') {
				//确认发货
				if (this.status != 'all') {
					//只有不是在全部订单下才删除这一项
					order.splice(index, 1); //删除某项
					this.$set(this, 'order', order);
				} else {
					this.listDeal();
				}
			} else if (res.action == 'setReceivingGoods' || res.action == 'shopExamine' || res.action == 'setDeliverGoods') {
				//确认收货、商家审核、立即发货
				this.listDeal2();
			}
			uni.$off('isDelorder'); //取消监听
		});

		if (this.action == '') {
			this.listDeal();
		}
	},
	methods: {
		// 重新刷新正常订单列表
		listDeal() {
			let order_id = uni.getStorageSync('obj').order_id;
			let index = uni.getStorageSync('obj').index;
			uni.showLoading({ title: '请稍后...' });
			orderList({
				status: this.status,
				is_dianping: this.is_dianping,
				sale_status: this.sale_status,
				page: Math.ceil((index + 1) / 10)
			}).then(res => {
				uni.hideLoading();
				for (let item of res.data) {
					if (item.order_id == order_id) {
						this.$set(this.order, index, item);
						break;
					}
				}
			});
		},
		// 重新刷新售后订单列表
		listDeal2() {
			let refund_id = uni.getStorageSync('refund').refund_id;
			let index = uni.getStorageSync('refund').index;
			uni.showLoading({
				title: '请稍后...'
			});
			getRefundOrderList({
				page: Math.ceil((index + 1) / 20),
				pagesize: 20
			}).then(res => {
				console.log(res);
				uni.hideLoading(); //结束加载
				for (let item of res.data) {
					if (item.refund_id == refund_id) {
						this.$set(this.refundOrder, index, item);
						break;
					}
				}
			});
		},

		totkxq(data) {
			uni.showModal({
				title: '退款原因',
				content: data,
				showCancel: false,
				confirmText: '我知道了',
				confirmColor: '#ff6900',
				success: res => {
					if (res.confirm) {
						console.log('用户点击确定');
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		},
		//点击切换
		taggletab(event) {
			let that = this;
			let statusTab = event.currentTarget.dataset.statustab;
			let status = event.currentTarget.dataset.status;
			let is_dianping = event.currentTarget.dataset.is_dianping;
			let sale_status = event.currentTarget.dataset.sale_status;
			this.order = [];
			this.refundOrder=[];
			this.statusTab = statusTab;
			this.tabactive = statusTab;
			this.status = status;
			this.is_dianping = is_dianping;
			this.sale_status = sale_status;
			this.is_loading_done = false;
			this.currentTab = event.target.dataset.current;
			this.pageNum = 0;
			
			
			console.log(this.refundOrder,'aaaa');
			this.initializedata();
		},
		// 拒绝退款原因关闭弹窗
		saveReason(e) {
			this.showReasonRefusal = false; //关闭弹窗
			let refund_id = uni.getStorageSync('refund').refund_id;
			let params = {
				examine_reason: this.ReasonRefusal,
				refund_id: refund_id,
				shop_id: '',
				type: 2 //拒绝
			};
			if (!this.ReasonRefusal) {
				this.$api.msg('请填写拒绝原因');
				return;
			}
			shopExamine(params).then(res => {
				// console.log(res)
				if (res.code == 0) {
					uni.$emit('isDelorder', { action: 'shopExamine' });
					
					this.$api.msg('退款审核成功');
				} else {
					this.$api.msg(res.msg);
				}
			});
			this.showReasonRefusal = false; //关闭弹窗
		},
		// 获取拒绝退款原因
		HandleReasonRefusal(e) {
			this.ReasonRefusal = e.detail.value;
		},
		/**
		 * 初始化数据
		 */
		initializedata() {
			this.pageNum++;
			uni.showLoading({
				title: '加载中...'
			});
			var that = this;
			// 点击售后/退款请求新接口
			if (that.statusTab == 7) {
				let params = {
					page: that.pageNum,
					shop_id: ''
				};
				getRefundOrderList(params).then(res => {
					uni.stopPullDownRefresh();
					uni.hideLoading(); //结束加载
					if (res.data == null || res.data.length == 0) {
						this.is_loading_done = true;
						this.$api.msg('没有更多了~');
					} else {
						this.refundOrder = res.data;
					}
					uni.pageScrollTo({
						scrollTop: uni.getStorageSync('scrollTop'),
						duration: 0
					});
				});
				return;
			}

			// 正常订单列表
			let params = {
				status: that.status,
				is_dianping: that.is_dianping,
				sale_status: that.sale_status,
				page: this.pageNum
			};

			orderList(params).then(res => {
				uni.stopPullDownRefresh();
				uni.hideLoading(); //结束加载
				if (res.data == null || res.data.length == 0) {
					this.is_loading_done = true;
					this.$api.msg('没有更多了~');
				} else {
					this.order = [...this.order, ...res.data];
				}
				uni.pageScrollTo({
					scrollTop: uni.getStorageSync('scrollTop'),
					duration: 0
				});
			});
		},
		/**
		 * 订单操作
		 */
		operation(event) {
			let that = this;
			let action = event.currentTarget.dataset.action;
			let order_id = event.currentTarget.dataset.orderid;
			let vendor = event.currentTarget.dataset.vendor;
			let index = Number(event.currentTarget.dataset.index);
			let refund_id = event.currentTarget.dataset.refundid;
			let name = event.currentTarget.dataset.name;
			let type = event.currentTarget.dataset.type;
			uni.setStorageSync('obj', { order_id, index });
			uni.setStorageSync('refund', { refund_id, index });
			switch (action) {
				case 'oneKeyCancel': //一键核销 OK
					that.requestOrder(order_id, action);
					console.info('一键核销');
					break;
				case 'oneKeyShipments': //一键发货 OK
					console.info('一键发货');
					that.express(order_id, action, vendor);
					break;
				case 'checkLogistics': //查看物流
					that.logistics(order_id, action, vendor);
					console.info('查看物流');
					break;
				case 'orderDetails': //订单详情
					console.info('订单详情');
					that.orderDetails(order_id, order_id);
					break;
				case 'consentRefund': //同意退款
					this.clrefund(1, order_id, index);
					break;
				case 'refuseRefund': //拒绝退款
					this.clrefund(2, order_id, index);
					break;
				// 售后/退款新接口
				case 'getRefundDetail': //订单详情
					that.getRefundDetail(refund_id);
					break;
				case 'viewLogistics': //查看物流
					that.viewLogistics(refund_id);
					break;
				case 'setReceivingGoods': //确认收货
					that.requestRefundOrder(refund_id, action);
					break;
				case 'shopExamine': //同意&拒绝
					that.shopExamine(refund_id, name, type);
					break;
				case 'setDeliverGoods': //立即发货
					that.setDeliverGoods(refund_id, action);
					break;
				default:
					//其他的 退款啥的 处理ok了
					// console.info('1111', action);
					break;
			}
		},
		// 正常订单
		//处理退款
		clrefund(type, orderid, index) {
			uni.showModal({
				title: '提示',
				content: type == 1 ? '是否确定退款？' : '是否拒绝退款',
				success: res => {
					if (res.confirm) {
						new Promise((reslove, reject) => {
							if (type == 1) {
								//同意退款
								consentRefund({ order_id: orderid })
									.then(res => {
										reslove(res);
									})
									.catch(err => {
										reject(err);
									});
							} else {
								//拒绝退款
								refuseRefund({ order_id: orderid })
									.then(res => {
										reslove(res);
									})
									.catch(err => {
										reject(err);
									});
							}
						})
							.then(res => {
								if (res.code == 0) {
									if (this.status != 'all') {
										let order = this.order;
										order.splice(index, 1); //删除某项
										this.$set(this, 'order', order);
									} else {
										this.listDeal();
									}
								} else {
									this.$api.msg(returnRes.msg);
								}
							})
							.catch(err => {
								console.log(err, '失败了');
								//this.$api.msg(err.msg)
							});
					}
				}
			});
		},
		//查看物流
		logistics: function(order_id, action, vendor) {
			uni.navigateTo({
				url: '/pages/ViewLogistics/ViewLogistics?order_id=' + order_id + '&action=' + action + '&vendor=' + vendor
			});
		},
		//跳转订单详情 商家查看店铺的订单详情
		orderDetails: function(order_id) {
			uni.navigateTo({
				url: `/pages/order/shoporderdetail/shoporderdetail?order_id=${order_id}`
			});
		},
		// 跳转发快递订单 ok 发货
		express(order_id, action, vendor) {
			uni.navigateTo({
				url: '/pages/order/delivery/delivery?order_id=' + order_id + '&action=' + action + '&vendor=' + vendor
			});
		},
		//请求后台操作订单 一键核销
		requestOrder(order_id, action) {
			var that = this;
			let params = {
				order_id: order_id
				//action: action,
			};
			//一键核销方法
			oneKeyCancel(params).then(res => {
				if (res.code == 0) {
					uni.showModal({
						title: '提示',
						content: res.msg,
						showCancel: false,
						success(res) {
							uni.redirectTo({
								url: '/pages/order/shopOrder?status=' + that.status + '&current=' + that.statusTab
							});
						}
					});
				} else {
					this.$api.msg(res.msg);
				}
			});
		},

		// 售后/退款订单
		// 订单详情
		getRefundDetail: function(refund_id) {
			uni.navigateTo({
				url: `/pages/order/shoprefundorderdetail/shoprefundorderdetail?refund_id=${refund_id}`
			});
		},
		//查看物流
		viewLogistics: function(refund_id) {
			uni.navigateTo({
				url: `/pages/ViewLogistics/ViewLogistics?refund_id=${refund_id}`
			});
		},
		//立即发货
		setDeliverGoods:function(refund_id) {
			uni.navigateTo({
				url: '/pages/order/ExamineDelivery/ExamineDelivery?refund_id=' + refund_id
			});
		},
		// 请求后台操作售后订单确认收货
		requestRefundOrder: function(refund_id, action) {
			let params = {
				refund_id: refund_id,
				shop_id: ''
			};
			setReceivingGoods(params).then(res => {
				// console.log(res);
				if (res.code == 0) {
					uni.$emit('isDelorder', { action: 'setReceivingGoods' });
					uni.showToast({
						title: '收货成功',
						duration: 2000,
						icon: 'none'
					});
					// this.listDeal2(); //确认收货成功自动刷新售后列表
				} else {
					this.$api.msg(res.msg);
				}
			});
		},
		// 请求后台操作售后订单同意&拒绝
		shopExamine: function(refund_id, name, type) {
			if (name == '同意') {
				if (type == 3) {
					//直接退款
					var params = {
						refund_id: refund_id,
						shop_id: '',
						type: 1
					};
					uni.showModal({
						title: '提示',
						content: '请问是否确认同意退款？',
						success: res => {
							if (res.confirm) {
								shopExamine(params).then(res => {
									if (res.code == 0) {
										uni.$emit('isDelorder', { action: 'shopExamine' });
										uni.showToast({
											title: '操作成功',
											duration: 2000,
											icon: 'none'
										});
										this.listDeal2(); //同意退款后自动刷新售后列表
									}
								});
							}
						}
					});
				} else if (type == 1 || type == 2) {
					//退款退货 换货refund_id, name, type
					uni.navigateTo({
						url: `/pages/order/shopExamine/shopExamine?refund_id=${refund_id}&type=${type}`
					});
				}
			} else if (name == '拒绝') {
				this.showReasonRefusal = true;
			}
		}
	}
};
</script>

<style lang="scss">
@import './shopOrder.scss';
</style>
