<script setup>
	// 商家订单
	import {
		ref,
		reactive,
		computed,
		getCurrentInstance,
	} from 'vue'
	import {
		onLoad,
		onReady,
		onPageScroll,
	} from '@dcloudio/uni-app';
	import {
		useStore
	} from 'vuex'
	// 顶部
	import apex from '@/components/header/apex.vue'
	//顶部条件栏
	import JyShopNavigation from '@/components/public/jy-shop-navigation'
	// 订单列表项
	import orderItem from '@/components/shop/order/item.vue';
	// 快递信息
	import expressVue from '@/components/shop/order/express.vue';
	// 工具库
	import util from '@/common/js/util';
	// 
	import api from '@/api/index.js'

	const {
		proxy
	} = getCurrentInstance()
	// 
	const store = useStore()
	// tabs
	const tabs = reactive([{
			id: '',
			name: '全部'
		},
		{
			id: 0,
			name: '待付款'
		},
		{
			id: 1,
			name: '待发货'
		},
		{
			id: 4,
			name: '待收货'
		},
		{
			id: 7,
			name: '售后/退款'
		}
	])
	// 当前tab下标
	const tabIndex = ref(0)
	// 列表
	const list = reactive({
		search: '',
		status: '',
		data: [],
		pageSize: 10,
		pageNum: 1,
		total: 0,
	})
	// 顶部导航背景颜色
	const apexBgColor = ref('#ffffff00')
	// 当前操作的订单
	const orderDetail = reactive({})
	// 确认退货的收货地址
	const address = reactive({
		realName: '',
		userPhone: '',
		userAddress: '',
	})
	// 用户信息
	const userinfo = computed(() => store.state.userinfo)

	onLoad((options) => {
		// 获取商家订单列表
		getList()
	})
	// 
	onReady(() => {
		// proxy.$refs.addressRef.open()
	})

	onPageScroll((ev) => {
		apexBgColor.value = ev.scrollTop > 44 ? '#fff' : '#ffffff00'
	})

	// 重载列表
	function refreshList() {
		list.pageNum = 1
		getList()
	}

	// 获取更多列表
	function getMoreList() {
		if (list.data.length >= list.total) return
		list.pageNum++
		getList()
	}

	// 获取商家订单列表
	function getList() {
		api.shop.getShopOrderList({
			query: {
				merId: userinfo.value.merId,
				searchStr: list.search,
				status: list.status,
				pageNum: list.pageNum,
				pageSize: list.pageSize,
			},
		}).then(res => {
			if (res.code == 200) {
				if (list.pageNum == 1) list.data.length = 0
				list.data.push(...res.rows.map(item => {
					// 状态
					item.status = Number(item.status)
					item.refundStatus = Number(item.refundStatus)
					// 编辑订单状态文字
					if (item.refundStatus != 0) {
						item.status_text = {
							'0': '待商家审核',
							'1': '商家拒绝',
							'2': '退款中',
							'3': '已退款',
							'4': '用户退货',
							'5': '商家待收货',
							'6': '已撤销',
						} [item.afterSaleStatus]
					} else {
						item.status_text = {
							'0': '待支付',
							'1': '待发货',
							'4': '待收货',
							'5': '已收货',
							'6': '已完成',
							'9': '已取消',
						} [item.status]
					}
					return item
				}))
				list.total = res.total
				return
			}
			util.alert({
				content: res.msg,
				showCancel: false
			})
		})
	}

	/**
	 * 点击订单列表项
	 * @param {Object} ev 订单列表项
	 */
	function handleItem(ev) {
		console.log('handleItem', ev)
		return
		uni.navigateTo({
			url: util.setUrl('/pages/shop/order/detail')
		})
	}

	/**
	 * 点击tab
	 * @param {Object} ev
	 */
	function itemClick(ev) {
		list.status = ev.id
		// 重载列表
		refreshList()
	}

	/* 填写退货物流信息
	 * @param {Object} item 订单详情
	 */
	function handleExpress(item) {
		Object.assign(orderDetail, {}, item)
		proxy.$refs.expressRef.open()
	}

	/**
	 * 填写退货物流信息
	 * @param {Object} param
	 */
	function handleExpressConfirm(param) {
		// 商家发货
		api.shop.setShopDeliver({
			data: {
				// 订单号
				orderNo: orderDetail.orderNo,
				// 商品总数
				totalNum: orderDetail.totalNum,
				// 快递公司名称
				expressName: param.expressName,
				// 运单号
				trackingNumber: param.trackingNumber,
				// 备注
				deliveryMark: '',
				// 商家id
				merId: orderDetail.merId,
				// 订单ID
				orderId: orderDetail.id,
				// 快递公司代码
				deliveryType: param.id,
				// 用户ID（购买订单人
				uid: orderDetail.uid,
			}
		}).then(res => {
			// 重载列表
			refreshList()
		})
	}

	/**
	 * 快捷改价
	 * @param {Object} item 订单详情
	 */
	function handlePriceChange(item) {
		item.price = item.totalPrice
		Object.assign(orderDetail, {}, item)
		proxy.$refs.changePriceRef.open()
	}

	// 快捷改价确定
	function handlePriceChangeConfirm() {
		// 商家发货
		api.shop.setShopOrderPrice({
			query: {
				// 订单ID
				id: orderDetail.id,
				// 用户ID（购买订单人
				price: orderDetail.price,
			}
		}).then(res => {
			if (res.code === 200) {
				proxy.$refs.changePriceRef.close()
				// 重载列表
				refreshList()
				return
			}
			util.alert({
				content: res.msg,
				showCancel: false
			})
		})
	}

	/**
	 * 商家拒绝售后
	 * @param {Object} item 订单项
	 */
	function handleUnrefund(item) {
		api.shop.setShopOrderUnrefund({
			data: {
				// 售后订单id
				id: item.refundOrder.id,
				// 订单编号
				refundOrderNo: item.orderNo,
				// 订单金额
				refundPrice: item.totalPrice,
			},
		}).then(res => {
			if (res.code === 200) {
				// 重载列表
				refreshList()
				return
			}
			util.alert({
				content: res.msg,
				showCancel: false
			})
		})
	}

	/**
	 * 商家同意售后
	 * @param {Object} item 订单项
	 */
	function handleRefund(item) {
		console.log('handleRefund', item)
		Object.assign(orderDetail, {}, item)
		// 售后类型：1-仅退款，2-退货退款
		if (item.refundOrder.afterSalesType == 1) handleOrderRefund()
		else if (item.refundOrder.afterSalesType == 2) proxy.$refs.addressRef.open()
	}

	// 填写收货地址确认
	function handleAddressConfirm() {
		console.log('address', address)
		// 验证必填项
		if (!address.realName) {
			util.alert('收货人姓名不能为空')
			return
		}
		if (!address.userPhone) {
			util.alert('收货人电话不能为空')
			return
		}
		if (!address.userAddress) {
			util.alert('收货地址不能为空')
			return
		}
		// 
		handleOrderRefund()
	}

	// 确认售后
	function handleOrderRefund() {
		// 
		api.shop.setShopOrderRefund({
			data: {
				// 售后订单id
				id: orderDetail.refundOrder.id,
				// 订单编号
				refundOrderNo: orderDetail.orderNo,
				// 订单金额
				refundPrice: orderDetail.totalPrice,
				...address,
			},
		}).then(res => {
			if (res.code === 200) {
				proxy.$refs.addressRef.close()
				address.realName = ''
				address.userAddress = ''
				address.userPhone = ''
				// 重载列表
				refreshList()
				return
			}
			util.alert({
				content: res.msg,
				showCancel: false
			})
		})

	}

	/**
	 * 预览图片
	 * @param {Array} urls
	 * @param {Number} current
	 */
	function viewImage(urls, current) {
		uni.previewImage({
			urls,
			current,
		})
	}

	/**
	 * 商家确认收货
	 * @param {Object} item 订单项
	 */
	function handleRefundOrder(item) {
		api.shop.setShopRefundOrder({
			// 售后订单id
			path: [item.refundOrder.id],
		}).then(res => {
			if (res.code === 200) {
				// 重载列表
				refreshList()
				return
			}
			util.alert({
				content: res.msg,
				showCancel: false
			})
		})
	}
