<template>
	<view class="container">
		<u-navbar leftIconColor="#fff" titleStyle="color:#fff;fontSize:36rpx;" :autoBack="true" bgColor="#2C6FF3"
			:placeholder="true" title="退款列表"></u-navbar>
		<view class="header-container">
			<view class="search">
				<u-search animation placeholder="请输入订单编号,设备号,用户手机号" :clearabled="false" v-model="keyword"
					:showAction="false" @search="search"></u-search>
				<view class="scan-icon" @click="scan">
					<u-icon name="scan" size="22" color="#909399"></u-icon>
				</view>
			</view>

			<view class="flex align-center justify-between" style="margin-top: 28rpx;">
				<view class="exceptiontype-container" @tap="actionSheetShow=true">
					{{orderStatus.name?orderStatus.name:'选择状态'}}
				</view>

				<view class="flex align-center  date-container">
					<view class="" style="margin-right: 10rpx;" @tap="dateSelect('start')">
						{{dateStart?dateStart:'开始日期'}}
					</view>
					<view class="" style="margin-right: 10rpx;">至</view>
					<view class="" @tap="dateSelect('end')">{{dateend?dateend:'结束日期'}}</view>
				</view>

				<view>
					<view class="change-month" @tap="changeMonth(-1)">
						上一月
					</view>
					<view class="change-month" style="margin-left: 20rpx;" @tap="changeMonth(1)">
						下一月
					</view>
				</view>
			</view>
		</view>
		<scroll-view @scrolltolower="loadMore" class="scrollview" :scroll-with-animation="true" scroll-y
			lower-threshold="100" :style="{height:fullHeight}">
			<view class="order-content" v-if="list&&list.length>0">
				<block v-for="(item,index) in list" :key="item.id">
					<view class="scrollview-container">
						<view class="flex align-center order-top">
							<view class="">订单编号：{{item.orderId}}</view>
							<view class="refund-status">
								<view class="com-status" style="color: #FF1E1E;" v-if="item.refundStatus==1">待处理</view>
								<view class="com-status" style="color: #aaff00;" v-if="item.refundStatus==2">退款中</view>
								<view class="com-status" style="color: #bdbdbd;" v-if="item.refundStatus==3">已拒绝</view>
								<view class="com-status" style="color: #22ca08;" v-if="item.refundStatus==4">已退款</view>
								<view class="com-status" style="color: #ff5500;" v-if="item.refundStatus==5">退款失败</view>
							</view>
						</view>
						<view class="ddxx-box">
							<!-- <view class="flex align-center justify-between">
								<view class="flex align-center">
									<view class="flex align-end" v-for="(item1,index1) in item.orderRefundGoods"
										:key="item1.id">
										<u--image radius="4" width="130rpx" height="130rpx" :src="item1.cover" mode="widthFix"
											:lazy-lord="true"></u--image>
										<view class="">×{{item1.totalNumber}}</view>
									</view>
								</view>
							</view> -->
							<view class="flex align-center con-item">
								<view class="oc-name">设备id：</view>{{item.deviceId}}
							</view>
							<view class="flex align-center con-item martop12">
								<view class="oc-name">申请时间：</view>{{item.createTime}}
							</view>
							<view class="flex align-center con-item martop12">
								<view class="oc-name">退款原因：</view>{{item.reason}}
							</view>
							<view class="flex align-center con-item martop12">
								<view class="oc-name">商品及说明：</view>{{item.description||'/'}}
							</view>
							<view class="flex align-center martop12">
								<view class="oc-name">联系电话：</view>{{item.memberTel}}
								<view class="phone"
									@click="$tab.navigateTo(`/pages/order/userInfo?id=${item.memberTel}`)">
									会员信息
								</view>
							</view>

							<!-- 	<view class="flex align-center con-item">
								线路：{{item.placeName}}
							</view> -->
							<view class="flex align-center justify-between con-item martop12">
								<view class="flex align-center ">
									<view class="oc-name">订单金额：</view>￥{{(Number(item.refundTotal)/100).toFixed(2)}}
								</view>

								<view class="refundamount-text marleft"
									v-if="item.refundStatus==2||item.refundStatus==4||item.refundStatus==5">
									退款金额：￥{{(Number(item.refundMoney)/100).toFixed(2)}}
								</view>
							</view>
							<!-- <view class="flex align-end martop">
								<view class="image-box" v-for="(item2,index2) in item.imgUrls" :key="index2">
									<u--image radius="4" width="160rpx" height="160rpx" :src="item2" mode="widthFix"
										:lazy-lord="true"></u--image>
								</view>
							</view> -->

							<view class="goods-container" v-for="(item1,index1) in item.orderRefundGoods"
								:key="item1.id">
								<view class="flex align-center justify-center image-container">
									<u--image radius="4" width="130rpx" height="130rpx" :src="item1.cover"
										mode="aspectFit" :lazy-lord="true"></u--image>
								</view>
								<view class="details-container">
									<view class="flex align-center goods-name-num justify-between">
										<view class="goods-name">{{item1.goodsName}}</view>
										<view class="goods-num">×{{item1.totalNumber}}</view>
									</view>
									<view class="gp-item">
										单价：￥{{(Number(item1.totalMoney)/Number(item1.totalNumber))/100}}
									</view>
								</view>
							</view>
						</view>
						<view class="flex  align-center justify-end" style="padding-top:12rpx;">
							<view class="">
								<xbutton size='medium' round='25rpx' padding='0rpx 20rpx' bgColor='#43cf7c'
									width='140rpx' @tap="showVideoView(item)">查看视频</xbutton>
							</view>
							<view style="margin-left: 24rpx;"
								v-if="item.refundStatus==1||item.refundStatus==3||item.refundStatus==5">
								<xbutton size='medium' round='25rpx' padding='0rpx 20rpx' width="150rpx"
									@click='refund(item)'>
									退款</xbutton>
							</view>
						</view>

					</view>
				</block>
				<u-loadmore :status="loadmoreStatus" />
			</view>

			<view v-else class='empty'>
				<u-empty mode="data" text="数据为空"></u-empty>
			</view>
		</scroll-view>

		<u-popup :show="refundShow" mode="center" :safeAreaInsetBottom="false" @close="refundShow=false" @open="open">
			<view class="refund-container">
				<u-radio-group placement="row" v-model="radioType" @change="radioChange">
					<u-radio :customStyle="{marginRight: '24rpx'}" activeColor="#2C6FF3" label="系统退款" name="2">
					</u-radio>
					<u-radio activeColor="#2C6FF3" label="拒绝退款" name="3"></u-radio>
				</u-radio-group>
				<view v-if="radioType=='2'">
					<view class="martop" v-for="(item,index) in orderGoods" :key="item.id">
						<view class="flex align-center" @tap="checked(item)">
							<view class="checked">
								<image v-if="item.checked"
									src="https://cdn.ossfile.mxrvending.com/assets/xy_merc_mini/images/commodity/selected.png"
									mode="widthFix">
								</image>
								<image v-else
									src="https://cdn.ossfile.mxrvending.com/assets/xy_merc_mini/images/commodity/select.png"
									mode="widthFix"></image>
							</view>
							<view class="">{{item.goodsName}}*{{item.totalNumber}}</view>
						</view>
						<view class="flex align-center" style="margin-top: 24rpx;">
							<u-number-box button-size="30" v-model="item.refundNum" class='martop'></u-number-box>
							<view class='marleft'>
								<u--input placeholder="退款金额" @blur="refundGoodsChange" type="digit"
									v-model="item.totalMoney" border="surround">
								</u--input>
							</view>
						</view>
					</view>
				</view>
				<view class='martop'>
					<u--textarea v-model="remark" placeholder="备注"></u--textarea>
				</view>
				<view class="martop" v-if="radioType=='2'">总退款金额：￥{{refundTotalMoney}}</view>
				<view class="flex align-center justify-end martop">
					<view class="">
						<xbutton width='200rpx' @click='refundShow=false'>取消</xbutton>
					</view>
					<view class='marleft'>
						<xbutton width='200rpx' @click="refundSure">确定</xbutton>
					</view>
				</view>
			</view>
		</u-popup>
		<u-datetime-picker :show="show" mode="date" v-model="nowDate" @confirm="confirm" :closeOnClickOverlay="true"
			@close="close" @cancel="close"></u-datetime-picker>
		<u-action-sheet :show="actionSheetShow" :actions="actions" title="请选择订单状态" @close="actionSheetShow = false"
			@select="actionsheetSelect($event)"></u-action-sheet>
		<xvideo :list="videoList" ref="video" showBtn></xvideo>
	</view>
