<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>
				<view class="query-header-actions">
					<button class="btn btn-small" type="default" @tap="search">
						<text class="btn-text">查询</text>
					</button>
				</view>
			</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.bottleCode" placeholder="请输入" />
				</view>
				<view class="text-block">
					<text class="middle-date">产品名称</text>
					<input class="middle-date-des" type="text" v-model="queryForm.productName" placeholder="请输入" />
				</view>
				<view class="text-block">
					<text class="middle-date">积分明细编码</text>
					<input class="middle-date-des" type="text" v-model="queryForm.detailId" 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>
			<view class="statistics-section" v-if="pointStatistics.total !== undefined">
				<text class="statistics-text">当前总积分：{{ formatPoints(pointStatistics.total) }}，可用积分：{{ formatPoints(pointStatistics.balance) }}</text>
			</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.detailId || '--' }}</text>
							<view class="title-info" v-if="item.pointStatus">
								<button class="title-info__status" type="default">
									<text class="item-block-btn__text">{{ getPointStatusText(item.pointStatus) }}</text>
								</button>
							</view>
						</view>
						<view class="middle view">
							<text class="middle-title">{{ item.productName || '--' }}</text>
							<view class="text-block-row">
								<view class="text-block-item">
									<text class="middle-date-des">获得时间</text>
									<text class="middle-date">{{ item.earnedTime || '--' }}</text>
								</view>
								<view class="text-block-item">
									<text class="middle-date-des">失效时间</text>
									<text class="middle-date">{{ item.expiryTime || '--' }}</text>
								</view>
							</view>
							<view class="text-block-row">
								<view class="text-block-item">
									<text class="middle-date-des">瓶码</text>
									<text class="middle-date">{{ item.bottleCode || '--' }}</text>
								</view>
								<view class="text-block-item">
									<text class="middle-date-des">积分数量</text>
									<text class="middle-date">{{ formatPoints(item.earnedPoints) }}</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>
		
		<!-- 积分申请对话框 -->
		<uni-popup ref="applyPopup" type="center" background-color="#fff" :mask-click='false'>
			<view class="popup-content">
				<view class="popup-header">
					<text class="popup-title">积分申请</text>
					<text class="popup-close" @click="closeApplyDialog">×</text>
				</view>
				<view class="popup-body">
					<view class="form-item">
						<text class="form-description">当前总积分：{{ formatPoints(applyForm.total) }}，可用积分：{{ formatPoints(applyForm.balance) }}</text>
					</view>
					<view class="form-item">
						<text class="form-label">请输入申请积分</text>
						<input class="form-input" type="number" v-model="applyForm.apply" placeholder="请输入申请积分" />
					</view>
				</view>
				<view class="popup-footer">
					<button class="btn btn-cancel" type="default" @tap="closeApplyDialog">
						<text class="btn-text">取消</text>
					</button>
					<button class="btn btn-confirm" type="default" @tap="handleApplySubmit" :disabled="applyLoading">
						<text class="btn-text">{{ applyLoading ? '提交中...' : '确定' }}</text>
					</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import { mapState, mapGetters } from 'vuex'
	import { fetchDistributerPointEarnPage, fetchDistributerPointStatistics, apiApplyIntegral } from '@/servers/integral.js'
	import noData from '@/components/nodata.nvue'
	
	const POINT_STATUS_TEXT = {
		NORMAL: '正常未使用',
		USED: '已使用',
		PARTIALLY_USED: '部分使用',
		EXPIRED: '已过期'
	}
	
	export default {
		components: {
			noData
		},
		data() {
			return {
				isQueryCollapsed: true,
				loading: false,
				refreshing: false,
				loadingText: '加载中...',
				queryForm: {
					bottleCode: '',
					productName: '',
					detailId: '',
					startDate: '',
					endDate: ''
				},
				lists: [],
				page: {
					PAGE: "1",
					PAGESIZE: "10",
				},
				loadParams: {
					total: 0,
					totalPage: 1,
					isDone: false,
					isRefresh: false
				},
				pointStatistics: {
					total: undefined,
					balance: undefined
				},
				applyForm: {
					total: '',
					balance: '',
					apply: ''
				},
				applyLoading: 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.fetchPointStatistics()
			this.getSalesPlan(true)
		},
		onNavigationBarButtonTap(e) {
			// 标题栏按钮点击事件，积分申请按钮
			this.showApplyDialog()
		},
		methods: {
			toggleQuery() {
				this.isQueryCollapsed = !this.isQueryCollapsed
			},
			getPointStatusText(status) {
				return POINT_STATUS_TEXT[status] || status || '--'
			},
			formatPoints(points) {
				if (points === null || points === undefined || points === '') {
					return '0.00'
				}
				const num = Number(points)
				if (isNaN(num)) {
					return '0.00'
				}
				return num.toFixed(2)
			},
			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 fetchDistributerPointEarnPage(params)
					uni.hideLoading()
					
					if (!res || res.status !== 1) {
						this.lists = []
						this.loadParams.total = 0
						this.loadParams.totalPage = 1
						uni.showToast({
							title: (res && res.msg) || '查询失败',
							icon: 'none'
						})
						return
					}
					
					const rows = (res.data && res.data.Rows) || []
					const total = (res.data && res.data.Total) || 0
					
					this.loadParams.total = total * 1
					this.loadParams.totalPage = Math.ceil(total * 1 / this.page.PAGESIZE * 1)
					
					if (isRefresh) {
						this.lists = rows
						this.loadParams.isDone = false
					} else {
						this.lists = this.lists.concat(rows)
					}
				} 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 = {
					currentpage: String((this.page.PAGE - 1) * 1),
					pagesize: String(this.page.PAGESIZE * 1)
				}
				
				// 统一使用当前登录用户的客户编码
				const currentUserDistributerId = this.userInfo.code
				if (currentUserDistributerId) {
					payload.distributerId = String(currentUserDistributerId).trim()
				}
				
				if (this.queryForm.bottleCode) payload.bottleCode = this.queryForm.bottleCode.trim()
				if (this.queryForm.productName) payload.productName = this.queryForm.productName.trim()
				if (this.queryForm.detailId) payload.detailId = this.queryForm.detailId.trim()
				if (this.queryForm.startDate) payload.beginTime = this.queryForm.startDate + ' 00:00:00'
				if (this.queryForm.endDate) payload.endTime = this.queryForm.endDate + ' 23:59:59'
				
				return payload
			},
			refresh(e) {
				this.refreshing = true
				this.reset()
				this.fetchPointStatistics()
				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 = '加载中'
			},
			async fetchPointStatistics() {
				// 统一使用当前登录用户的客户编码
				const distributerId = this.userInfo.code
				if (!distributerId) return
				try {
					const res = await fetchDistributerPointStatistics({
						distributerId: String(distributerId)
					})
					if (res && res.status === 1 && res.data) {
						this.pointStatistics.total = res.data.total || '0'
						this.pointStatistics.balance = res.data.balance || '0'
					}
				} catch (error) {
					// 静默失败
				}
			},
			async showApplyDialog() {
				// 先获取积分统计信息
				const distributerId = this.userInfo.code
				if (!distributerId) {
					uni.showToast({
						title: '无法获取当前登录用户的客户编码',
						icon: 'none'
					})
					return
				}
				try {
					const res = await fetchDistributerPointStatistics({
						distributerId: String(distributerId)
					})
					if (res && res.status === 1 && res.data) {
						this.applyForm.total = res.data.total || '0'
						this.applyForm.balance = res.data.balance || '0'
						this.applyForm.apply = ''
						this.$refs.applyPopup.open('center')
					} else {
						uni.showToast({
							title: (res && res.msg) || '获取积分统计信息失败',
							icon: 'none'
						})
					}
				} catch (error) {
					uni.showToast({
						title: '获取积分统计信息异常，请稍后重试',
						icon: 'none'
					})
				}
			},
			closeApplyDialog() {
				this.$refs.applyPopup.close()
			},
			async handleApplySubmit() {
				if (!this.applyForm.apply || this.applyForm.apply.trim() === '') {
					uni.showToast({
						title: '请输入申请积分',
						icon: 'none'
					})
					return
				}
				const applyValue = Number(this.applyForm.apply)
				if (isNaN(applyValue) || applyValue < 0) {
					uni.showToast({
						title: '申请积分必须大于等于0',
						icon: 'none'
					})
					return
				}
				if (applyValue > Number(this.applyForm.balance)) {
					uni.showToast({
						title: '申请积分不能大于可用积分',
						icon: 'none'
					})
					return
				}
				// 获取当前登录用户的客户编码
				const distributerId = this.userInfo.code
				if (!distributerId) {
					uni.showToast({
						title: '无法获取当前登录用户的客户编码',
						icon: 'none'
					})
					return
				}
				this.applyLoading = true
				try {
					const params = {
						customer: String(distributerId),
						total: String(this.applyForm.total),
						balance: String(this.applyForm.balance),
						apply: String(this.applyForm.apply)
					}
					const res = await apiApplyIntegral(params)
					if (res && res.msgtype === 'S') {
						uni.showToast({
							title: res.message || '积分申请成功',
							icon: 'success'
						})
						this.closeApplyDialog()
						// 刷新积分统计信息
						this.fetchPointStatistics()
					} else {
						uni.showToast({
							title: (res && res.message) || '积分申请失败',
							icon: 'none'
						})
					}
				} catch (error) {
					uni.showToast({
						title: '积分申请异常，请稍后重试',
						icon: 'none'
					})
				} finally {
					this.applyLoading = false
				}
			}
		}
	}
