<template>
	<view class="page">
		<!-- 导航栏 -->
		<navbar title="提现记录" leftClick @leftClick="$utils.navigateBack" color="#fff" />

		<view class="tools">
			<uv-datetime-picker ref="datetimePicker" v-model="selectedTime" mode="year-month" confirmColor="#84A73F"
				@confirm="onTimeChange"></uv-datetime-picker>
			<button plain class="flex btn" @click="openTimePicker">
				<text>{{ displaySelectedTime }}</text>
				<image class="btn-icon" src="../static/runningWater/icon-arrow.png" mode="widthFix"></image>
			</button>
		</view>

		<view class="card list">
			<template v-if="list.length">
				<view class="flex list-item" v-for="(item, index) in list" :key="index">
					<image class="list-item-icon" src="../static/runningWater/icon-commission.png" mode="widthFix">
					</image>
					<view class="list-item-info">
						<view class="highlight">佣金提现</view>
						<view>{{ item.createTime }}</view>
					</view>
					<view class="list-item-value">{{ `-${item.amount}` }}</view>
					<view class="uni-color-btn" @click="withdraw(item)" v-if="item.status == 0">领取</view>
				</view>
			</template>
			<template v-else>
				<uv-empty mode="history" textSize="28rpx" iconSize="100rpx" />
			</template>
		</view>

	</view>
</template>

<script>
	import mixinsList from "@/mixins/list.js"
	export default {
		mixins: [mixinsList],
		data() {
			return {
				selectedTime: new Date(),

				x: ['+', '-', '-', '+'],
				mixinsListApi: "queryCashoutLog", //getWaterPageList
				beforeDate: new Date(), //开始日期
				afterDate: new Date(), //结束日期

				totalMoney: 0,
				totalWithdraw: 0,
			}
		},
		computed: {
			displaySelectedTime() {
				return this.$dayjs(this.selectedTime).format("YYYY年M月")
			}
		},
		onLoad() {
		},
		methods: {
			//打开日历
			openCalendars() {
				if (this?.$refs?.calendars) {
					this.$refs.calendars.open();
				}
			},

			// 选择了日期
			handleSelectCalendars(day) {

				console.log(day);

				// let beforeDate = this.getYearMonth(day?.range?.before)
				// let afterDate = this.getYearMonth(day?.range?.after)
				// this.beforeYear = beforeDate.year;
				// this.beforeMonth = beforeDate.month;
				// this.afterYear = afterDate.year;
				// this.afterMonth = afterDate.month;
			},

			getDataThen(list, total, result) {
				this.totalMoney = result.totalMoney
				this.totalWithdraw = result.totalWithdraw
				this.list = result.page.records
				this.total = result.page.total
			},

			openTimePicker() {
				this.$refs.datetimePicker.open();
			},
			onTimeChange(e) {
				// todo
				console.log('--onTimeChange', e)
			},
			requestMerchantTransferH5(item, fn) {
				// #ifdef H5
				// 使用Vue原型上的jWeixin
				const jWeixin = this.$jWeixin
				if (!jWeixin) {
					console.error('jWeixin未初始化')
					uni.showToast({
						title: '微信环境异常',
						icon: 'none'
					})
					return
				}

				jWeixin.ready(() => {
					jWeixin.checkJsApi({
						jsApiList: ['requestMerchantTransfer'],
						success: (res) => {
							if (res.checkResult['requestMerchantTransfer']) {
								// H5环境下使用WeixinJSBridge
								if (typeof WeixinJSBridge !== 'undefined') {
									WeixinJSBridge.invoke('requestMerchantTransfer', {
										appId: this.$config.appId,
										mchId: this.$config.mchId,
										package: item.packageInfo,
									}, (res) => {
										if (res.err_msg === 'requestMerchantTransfer:ok') {
											// 提现成功后的处理
											fn && fn()
										} else {
											console.log('提现失败:', res)
											uni.showToast({
												title: '提现失败，请稍后再试',
												icon: 'none'
											})
										}
									})
								} else {
									console.error('WeixinJSBridge未找到')
									uni.showToast({
										title: '请在微信中打开',
										icon: 'none'
									})
								}
							} else {
								uni.showToast({
									title: '你的微信版本过低，请更新至最新版本',
									icon: 'none'
								})
							}
						},
						fail: (error) => {
							console.error('checkJsApi失败:', error)
							uni.showToast({
								title: '微信接口检查失败',
								icon: 'none'
							})
						}
					})
				})

				jWeixin.error((res) => {
					console.error('微信配置失败:', res)
					uni.showToast({
						title: '微信配置失败',
						icon: 'none'
					})
				})
				// #endif
			},
			withdraw(item) {
				// #ifdef H5
				// 检查是否在微信环境
				if (!this.isInWechat()) {
					uni.showToast({
						title: '请在微信中打开',
						icon: 'none'
					})
					return
				}
				
				// H5环境下使用专门的H5提现方法
				this.requestMerchantTransferH5(item, () => {
					this.$store.commit('getUserInfo')
					this.$store.commit('getRiceInfo')
					this.$api('getMoney', {
						id: item.id,
					}).then(res => {
						this.getData()
					})
				})
				return
				// #endif

				// #ifdef MP-WEIXIN
				// 小程序环境下的处理
				// 拉起微信收款确认页面
				if (!wx.canIUse('requestMerchantTransfer')) {
					wx.showModal({
						content: '你的微信版本过低，请更新至最新版本。',
						showCancel: false,
					});
					return
				}

				// 在真机环境中，调用API
				wx.requestMerchantTransfer({
					appId: wx.getAccountInfoSync().miniProgram.appId,
					mchId: this.$config.mchId,
					package: item.packageInfo,
					success: (res) => {
						this.$store.commit('getUserInfo')
						this.$store.commit('getRiceInfo')

						this.$api('getMoney', {
							id: item.id,
						}).then(res => {
							this.getData()
						})
					},
					fail: (res) => {
						console.log('fail:', res);
						uni.showToast({
							title: '提现失败，请稍后再试',
							icon: 'none'
						})
					},
					complete: (res) => {
						console.log('requestMerchantTransfer完成:', res);
					}
				});
				// #endif
			},
			// #ifdef H5
			// 检查是否在微信环境
			isInWechat() {
				const ua = navigator.userAgent.toLowerCase()
				return ua.indexOf('micromessenger') !== -1
			},
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		background-color: $uni-bg-color;
		min-height: 100vh;

		/deep/ .nav-bar__view {
			background-image: linear-gradient(#84A73F, #D8FF8F);
		}
	}

	.uni-color-btn {
		padding: 10rpx 20rpx;
		margin: 0;
		font-size: 26rpx;
		margin-left: 20rpx;
	}

	.tools {
		background-color: $uni-fg-color;
		padding: 25rpx 42rpx;

		.btn {
			display: inline-block;
			border: none;
			color: #000000;
			font-size: 28rpx;
			line-height: 40rpx;

			&-icon {
				width: 28rpx;
				height: 28rpx;
				margin-left: 12rpx;
			}
		}
	}

	.list {
		margin: 9rpx 13rpx;
		padding: 31rpx 20rpx;

		&-item {
			padding-bottom: 19rpx;
			border-bottom: 1rpx solid #E0E0E0;
			margin-bottom: 20rpx;
			font-size: 28rpx;

			&-icon {
				width: 56rpx;
				height: auto;
				margin-right: 10rpx;
			}

			&-info {
				flex: 1;
				color: #949494;

				.highlight {
					color: #333333;
				}
			}

			&-value {
				color: #FF2A2A;
			}
		}
	}
</style>