<template>
	<view class="lists">
		<view class="status_bar" :style="navHeight"></view>
		<view class="main" :style="mainHeight">
			<view class="query-header-block">
				<view class="query-header-title" @click="toggleQuery">
					<text class="query-title-text">查询条件</text>
					<image class="query-toggle-icon" :src="isQueryCollapsed ? '/static/image/arrow_down@3x.png' : '/static/image/arrow_up@3x.png'" mode="aspectFit"></image>
				</view>
				<button class="btn btn-small" type="default" @tap="search">
					<text class="btn-text">查询</text>
				</button>
			</view>
			<view class="middle view planout-block-item" v-if="!isQueryCollapsed">
				<view class="text-block">
					<text class="middle-date">积分申请单号</text>
					<input class="middle-date-des" type="text" v-model="queryForm.rev_int_id" placeholder="请输入" />
				</view>
				<view class="text-block text-block-last">
					<text class="middle-date">申请日期</text>
					<view class="middle-date-des uni-list picker-year">
						<view class="uni-list-cell">
							<view class="uni-list-cell-db">
								<picker class="picker-block" @change="bindPickerStartDateChange" mode="date"
									:value="queryForm.startDate" fields='day'>
									<text class="uni-input-text">{{ queryForm.startDate || '开始日期' }}</text>
								</picker>
							</view>
						</view>
						<image class="icon-arrow" src="@/static/image/arrow_r@3x.png" mode="aspectFit"></image>
					</view>
				</view>
				<view class="text-block text-block-last">
					<text class="middle-date">至</text>
					<view class="middle-date-des uni-list picker-year">
						<view class="uni-list-cell">
							<view class="uni-list-cell-db">
								<picker class="picker-block" @change="bindPickerEndDateChange" mode="date"
									:value="queryForm.endDate" fields='day'>
									<text class="uni-input-text">{{ queryForm.endDate || '结束日期' }}</text>
								</picker>
							</view>
						</view>
						<image class="icon-arrow" src="@/static/image/arrow_r@3x.png" mode="aspectFit"></image>
					</view>
				</view>
			</view>
			<list ref="list" class="scroll-area view" loadmoreoffset='100' @loadmore="scrolltolower"
				:show-scrollbar='false'>
				<refresh @refresh="refresh" :display="refreshing ? 'show' : 'hide'">
				</refresh>
				<cell v-for="(item,index) in lists" :key="index">
					<view class="order view">
						<view class="top">
							<text class="title-no">积分申请单号：{{ item.rev_int_id || '--' }}</text>
							<view class="title-info" v-if="item.status_text">
								<button class="title-info__status" type="default">
									<text class="item-block-btn__text">{{ item.status_text }}</text>
								</button>
							</view>
						</view>
						<view class="middle view">
							<text class="middle-title">{{ item.custname || '--' }}</text>
							<view class="text-block-row">
								<view class="text-block text-block-third">
									<text class="middle-date-des">申请日期</text>
									<text class="middle-date">{{ formatDate(item.datum) || '--' }}</text>
								</view>
								<view class="text-block text-block-third">
									<text class="middle-date-des">申请时间</text>
									<text class="middle-date">{{ formatTime(item.uzeit) }}</text>
								</view>
								<view class="text-block text-block-third">
									<text class="middle-date-des">积分数量</text>
									<text class="middle-date">{{ formatQuantity(item.quantity) }}</text>
								</view>
							</view>
						</view>
					</view>
				</cell>
				<cell>
					<view class="loading-more" v-if='lists.length>2'>
						<text class="loading-more-text">{{loadingText}}</text>
					</view>
				</cell>
			</list>
			<no-data v-if="lists.length === 0 && !loading"></no-data>
		</view>
	</view>
</template>

