<template>
	<view>
		<view class="fe-modal-overlay" :class="{ 'fe-modal-overlay--active': active }" @tap="$emit('close')" />
		<view class="fe-modal fe-batch-qr-modal" :class="{ 'fe-modal--active': active }">
			<view class="fe-batch-qr-modal__body">
				<view class="fe-batch-qr-modal__title">{{ batch.modalTitle }}</view>
				<view class="fe-batch-qr-modal__subtitle">{{ batchSubtitle }}</view>

				<view class="fe-batch-qr-modal__code-wrap">
					<image
						v-if="qrImageUrl"
						class="fe-batch-qr-modal__img"
						:src="qrImageUrl"
						mode="aspectFit"
					/>
					<view v-else class="fe-batch-qr-modal__matrix">
						<view
							v-for="(cell, i) in qrCells"
							:key="i"
							class="fe-batch-qr-modal__cell"
							:class="{ 'fe-batch-qr-modal__cell--on': cell }"
						/>
					</view>
				</view>

				<view class="fe-batch-qr-modal__hint">{{ batch.hint }}</view>

				<view class="fe-batch-qr-modal__progress">
					<view class="fe-progress-label">
						<text class="fe-progress-label__text">登记进度</text>
						<text class="fe-progress-label__value">{{ progressText }}</text>
					</view>
					<view class="fe-progress-track">
						<view class="fe-progress-fill" :style="{ width: progressPercent + '%' }" />
					</view>
				</view>

				<view class="fe-batch-qr-modal__actions">
					<view class="fe-batch-qr-modal__action" @tap="onSave">
						<text class="fe-batch-qr-modal__action-icon">🖼</text>
						<text>保存相册</text>
					</view>
					<!-- #ifdef MP-WEIXIN -->
					<button class="fe-batch-qr-modal__action fe-batch-qr-modal__share-btn" open-type="share">
						<text class="fe-batch-qr-modal__action-icon">↗</text>
						<text>分享好友</text>
					</button>
					<!-- #endif -->
					<!-- #ifndef MP-WEIXIN -->
					<view class="fe-batch-qr-modal__action" @tap="onShare">
						<text class="fe-batch-qr-modal__action-icon">↗</text>
						<text>分享好友</text>
					</view>
					<!-- #endif -->
					<view class="fe-batch-qr-modal__action" @tap="onCopyLink">
						<text class="fe-batch-qr-modal__action-icon">🔗</text>
						<text>复制链接</text>
					</view>
					<view class="fe-batch-qr-modal__action" @tap="onViewProgress">
						<text class="fe-batch-qr-modal__action-icon">📈</text>
						<text>查看进度</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { BATCH_QR, QR_DEMO_PATTERN, showToast } from '@/common/chat-data.js'
import { resolveApiAssetUrl } from '@/common/config.js'
import { getDraftWorkflowProgress } from '@/api/draft.js'
import { mapRegistrationBatchDetail } from '@/utils/registration-batch.js'