</script>

<template>
	<apex :bgColor="apexBgColor" mode="flex">
		<template #content>
			<view class="search rows f1 mr30 plr20 bf8f8f8 br10">
				<uni-icons type="search" color="#999" />
				<input class="input ml20" type="text" placeholder="搜索内容" />
			</view>
		</template>
	</apex>

	<view class="app">
		<view class="shopHeaderBg bgColor"></view>

		<!-- tab选项卡 -->
		<view class="f1 pr">
			<JyShopNavigation v-model="tabIndex" :list="tabs" @tabItemClick="itemClick" />
		</view>

		<view class="product mlr20 pr">
			<!-- 订单列表 -->
			<view class="order">
				<template v-for="(item,index) in list.data" :key="index">
					<view class="mtb30">
						<orderItem :item="item" mode="shop" @item="handleItem">
							<template #menu="scope">
								<!-- 售后流程 -->
								<template v-if="scope.item.refundStatus == 1 ">
									<!-- 退款原因 -->
									<view class="menu rows ptb20">
										<view class="key fs0 c333">退款原因</view>
										<view class="value f1 ml20">
											<view class="c333 f28">{{item.refundOrder.refundReasonWap}}</view>
											<view class="c333 f28">{{item.refundOrder.refundReasonContent}}</view>
											<view class="imgList mt10 c666 f24">
												<template
													v-for="(secItem,secIndex) in item.refundOrder.refundReasonWapImg.split(',')"
													:key="secIndex">
													<image class="imgs wh80 br10" :src="secItem" mode="aspectFill"
														@click.stop="viewImage(item.refundOrder.refundReasonWapImg.split(','),secIndex)" />
												</template>
											</view>
										</view>
									</view>

									<!-- 待商家审核 -->
									<view class="menu ptb20 df jcr" v-if="scope.item.afterSaleStatus == 0">
										<view class="btn bar closeHollow plr30"
											@click.stop="handleUnrefund(scope.item)">拒绝退款</view>
										<view class="btn bar closeHollow plr30" @click.stop="handleRefund(scope.item)">
											同意退款</view>
										<!-- <view class="btn bar warmHollow plr30">联系用户</view> -->
									</view>

									<!-- 待商家确认收货 -->
									<view class="menu ptb20 df jcr" v-if="scope.item.afterSaleStatus == 5">
										<view class="btn bar warmHollow plr30"
											@click.stop="handleRefundOrder(scope.item)">
											确认收货</view>
									</view>
								</template>
								<template v-else>
									<!-- 收货地址 -->
									<view class="menu rows ptb20" v-if="[1,2,3,4,5,6].includes(scope.item.status)">
										<view class="key fs0 c333">收货地址</view>
										<view class="value f1 ml20">
											<view class="c333 f28">
												{{scope.item.address.province}}{{scope.item.address.city}}{{scope.item.address.country}}{{scope.item.address.detail}}
											</view>
											<view class="mt10 c666 f24">
												<text>{{scope.item.address.name}}</text>
												<text>{{scope.item.address.mobile}}</text>
											</view>
										</view>
									</view>
									<!-- 操作按钮 -->
									<view class="menu ptb20 df jcr" v-if="[0,1,6].includes(scope.item.status)">
										<template v-if="scope.item.status == 0">
											<view class="btn bar warmHollow plr30"
												@click="handlePriceChange(scope.item)">
												修改价格</view>
										</template>
										<template v-if="scope.item.status == 1">
											<view class="btn bar warmHollow plr30"
												@click.stop="handleExpress(scope.item)">
												发货</view>
										</template>
									</view>
								</template>
							</template>
						</orderItem>
					</view>
				</template>
			</view>
		</view>

		<!-- 填充 -->
		<view class="fill" style="height: 30rpx;"></view>

		<!-- 物流弹窗 -->
		<expressVue ref="expressRef" @confirm="handleExpressConfirm" />

		<!-- 快捷改价 -->
		<uni-popup ref="changePriceRef" type="center">
			<view class="changePrice popMid bfff">
				<view class="header rows ptb20 plr20">
					<view>输入修改金额</view>
					<uni-icons type="closeempty" @click="$refs.changePriceRef.close()" />
				</view>

				<view class="form oh mtb30 plr30 c333 f30">
					<view class="line df aic">
						<view class="mr20">输入金额</view>
						<input type="text" v-model="orderDetail.price" placeholder="输入修改价格"
							placeholder-class="placeholderStyle" />
					</view>
				</view>

				<view class="btn warm mtb30 mlr30" @click="handlePriceChangeConfirm">确定金额</view>
			</view>
		</uni-popup>

		<!-- 同意退款 -->
		<uni-popup ref="addressRef" type="center">
			<view class="addressAlt popMid bfff">
				<view class="header rows ptb20 plr20">
					<view>填写退货地址信息</view>
					<uni-icons type="closeempty" @click="$refs.addressRef.close()" />
				</view>

				<view class="form oh plr30 c333 f30">
					<view class="line mtb20">
						<input type="text" v-model="address.realName" placeholder="收货人姓名"
							placeholder-class="placeholderStyle" />
					</view>
					<view class="line mtb20">
						<input type="text" v-model="address.userPhone" placeholder="收货人电话"
							placeholder-class="placeholderStyle" />
					</view>
					<view class="line mtb20">
						<input type="text" v-model="address.userAddress" placeholder="收货人详细地址"
							placeholder-class="placeholderStyle" />
					</view>
				</view>

				<view class="btn warm mtb30 mlr30" @click="handleAddressConfirm">确认</view>
			</view>
		</uni-popup>
	</view>
</template>

<style scoped lang="scss">
	// 搜索
	.search {
		height: 30px;
	}

	// 背景颜色
	.bgColor {
		height: 300rpx;
	}

	.menu {
		border-top: 2rpx solid #eee;
	}
</style>