</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-actions {
		flex-direction: row;
		align-items: center;
	}

	.btn-apply {
		width: 160rpx;
		height: 64rpx;
		background: #FF1D32;
		border-radius: 32rpx;
		margin-right: 16rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.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: 16rpx;
	}

	.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;
	}

	.statistics-section {
		height: 60rpx;
		padding: 0 32rpx;
		background: #fff;
		border-radius: 16rpx 0 0 16rpx;
		margin-top: 16rpx;
		margin-bottom: 16rpx;
		flex-direction: row;
		align-items: center;
		justify-content: center;
	}

	.statistics-text {
		font-size: 28rpx;
		color: #333;
	}

	.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-item {
		flex: 1;
		flex-direction: column;
		margin-right: 32rpx;
	}

	.text-block-item: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;
	}

	/* 积分申请弹窗样式 */
	.popup-content {
		width: 600rpx;
		background-color: #fff;
		border-radius: 16rpx;
		overflow: hidden;
		flex-direction: column;
	}

	.popup-header {
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 24rpx;
		border-bottom: 1px solid #f4f5f6;
		flex-shrink: 0;
	}

	.popup-title {
		font-size: 32rpx;
		font-weight: 500;
		color: #333;
	}

	.popup-close {
		font-size: 40rpx;
		color: #999;
		line-height: 40rpx;
		width: 40rpx;
		height: 40rpx;
		text-align: center;
	}

	.popup-body {
		padding: 24rpx;
		flex-direction: column;
	}

	.form-item {
		margin-bottom: 24rpx;
		flex-direction: column;
	}

	.form-item:last-child {
		margin-bottom: 0;
	}

	.form-label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 12rpx;
	}

	.form-description {
		font-size: 28rpx;
		color: #666;
		line-height: 40rpx;
	}

	.form-input {
		height: 80rpx;
		padding: 0 24rpx;
		background: #f5f5f5;
		border-radius: 8rpx;
		font-size: 28rpx;
		color: #333;
		line-height: 80rpx;
	}

	.popup-footer {
		flex-direction: row;
		align-items: center;
		justify-content: flex-end;
		padding: 16rpx 24rpx;
		border-top: 1px solid #f4f5f6;
		flex-shrink: 0;
	}

	.btn-cancel {
		width: 160rpx;
		height: 64rpx;
		background: #f5f5f5;
		border-radius: 32rpx;
		margin-right: 24rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.btn-cancel .btn-text {
		color: #333;
	}

	.btn-confirm {
		width: 160rpx;
		height: 64rpx;
		background: $wly-primary-color;
		border-radius: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.btn-confirm[disabled] {
		opacity: 0.6;
	}
</style>