export default {
	name: 'FeBatchQrModal',
	props: {
		active: { type: Boolean, default: false },
		batch: {
			type: Object,
			default() {
				return { ...BATCH_QR }
			}
		}
	},
	data() {
		return {
			progressLoading: false,
			progressCurrent: null,
			progressTotal: null
		}
	},
	computed: {
		qrImageUrl() {
			const raw = this.batch.qrCodeUrl
				|| this.batch.qr_code_url
				|| ''
			return resolveApiAssetUrl(raw)
		},
		qrCells() {
			return QR_DEMO_PATTERN.split('').map((c) => c === '1')
		},
		batchSubtitle() {
			if (this.batch.subtitle) return this.batch.subtitle
			const title = this.batch.title || ''
			const id = this.batch.batchId || this.batch.draftId || ''
			if (title && id) return `${title} ${id}`
			return title || id || ''
		},
		registeredCount() {
			if (this.progressCurrent != null) return this.progressCurrent
			return this.batch.registered != null ? Number(this.batch.registered) : 0
		},
		totalCount() {
			if (this.progressTotal != null) return this.progressTotal
			return this.batch.total != null ? Number(this.batch.total) : 0
		},
		progressText() {
			if (this.progressLoading && this.progressCurrent == null) return '加载中...'
			return `${this.registeredCount}/${this.totalCount}`
		},
		progressPercent() {
			if (!this.totalCount) return 0
			return Math.round((this.registeredCount / this.totalCount) * 100)
		},
		draftId() {
			return this.batch.draftId != null ? this.batch.draftId : null
		}
	},
	watch: {
		active(val) {
			if (val) this.fetchProgress()
			else this.resetProgress()
		},
		draftId() {
			if (this.active) this.fetchProgress()
		}
	},
	methods: {
		resetProgress() {
			this.progressLoading = false
			this.progressCurrent = null
			this.progressTotal = null
		},
		async fetchProgress() {
			const draftId = this.draftId
			if (draftId == null || draftId === '') {
				this.resetProgress()
				return
			}
			this.progressLoading = true
			try {
				const raw = await getDraftWorkflowProgress(draftId, { showError: false })
				const detail = mapRegistrationBatchDetail(raw)
				const current = detail.progress && detail.progress.current != null
					? detail.progress.current
					: 0
				const total = detail.progress && detail.progress.total != null
					? detail.progress.total
					: (detail.stats && detail.stats.expected) || 0
				this.progressCurrent = current
				this.progressTotal = total
				this.$emit('progress-loaded', {
					draftId,
					registered: current,
					total,
					detail
				})
			} catch (e) {
				// 保留 batch 兜底数字，不打断弹框
				this.progressCurrent = null
				this.progressTotal = null
			} finally {
				this.progressLoading = false
			}
		},
		onSave() {
			const url = this.qrImageUrl
			if (!url) {
				showToast('暂无二维码图片')
				this.$emit('save')
				return
			}
			// #ifdef MP-WEIXIN
			uni.downloadFile({
				url,
				success: (res) => {
					if (res.statusCode !== 200 || !res.tempFilePath) {
						showToast('下载二维码失败')
						return
					}
					uni.saveImageToPhotosAlbum({
						filePath: res.tempFilePath,
						success: () => showToast('已保存到相册'),
						fail: () => showToast('保存失败，请检查相册权限')
					})
				},
				fail: () => showToast('下载二维码失败')
			})
			// #endif
			// #ifndef MP-WEIXIN
			showToast('请在微信小程序中保存到相册')
			// #endif
			this.$emit('save')
		},
		onShare() {
			// H5 / 非微信端兜底；微信端走 open-type="share" + 页面 onShareAppMessage
			showToast('请在微信小程序中分享给好友')
			this.$emit('share')
		},
		onCopyLink() {
			const link = this.batch.shareLink || ''
			if (!link) {
				showToast('暂无登记链接')
				return
			}
			uni.setClipboardData({
				data: link,
				success: () => showToast('已复制小程序路径')
			})
			this.$emit('copy')
		},
		onViewProgress() {
			this.$emit('progress')
		}
	}
}
</script>

<style lang="scss" scoped>
.fe-batch-qr-modal {
	max-width: 760rpx;
}

.fe-batch-qr-modal__body {
	padding: 40rpx 40rpx 36rpx;
	text-align: center;
}

.fe-batch-qr-modal__title {
	font-size: 34rpx;
	font-weight: 700;
	color: $fe-foreground;
	margin-bottom: 8rpx;
}

.fe-batch-qr-modal__subtitle {
	font-size: 26rpx;
	color: $fe-muted;
	margin-bottom: 24rpx;
}

.fe-batch-qr-modal__code-wrap {
	width: 360rpx;
	height: 360rpx;
	margin: 0 auto 20rpx;
	padding: 24rpx;
	background: #fff;
	border: 2rpx solid $fe-border;
	border-radius: $fe-radius-md;
	box-sizing: border-box;
	display: flex;
	align-items: center;
	justify-content: center;
}

.fe-batch-qr-modal__img {
	width: 100%;
	height: 100%;
	display: block;
}

.fe-batch-qr-modal__matrix {
	width: 280rpx;
	height: 280rpx;
	display: grid;
	grid-template-columns: repeat(15, 1fr);
	gap: 3rpx;
}

.fe-batch-qr-modal__cell {
	background: #fff;
	border-radius: 2rpx;
}

.fe-batch-qr-modal__cell--on {
	background: $fe-foreground;
}

.fe-batch-qr-modal__hint {
	font-size: 26rpx;
	color: $fe-muted;
	margin-bottom: 24rpx;
}

.fe-batch-qr-modal__progress {
	margin-bottom: 32rpx;
	text-align: left;
}

.fe-progress-label__text {
	color: $fe-muted;
}

.fe-progress-label__value {
	font-weight: 700;
	color: $fe-primary;
}

.fe-batch-qr-modal__actions {
	display: grid;
	grid-template-columns: 1fr 1fr;
	gap: 16rpx;
}

.fe-batch-qr-modal__action {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 10rpx;
	padding: 20rpx 16rpx;
	border-radius: $fe-radius-sm;
	border: 1rpx solid $fe-border;
	background: $fe-surface;
	font-size: 26rpx;
	font-weight: 600;
	color: $fe-foreground;
	box-sizing: border-box;
}

.fe-batch-qr-modal__action:active {
	background: $fe-primary-bg;
}

.fe-batch-qr-modal__share-btn {
	margin: 0;
	line-height: inherit;
	font-size: 26rpx;
	font-weight: 600;
	color: $fe-foreground;
	border-radius: $fe-radius-sm;
	&::after {
		border: none;
	}
}

.fe-batch-qr-modal__action-icon {
	font-size: 30rpx;
	line-height: 1;
}
</style>
