<template>
	<view class="lists">
		<view class="status_bar" :style="navHeight"></view>
		<view class="header-bg">
			<image class="header-bg-img" src="@/static/image/nav_bg@3x.png" mode="scaleToFill"></image>
		</view>
		<view class="main">
			<view class="middle view">
				<view class="text-block">
					<text class="middle-date">查询条件</text>
					<view class="middle-date-des">
						<picker @change="bindPickerOptionChange" :value="conditionOptionIndex" :range="dateOptions" range-key="label">
							<text class="uni-input">{{dateOptions[conditionOptionIndex].label}}</text>
						</picker>
						<image class="icon-arrow" src="@/static/image/arrow_r@3x.png" mode="aspectFit"></image>
					</view>
				</view>
				<view class="text-block" v-if="condition.option !== 'BT'">
					<text class="middle-date">查询日期</text>
					<view class="middle-date-des">
						<view class="picker-year">
							<view class="uni-list-cell">
								<view class="uni-list-cell-db">
									<picker class="picker-block" @change="bindPickerDateChange" mode="date"
										:value="condition.posting_date" fields='day'>
										<text class="uni-input">{{condition.posting_date || '请选择日期'}}</text>
									</picker>
								</view>
							</view>
							<image class="icon-arrow" src="@/static/image/arrow_r@3x.png" mode="aspectFit"></image>
						</view>
					</view>
				</view>
				<view class="text-block" v-if="condition.option === 'BT'" key="start-date">
					<text class="middle-date">开始日期</text>
					<view class="middle-date-des">
						<view class="picker-year">
							<view class="uni-list-cell">
								<view class="uni-list-cell-db">
									<picker class="picker-block" @change="bindPickerStartDateChange" mode="date"
										:value="condition.posting_date_start" fields='day'>
										<text class="uni-input">{{condition.posting_date_start || '请选择开始日期'}}</text>
									</picker>
								</view>
							</view>
							<image class="icon-arrow" src="@/static/image/arrow_r@3x.png" mode="aspectFit"></image>
						</view>
					</view>
				</view>
				<view class="text-block text-block-last" v-if="condition.option === 'BT'" key="end-date">
					<text class="middle-date">结束日期</text>
					<view class="middle-date-des">
						<view class="picker-year">
							<view class="uni-list-cell">
								<view class="uni-list-cell-db">
									<picker class="picker-block" @change="bindPickerEndDateChange" mode="date"
										:value="condition.posting_date_end" fields='day'>
										<text class="uni-input">{{condition.posting_date_end || '请选择结束日期'}}</text>
									</picker>
								</view>
							</view>
							<image class="icon-arrow" src="@/static/image/arrow_r@3x.png" mode="aspectFit"></image>
						</view>
					</view>
				</view>
			</view>
			<view class="planout-block">
				<button class="btn" type="default" @tap="search">
					<text class="btn-text">查询</text>
				</button>
			</view>
			<list class="scroll-area view" scrollable loadmoreoffset='100' show-scrollbar='false' @loadmore="scrolltolower">
				<cell class="list-cell" v-for="(item,index) in lists" :key='index'>
					<view class="middle view planout-block-item">
						<view class="text-block">
							<text class="middle-date middle-date-select">客户编码</text>
							<text class="middle-date-des middle-date-des-select">{{item.billto_bp}}</text>
						</view>
						<view class="text-block">
							<text class="middle-date middle-date-select">客户名称</text>
							<text class="middle-date-des middle-date-des-select">{{item.billto_name}}</text>
						</view>
						<view class="text-block">
							<text class="middle-date middle-date-select">上账日期</text>
							<text class="middle-date-des middle-date-des-select">{{item.posting_date}}</text>
						</view>
						<view class="text-block">
							<text class="middle-date middle-date-select">摘要</text>
							<text class="middle-date-des middle-date-des-select">{{item.zy}}</text>
						</view>
						<view class="text-block text-block-last">
							<text class="middle-date middle-date-select">金额</text>
							<text class="middle-date-des middle-date-des-select">{{item.forward_amount}}</text>
						</view>
					</view>
					<view class="empty-block"></view>
				</cell>
				<cell>
					<view class="loading-more" v-if='lists.length>0'>
						<text class="loading-more-text" v-if="lists.length >= page.totalCount && page.totalCount > 0">-- 到底了 --</text>
						<text class="loading-more-text" v-else-if="isLoading">加载中...</text>
						<text class="loading-more-text" v-else>上拉加载更多</text>
					</view>
					<view class="loading-more" v-else>
						<text class="loading-more-text">暂无数据</text>
					</view>
				</cell>
			</list>

		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'

	import {
		apiGetMarketSupportFee
	} from '@/servers/billingInvoice.js'

	import timeFormat from '@/uview-ui/libs/function/timeFormat.js'

	export default {
		data() {
			return {
				loadingText: '加载中...',
				refreshing: false,
				isOpened: 'none',
				isLoading: false, // 添加加载状态，防止重复请求
				// 日期查询选项：是、介于、小于等于、大于等于
				dateOptions: [
					{ label: '是', value: 'EQ' },
					{ label: '介于', value: 'BT' },
					{ label: '小于等于', value: 'LE' },
					{ label: '大于等于', value: 'GE' }
				],
				conditionOptionIndex: 0, // 默认选择"是"
				condition: {
					option: 'EQ', // 默认是"是"
					posting_date: '', // 单个日期（用于EQ、LE、GE）
					posting_date_start: '', // 开始日期（用于BT）
					posting_date_end: '' // 结束日期（用于BT）
				},
				lists: [],
				page: {
					page: 1,
					pagesize: 20,
					totalCount: 0
				}
			}
		},
		computed: {
			navHeight() {
				return {
					'height': `${this.sysinfo.safeArea.top + 44}px`
				}
			},
			mainHeight() {
				return {
					'height': `${this.sysinfo.safeArea.height }px`,
				}
			},
			...mapState(['sysinfo', 'userInfo', 'userBpData'])
		},
		created() {
			// 不设置默认日期，让用户自己选择
			// this.queryData(1);
		},
		methods: {
			bindPickerOptionChange(e) {
				this.conditionOptionIndex = e.detail.value
				this.condition.option = this.dateOptions[e.detail.value].value
				// 切换选项时清空日期
				this.condition.posting_date = ''
				this.condition.posting_date_start = ''
				this.condition.posting_date_end = ''
			},
			bindPickerDateChange(e) {
				this.condition.posting_date = e.detail.value
			},
			bindPickerStartDateChange(e) {
				this.condition.posting_date_start = e.detail.value
			},
			bindPickerEndDateChange(e) {
				this.condition.posting_date_end = e.detail.value
			},
			search() {
				this.lists = [];
				this.page.page = 1;
				this.page.totalCount = 0; // 重置总数
				this.queryData(1);
			},
			scrolltolower() {
				// 防止重复请求
				if (this.isLoading) {
					return;
				}
				// 判断是否已加载完所有数据
				if (this.lists.length >= this.page.totalCount && this.page.totalCount > 0) {
					return;
				}
				this.page.page++;
				this.queryData(this.page.page);
			},
			async queryData(pageNo) {
				// 防止重复请求
				if (this.isLoading) {
					return;
				}
				this.isLoading = true;

				// 构建查询条件对象，与PC端格式保持一致
				const allConditions = {}

				// 处理日期条件，根据选项类型构建不同的查询条件（属性名小写，与PC端保持一致）
				if (this.condition.option === 'BT') {
					// 介于：需要开始日期和结束日期
					if (this.condition.posting_date_start || this.condition.posting_date_end) {
						allConditions.posting_date = [{
							sign: 'I',
							option: 'BT',
							low: this.condition.posting_date_start || '',
							high: this.condition.posting_date_end || ''
						}]
					}
				} else if (this.condition.option === 'EQ' || this.condition.option === 'LE' || this.condition.option === 'GE') {
					// 是、小于等于、大于等于：只需要单个日期
					if (this.condition.posting_date) {
						allConditions.posting_date = [{
							sign: 'I',
							option: this.condition.option,
							low: this.condition.posting_date,
							high: ''
						}]
					}
				}

				// 处理客户条件（如果存在）
				if (this.condition.customer && this.condition.customer.length > 0) {
					const customer = this.condition.customer.map(v => ({
						sign: v.sign || v.SIGN || 'I',
						option: v.option || v.OPTION || 'EQ',
						low: v.low || v.LOW || '',
						high: v.high || v.HIGH || ''
					}))
					// 字段名使用小写，与PC端保持一致
					allConditions.customer = customer
				}

				// 获取用户编号和角色信息，参考 ticket-order.nvue 的方式
				const userCode = this.userInfo?.code || ''
				// 从 userBpData 获取第一个角色的 ROLE_ID
				const roleId = this.userBpData?.ROLES && this.userBpData.ROLES.length > 0
					? this.userBpData.ROLES[0].ROLE_ID
					: ''
				let params = {
					user_bp: userCode,
					role: roleId,
					...allConditions,
					page: pageNo,
					pagesize: this.page.pagesize,
					totalCount: pageNo === 1 ? 0 : this.page.totalCount, // 第一页时重置totalCount
					is_result: 1,
					sort: []
				}

				try {
					if (pageNo === 1) {
						uni.showLoading({
							title: '加载中'
						});
					}
					const res = await apiGetMarketSupportFee(params);
					if (pageNo === 1) {
						uni.hideLoading();
					}

					if (res && res.data) {
						if (pageNo === 1) {
							this.lists = res.data || [];
						} else {
							this.lists = this.lists.concat(res.data || []);
						}
						// 更新总数，优先使用后端返回的总数
						const totalCount = res?.TOTALCOUNT || res?.totalCount || res?.Total || 0;
						if (totalCount > 0) {
							this.page.totalCount = totalCount;
						}
					}
				} catch (error) {
					console.error('查询失败', error);
					if (pageNo === 1) {
						uni.hideLoading();
					}
				} finally {
					this.isLoading = false;
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	/* #ifndef APP-PLUS */
	page {
		width: 100%;
		min-height: 100%;
		display: flex;
		background: #F2F3F5;
	}

	.status_bar {
		height: var(--status-bar-height);
	}

	/* #endif */

	.lists {
		position: relative;
		flex-direction: column;
		overflow-y: scroll;
		background: #f0f4f5;
		overflow-x: hidden;
	}

	.header-bg {
		height: 284rpx;
		margin-top: -88rpx;
	}

	.header-bg-img {
		width: 750rpx;
	}

	.view {
		flex-direction: column;
	}

	.main {
		position: relative;
		flex-direction: column;
		flex: 1;
		margin-top: -164rpx;
		padding: 0 16rpx;
		min-height: 0;
	}

	.middle {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 32rpx 64rpx 32rpx 48rpx;
		margin-bottom: 0;
	}

	.text-block {
		display: flex;
		overflow: hidden;
		height: 96rpx;
		margin-bottom: 14rpx;
		border-bottom: 1px solid #f4f5f6;
		justify-content: space-between;
		align-items: center;
	}

	.text-block-last {
		margin-bottom: 0;
		border-bottom: 0;
	}

	.middle-date {
		flex: 2;
		font-size: 28rpx;
		line-height: 96rpx;
		color: #333;
		margin-bottom: 8rpx;
	}

	.middle-date-des {
		flex: 3;
		font-size: 28rpx;
		line-height: 96rpx;
		height: 96rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		color: #888;
		display: flex;
		align-items: center;
		justify-content: flex-start;
		position: relative;
	}
	
	.middle-date-des picker {
		flex: 1;
		min-width: 0;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: flex-start;
	}

	.picker-year {
		position: relative;
		border-radius: 4px;
		align-items: center;
		flex: 1;
		flex-direction: row;
		justify-content: flex-start;
		width: 100%;
		padding-right: 24rpx;
	}

	.uni-list-cell {
		flex: 1;
		min-width: 0;
		display: flex;
		align-items: center;
		justify-content: flex-start;
	}

	.uni-list-cell-db {
		flex: 1;
		height: 48px;
		line-height: 48px;
		min-width: 0;
		display: flex;
		align-items: center;
		justify-content: flex-start;
		text-align: left;
	}

	.picker-block {
		flex: 1;
		min-width: 0;
		width: 100%;
		text-align: left;
		display: flex;
		align-items: center;
		justify-content: flex-start;
	}

	.uni-input {
		font-size: 28rpx;
		color: #333;
		text-align: left;
		width: 100%;
		overflow: visible;
		white-space: nowrap;
		display: block;
		text-align: left;
	}

	.icon-arrow {
		position: absolute;
		right: 0;
		top: 50%;
		margin-top: -10rpx;
		width: 12rpx;
		height: 20rpx;
		z-index: 10;
		flex-shrink: 0;
	}

	.planout-block {
		display: flex;
		justify-content: space-between;
		margin-top: 30rpx;
		margin-bottom: 30rpx;
		padding: 0 24rpx;
	}

	.planout-block-item {
		flex: 1;
		width: 750rpx;
		margin-bottom: 26rpx;
		background-color: #fff;
		border-radius: 16rpx;
		padding: 32rpx 64rpx 32rpx 48rpx;
	}

	.middle-date-select {
		color: #888;
	}

	.middle-date-des-select {
		color: #333;
	}

	.btn {
		flex: 1;
		height: 92rpx;
		background: $wly-primary-color;
		border-radius: 46rpx;
		justify-content: center;
		align-items: center;
	}

	.btn-text {
		color: #fff;
		font-size: 34rpx;
	}

	.scroll-area {
		flex: 1;
	}

	.list-cell {
		flex-direction: column;
	}
	
	.empty-block {
		height: 24rpx;
	}
	
	.loading-more {
		align-items: center;
		justify-content: center;
		padding-top: 20rpx;
		padding-bottom: 20rpx;
	}
	
	.loading-more-text {
		font-size: 28rpx;
		color: #999;
	}
</style>