</template>

<script>
	import {
		refundList,
		hendel
	} from "@/api/order/order.js"

	import xvideo from "./components/xvideo.vue"
	export default {
		components: {
			xvideo
		},
		data() {
			return {
				refundList: [],
				refundListlenght: '',
				isEmpty: false,

				refundShow: false,
				show: false,
				actionSheetShow: false,
				mode: 'single',

				index: 1,
				unchecked: false,


				actions: [{
					name: "全部",
					label: ""
				}, {
					name: "待处理",
					label: 1
				}, {
					name: '已退款',
					label: 2
				}, {
					name: '已拒绝',
					label: 3
				}],
				orderStatus: {
					name: '全部',
					label: ''
				}, //退款状态
				date: '', //创建时间

				list: [], //订单列表
				page: 1, //当前分页
				size: 10, //分页数据条数
				loadmoreStatus: 'loadmore', //加载更多

				type: '',
				dateStart: '',
				dateend: '',

				keyword: '',

				orderGoods: null,
				radioType: '2',

				remark: '',
				id: null, //退款订单id

				nowDate: Number(new Date()),

				// refundTotalMoney: 0,
				refundReason: [],
				videoList: null,
				fullHeight: 0,
				dateDx:0
			}
		},

		async onLoad() {
			let _this = this;
			const query = uni.createSelectorQuery().in(this);
			query.select(".scrollview").boundingClientRect((data) => {
				uni.getSystemInfo({
					success(res) {
						// 针对iPhone X等机型底部安全距离做适配
						const model = res.model;
						const modelInclude = [
							"iPhone X", 
							'iPhone XR', 
							"iPhone XS", 
							"iPhone XS MAX",
							"iPhone 12/13 mini",
							"iPhone 12/13 (Pro)",
							"iPhone 12/13 Pro Max",
							"iPhone 14 Pro Max"
						];
						let safeDistance = modelInclude.includes(model)
						//动态设置商品区域高度
						console.log(res.windowHeight, data.top)
						if (safeDistance) {
							_this.fullHeight = res.windowHeight - data.top - 34 + 'px';
						} else {
							_this.fullHeight = res.windowHeight - data.top + 'px';
						}
					},
				});
			}).exec();

			await this.getRefundReason()
			await this.getList()
		},

		computed: {
			refundTotalMoney() {
				let num = 0;
				if (this.orderGoods) {
					this.orderGoods.forEach(i => {
						if (i.checked) {
							num += Number(i.totalMoney)
						}
					})
				}
				return num
			}
		},

		// watch: {
		// 	orderGoods: {
		// 		handler(newVal, oldVal) {
		// 			let num = 0;
		// 			if (newVal) {
		// 				newVal.forEach(i => {
		// 					if (i.checked) {
		// 						num += Number(i.totalMoney)
		// 					}
		// 				})
		// 			}
		// 			this.refundTotalMoney = num
		// 		},
		// 		deep: true,
		// 		immediate: true
		// 	}
		// },

		methods: {
			getRefundReason() {
				return new Promise((resolve, reject) => {
					this.getDict('order_refund_refund_reason').then(res => {
						let newData = []
						res.forEach(item => {
							newData.push({
								name: item.msg,
								code: item.code
							})
						})
						this.refundReason = newData;
						resolve(res)
					}).catch(err => {
						reject(err)
					})
				})
			},

			changeMonth(add) {
				this.dateDx += add;
				var date = new Date();
				var year = date.getFullYear(); //当前年：四位数字
				var month = date.getMonth() + 1 + this.dateDx; //当前月：0-11
				var yeardx = Math.ceil(month / 12) - 1
				month %= 12;
				if (month <= 0) month += 12;
				year += yeardx;
				month = month < 10 ? ('0' + month) : month;

				this.dateStart = year + '-' + month + '-01';

				var day = 28;
				if (2 == month) {
					if (year % 4 == 0) {
						day = 29;
					}
				} else {
					if (month < 8) {
						if (1 == month % 2) {
							day = 31;
						} else {
							day = 30;
						}
					} else {
						if (1 == month % 2) {
							day = 30;
						} else {
							day = 31;
						}
					}
				}
				this.dateend = year + '-' + month + '-' + (day < 10 ? ('0' + day) : day);
				this.search();
			},

			dateSelect(type) {
				if (type == 'start') {
					this.type = type
				}
				if (type == 'end') {
					this.type = type
				}
				this.show = true
			},
			confirm(e) {
				this.show = false
				if (this.type == 'start') {
					this.dateStart = uni.$u.timeFormat(e.value, 'yyyy-mm-dd')
				}
				if (this.type == 'end') {
					this.dateend = uni.$u.timeFormat(e.value, 'yyyy-mm-dd')
				}
				this.reset()
				this.getList()
			},

			close() {
				this.show = false
			},

			search() {
				this.reset()
				this.getList()
			},

			//扫码
			scan() {
				uni.scanCode({
					success: (res) => {
						this.keyword = res.result;
						this.search()
					}
				});
			},

			open() {
				this.refundShow = true
			},

			//获取数据列表
			getList() {
				refundList({
					page: {
						current: this.page,
						size: this.size,
					},
					refundStatus: this.orderStatus.label, //退款状态
					beginCreateTime: this.dateStart, //时间
					endCreateTime: this.dateend
				}).then(res => {
					let data = res.data.records;
					let newData = [];
					console.log('res', data)
					data.forEach(i => {
						if (i.imgUrls) {
							i.imgUrls = i.imgUrls.split(',')
						}
						let refundTotal = 0;
						if (i.orderRefundGoods) { //处理无数据情况
							i.orderRefundGoods.forEach(j => {
								refundTotal += j.totalMoney
							})
						}
						if (this.refundReason.length > 0) {
							this.refundReason.forEach(j => {
								if (i.reason == j.code) {
									i.reason = j.name
								}
							})
						}

						i.refundTotal = refundTotal
						newData.push(i)
					})
					if (newData.length < 10) {
						this.loadmoreStatus = "nomore"
					} else {
						this.loadmoreStatus = "loadmore"
					}
					this.list = this.list.concat(newData)
				})
			},

			//重置数据
			reset() {
				this.loadmoreStatus == 'loadmore'
				this.page = 1;
				this.size = 10;
				this.list = [];
			},

			//上拉加载
			loadMore(e) {
				if (this.loadmoreStatus == 'nomore') return
				this.page++
				this.getList()
			},

			//退款按钮
			refund(e) {
				this.id = e.id;
				let orderRefundGoods = JSON.parse(JSON.stringify(e.orderRefundGoods));
				let arr = []
				if (orderRefundGoods && orderRefundGoods.length > 0) {
					arr = orderRefundGoods.map(i => {
						i.checked = false;
						i.refundNum = 1;
						i.totalMoney = Number(i.totalMoney) / 100
						return i
					});
				} else {
					arr = []
				}
				this.orderGoods = JSON.parse(JSON.stringify(arr))
				this.refundShow = true
			},

			//退款状态选择
			actionsheetSelect(e) {
				this.orderStatus = e
				this.search()
			},

			//退款选项
			radioChange(e) {},

			//选中商品
			checked(item) {
				this.orderGoods.forEach(i => {
					if (i.id == item.id) {
						i.checked = !i.checked
					}
				})
				this.orderGoods = JSON.parse(JSON.stringify(this.orderGoods))
			},

			refundGoodsChange(e) {
				if (!this.$xy.testPrice(e)) {
					this.$modal.msg('输入价格最低为分！')
				}
			},

			// 退款处理确认按钮
			refundSure() {
				let ordersGoods = [];
				if (this.radioType == 2) {
					for (var i = 0; i < this.orderGoods.length; i++) {
						let item = this.orderGoods[i]
						if (item.checked) {
							if (!this.$xy.testPrice(item.totalMoney)) {
								this.$modal.msg('输入价格最低为分！')
								return
							}
							ordersGoods.push({
								goodsId: item.goodsId,
								totalNumber: item.refundNum,
								refundMoney: item.totalMoney * 100
							})
						}
					}
					if (ordersGoods && ordersGoods.length == 0) {
						this.$modal.msg('请选择退款商品！')
						return
					}
				}

				let params = {
					id: this.id,
					refundStatus: Number(this.radioType),
					ordersGoods: ordersGoods,
					remark: this.remark
				}

				console.log('params', params)
				hendel(params).then(res => {
					if (res.code == 200) {
						this.$modal.msg('订单处理成功~')
						this.search()
					} else {
						this.$modal.msg('订单处理失败~')
					}
					this.orderGoods = null;
					this.refundShow = false;
				})
			},

			showVideoView(item) {
				this.$refs.video.show = true
				this.videoList = [
					item.urlVideo0,
					item.urlVideo1
				]
			},

			playVideo(o) {
				if (0 == o) {
					this.videoUrl = this.selOrder.url0;
				} else {
					this.videoUrl = this.selOrder.url1;
				}
			},

			closeVideoView() {
				this.videoUrl = '';
				this.hiddenOrderVideos = true;
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		.martop {
			margin-top: 30rpx;
		}

		.empty {
			margin-top: 40%;
		}

		.marleft {
			margin-left: 20rpx;
		}

		.scrollview {
			width: 724rpx;
			margin-left: 13rpx;
		}

		.header-container {
			padding: 20rpx 13rpx;
			background-color: #fff;

			.search {
				position: relative;

				.scan-icon {
					position: absolute;
					right: 24rpx;
					top: 50%;
					transform: translateY(-50%);
					z-index: 2;
				}
			}

			.params-list {
				.date-container {
					background-color: #fff;
					padding: 12rpx 24rpx;
					border-radius: 15rpx;
				}
			}

			.picker-container {
				width: 150rpx;
				padding: 12rpx 24rpx;
				border-radius: 15rpx;
				background-color: #fff;
			}

			.exceptiontype-container {
				background-color: #fff;
				border-radius: 10rpx;
				padding: 0 10rpx;
				width: 140rpx;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				line-height: 50rpx;
			}

			.change-month {
				display: inline-block;
				width: 100rpx;
				height: 45rpx;
				border: 1px solid #CCCCCC;
				border-radius: 6rpx;
				line-height: 43rpx;
				text-align: center;
				border-radius: 10rpx;
				text-align: center;
				font-size: 22rpx;
				color: #777777;
			}
		}

		.order-content {
			overflow: hidden;
		}

		.scrollview-container {
			background-color: #fff;
			margin-top: 20rpx;
			padding: 20rpx;
			border-radius: 15rpx;
			box-shadow: 0 5rpx 4rpx rgba(179, 179, 179, 0.3);

			.order-top {
				position: relative;
				font-size: 28rpx;
				color: #333;
				font-weight: bold;

				.refund-status {
					position: absolute;
					right: 0;
					top: 0;
				}
			}

			.ddxx-box {
				padding: 20rpx 13rpx;
				border-radius: 12rpx;
				font-size: 28rpx;
				color: #777;

				.martop12 {
					margin-top: 12rpx;
				}

				.goods-container {
					height: 154rpx;
					padding: 12rpx 12rpx 12rpx 164rpx;
					box-sizing: border-box;
					position: relative;
					border-radius: 8rpx;
					background-color: #f5f8fb;
					margin-top: 13rpx;

					.image-container {
						height: 130rpx;
						width: 130rpx;
						position: absolute;
						left: 12rpx;
						top: 50%;
						transform: translateY(-50%);
					}

					.details-container {
						position: relative;
						padding: 12rpx;

						.goods-name-num {
							.goods-name {
								font-size: 26rpx;
								color: #333;
								font-weight: bold;
							}

							.goods-num {
								font-size: 26rpx;
								color: red;
								margin-right: 40rpx;
								font-weight: bold;
							}
						}

						.goods-price {
							font-size: 28rpx;
						}

						.good-act {
							margin-top: 12rpx;
						}

						.gp-item {
							width: 50%;
							margin-top: 12rpx;
						}

						.goodf-act {
							font-size: 28rpx;
							color: #333;
							margin-top: 12rpx;
						}

						.goods-btn {
							margin-top: 12rpx;
						}

						.refund {
							position: absolute;
							right: 0;
							top: 0;
							background-color: red;
							color: #fff;
							border-radius: 4rpx;
							padding: 0 12rpx;
							line-height: 40rpx;
							font-size: 24rpx;
						}
					}
				}

				.oc-name {
					display: inline-block;
					width: 170rpx;
				}

				.phone {
					display: inline-block;
					font-size: 26rpx;
					font-family: PingFang SC;
					font-weight: 500;
					color: #2C6FF3;
					padding: 0 16rpx;
					line-height: 38rpx;
					background: #F4F8FF;
					border-radius: 8rpx;
					margin-left: 24rpx;
				}
			}

			.con-item {
				margin-top: 12rpx;
			}



			.untreated-btn {
				color: red;

			}

			.refunded-text {
				margin-left: 10rpx;
				color: #5e90d9;
			}

			.refundamount-text {
				color: red;
			}

			.image-box+.image-box {
				margin-left: 12rpx;
			}
		}

		.btn {
			margin-top: 12rpx;
		}

		.refund-container {
			background-color: #fff;
			width: 600rpx;
			padding: 20rpx 30rpx;

			.checked {
				width: 36rpx;
				height: 36rpx;
				margin-right: 12rpx;

				image {
					width: 36rpx;
					height: 36rpx;
				}
			}
		}
	}
</style>