<script>
	import { mapState } from 'vuex'
	import { getReverseIntegralList } from '@/servers/integral.js'
	import noData from '@/components/nodata.nvue'
	
	export default {
		components: {
			noData
		},
		data() {
			return {
				isQueryCollapsed: true,
				loading: false,
				refreshing: false,
				loadingText: '加载中...',
				queryForm: {
					rev_int_id: '',
					customer: '',
					custname: '',
					status_text: '',
					uname: '',
					startDate: '',
					endDate: ''
				},
				lists: [],
				page: {
					page: 1,
					pagesize: 10,
				},
				loadParams: {
					total: 0,
					totalPage: 1,
					isDone: false,
					isRefresh: false
				}
			}
		},
		computed: {
			...mapState(['sysinfo', 'userInfo']),
			navHeight() {
				return {
					'height': `${this.sysinfo.safeArea.top + 44}px`
				}
			},
			mainHeight() {
				return {
					'height': `${this.sysinfo.safeArea.height - 44 }px`,
				}
			}
		},
		created() {
			this.getSalesPlan(true)
		},
		methods: {
			toggleQuery() {
				this.isQueryCollapsed = !this.isQueryCollapsed
			},
			formatQuantity(quantity) {
				if (!quantity) return '0'
				if (typeof quantity === 'string' && quantity.endsWith('-')) {
					return '-' + quantity.replace('-', '')
				}
				return quantity
			},
			formatDate(date) {
				if (!date) return ''
				// SAP日期格式通常是 YYYYMMDD，转换为 YYYY-MM-DD
				if (date.length === 8) {
					return date.substring(0, 4) + '-' + date.substring(4, 6) + '-' + date.substring(6, 8)
				}
				return date
			},
			formatTime(time) {
				if (!time) return '--'
				const timeStr = String(time).trim()
				// 如果是6位数字 (HHMMSS)，格式化为 HH:MM:SS
				if (timeStr.length === 6 && /^\d+$/.test(timeStr)) {
					return timeStr.substring(0, 2) + ':' + timeStr.substring(2, 4) + ':' + timeStr.substring(4, 6)
				}
				// 如果是4位数字 (HHMM)，格式化为 HH:MM
				if (timeStr.length === 4 && /^\d+$/.test(timeStr)) {
					return timeStr.substring(0, 2) + ':' + timeStr.substring(2, 4)
				}
				// 如果已经包含冒号，直接返回
				if (timeStr.includes(':')) {
					return timeStr
				}
				return timeStr
			},
			bindPickerStartDateChange(e) {
				this.queryForm.startDate = e.detail.value
			},
			bindPickerEndDateChange(e) {
				this.queryForm.endDate = e.detail.value
			},
			search() {
				this.reset()
				this.getSalesPlan(true)
			},
			async getSalesPlan(isRefresh) {
				if (isRefresh) {
					this.page.page = 1
				}
				if (this.loadParams.isDone) {
					return
				}
				this.loading = true
				const params = this.buildPayload()
				
				uni.showLoading({
					title: '加载中'
				})
				
				try {
					const res = await getReverseIntegralList(params)
					uni.hideLoading()
					
					if (!res || (res.status !== 1 && res.msgtype !== 'S')) {
						this.lists = []
						this.loadParams.total = 0
						this.loadParams.totalPage = 1
						uni.showToast({
							title: (res && (res.msg || res.message)) || '查询失败',
							icon: 'none'
						})
						return
					}
					
					// 处理返回数据
					let data = []
					let total = 0
					
					if (res.data) {
						if (Array.isArray(res.data)) {
							data = res.data
							total = res.total || res.totalCount || 0
						} else if (res.data.data) {
							data = res.data.data
							total = res.data.total || res.data.totalCount || 0
						}
					}
					
					this.loadParams.total = total * 1
					this.loadParams.totalPage = Math.ceil(total * 1 / this.page.pagesize * 1)
					
					if (isRefresh) {
						this.lists = data
						this.loadParams.isDone = false
					} else {
						this.lists = this.lists.concat(data)
					}
					
					// 如果返回数据为空但总数不为0，重新查询第一页
					if (data.length === 0 && total > 0) {
						this.getSalesPlan(1)
					}
				} catch (error) {
					uni.hideLoading()
					this.lists = []
					this.loadParams.total = 0
					this.loadParams.totalPage = 1
					uni.showToast({
						title: '查询异常，请稍后重试',
						icon: 'none'
					})
				} finally {
					this.loading = false
					setTimeout(() => {
						this.refreshing = false
					}, 300)
				}
			},
			buildPayload() {
				const payload = {
					user_bp: this.userInfo.code,
					page: this.page.page,
					pagesize: this.page.pagesize,
					sort: []
				}
				
				// 构建查询条件
				const conditions = {}
				
				if (this.queryForm.rev_int_id) {
					conditions.rev_int_id = [{
						SIGN: 'I',
						OPTION: 'CP',
						LOW: this.queryForm.rev_int_id,
						HIGH: ''
					}]
				}
				
				if (this.queryForm.customer) {
					conditions.customer = [{
						SIGN: 'I',
						OPTION: 'EQ',
						LOW: this.queryForm.customer,
						HIGH: ''
					}]
				}
				
				if (this.queryForm.custname) {
					conditions.custname = [{
						SIGN: 'I',
						OPTION: 'CP',
						LOW: this.queryForm.custname,
						HIGH: ''
					}]
				}
				
				if (this.queryForm.status_text) {
					conditions.status_text = [{
						SIGN: 'I',
						OPTION: 'CP',
						LOW: this.queryForm.status_text,
						HIGH: ''
					}]
				}
				
				if (this.queryForm.uname) {
					conditions.uname = [{
						SIGN: 'I',
						OPTION: 'CP',
						LOW: this.queryForm.uname,
						HIGH: ''
					}]
				}
				
				if (this.queryForm.startDate || this.queryForm.endDate) {
					conditions.datum = [{
						SIGN: 'I',
						OPTION: 'BT',
						LOW: this.queryForm.startDate || '',
						HIGH: this.queryForm.endDate || ''
					}]
				}
				
				payload.is_result = 1
				Object.assign(payload, conditions)
				
				return payload
			},
			refresh(e) {
				this.refreshing = true
				this.reset()
				this.getSalesPlan(true)
				// #ifdef APP-NVUE
				try {
					this.$refs.list.resetLoadmore()
				} catch (e) {
					console.log('onrefresh', e)
				}
				// #endif
			},
			scrolltolower() {
				if (this.page.page < this.loadParams.totalPage) {
					this.page.page++
					this.getSalesPlan()
				} else {
					this.loadParams.isDone = true
					this.loadingText = '-- 到底了 --'
				}
			},
			reset() {
				this.loadParams = {
					total: 0,
					totalPage: 1,
					isDone: false,
					isRefresh: false
				}
				this.page.page = 1
				this.lists = []
				this.loadingText = '加载中'
				this.queryForm = {
					rev_int_id: '',
					customer: '',
					custname: '',
					status_text: '',
					uname: '',
					startDate: '',
					endDate: ''
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.view {
		flex-direction: column;
	}

	.lists {
		position: relative;
		flex-direction: column;
		background: #f0f4f5;
		flex: 1;
	}

	.main {
		position: relative;
		flex-direction: column;
		padding: 0 16rpx;
		padding-top: 40rpx;
	}

	.scroll-area {
		overflow-y: scroll;
		background: #f0f4f5;
	}

	.query-header-block {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 24rpx;
		margin-bottom: 30rpx;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
	}

	.query-header-title {
		flex-direction: row;
		align-items: center;
		flex: 1;
	}

	.query-title-text {
		font-size: 32rpx;
		color: #333;
		font-weight: 500;
		margin-right: 16rpx;
		display: flex;
		align-items: center;
		line-height: 32rpx;
	}

	.query-toggle-icon {
		width: 32rpx;
		height: 32rpx;
	}

	.btn-small {
		width: 200rpx;
		height: 64rpx;
		background: $wly-primary-color;
		border-radius: 32rpx;
		margin-left: 24rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

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

	.planout-block-item .text-block {
		overflow: hidden;
		height: 96rpx;
		margin-bottom: 14rpx;
		border-bottom: 1px solid #f4f5f6;
		flex-direction: row;
		align-items: center;
		justify-content: flex-start;
	}

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

	.planout-block-item .middle-date {
		flex: 1.5;
		font-size: 28rpx;
		line-height: 96rpx;
		color: #333;
		margin-bottom: 0;
		display: flex;
		align-items: center;
	}

	.planout-block-item .middle-date-des {
		flex: 4;
		font-size: 28rpx;
		line-height: 96rpx;
		height: 96rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		color: #888;
		display: flex;
		align-items: center;
	}

	.planout-block-item input.middle-date-des {
		padding: 0;
		text-align: left;
	}

	.picker-year {
		position: relative;
		border-radius: 4px;
		align-items: center;
		line-height: normal;
		display: flex;
		height: 96rpx;
	}

	.uni-list-cell {
		flex: 1;
		height: 96rpx;
		line-height: 96rpx;
		display: flex;
		align-items: center;
	}

	.uni-list-cell-db {
		flex: 1;
		display: flex;
		align-items: center;
	}

	.picker-block {
		flex: 1;
		display: flex;
		align-items: center;
	}

	.uni-input-text {
		height: 96rpx;
		line-height: 96rpx;
		font-size: 14px;
		color: #888;
		text-overflow: ellipsis;
		white-space: nowrap;
		overflow: hidden;
		display: flex;
		align-items: center;
	}

	.icon-arrow {
		position: absolute;
		right: 0;
		width: 12rpx;
		height: 20rpx;
		z-index: 10;
	}

	.btn-text {
		color: #fff;
		font-size: 28rpx;
		line-height: 28rpx;
		display: flex;
		align-items: center;
	}

	.order {
		flex: 1;
		background: #ffffff;
		border-radius: 16rpx;
		margin-top: 20rpx;
		margin-bottom: 32rpx;
		padding-top: 30rpx;
	}

	.top {
		height: 72rpx;
		align-items: center;
		justify-content: space-between;
		padding: 0 32rpx;
	}

	.title-no {
		font-size: 24rpx;
		color: #555555;
	}

	.title-info {
		align-items: center;
		margin-right: 26rpx;
	}

	.title-info__status {
		height: 48rpx;
		line-height: 48rpx;
		background: #f61d30;
		border-radius: 80rpx 200rpx 200rpx 80rpx;
		font-size: 12px;
		color: #fff;
		text-align: center;
		border-color: transparent;
	}

	uni-button::after {
		border: 0;
	}

	.item-block-btn__text {
		font-size: 12px;
		color: #fff;
		background: #f61d30;
	}

	.middle {
		position: relative;
		padding: 26rpx 32rpx;
	}

	.middle-title {
		font-weight: 500;
		font-size: 32rpx;
		color: $text-base-color;
		margin-bottom: 32rpx;
		font-family: PingFangSC, PingFangSC-Medium;
	}

	.text-block {
		flex: 1;
		flex-direction: column;
		margin-bottom: 32rpx;
		height: auto;
		border-bottom: 0;
	}

	.text-block-row {
		flex-direction: row;
		margin-bottom: 32rpx;
		justify-content: space-between;
	}

	.text-block-third {
		flex: 1;
		margin-bottom: 0;
		margin-right: 24rpx;
	}

	.text-block-third:last-child {
		margin-right: 0;
	}

	.middle-date {
		font-size: 28rpx;
		color: $text-base-color;
		margin-top: 8rpx;
		line-height: normal;
		flex: auto;
	}

	.middle-date-des {
		font-size: 24rpx;
		color: #999;
		line-height: normal;
		flex: auto;
	}

	.loading-more {
		flex: 1;
		align-items: center;
		justify-content: center;
		padding-top: 14px;
		padding-bottom: 14px;
		text-align: center;
	}

	.loading-more-text {
		font-size: 12px;
		color: #999;
	}
</style>
