<template>
	<view v-if="visible" class="bc-setup-mask" @tap="onMaskTap">
		<view class="bc-setup-sheet" @tap.stop>
			<view class="bc-setup-hd">
				<text class="bc-setup-title">{{ copy.title }}</text>
				<view class="bc-setup-close" @tap="close">
					<text class="bc-setup-close-txt">×</text>
				</view>
			</view>

			<scroll-view scroll-y class="bc-setup-scroll" :show-scrollbar="false">
				<view class="bc-setup-block">
					<text class="bc-setup-label">{{ copy.cover }}</text>
					<view class="bc-setup-cover" @tap="pickCover">
						<image
							v-if="coverPreview"
							class="bc-setup-cover-img"
							:src="coverPreview"
							mode="aspectFill"
						/>
						<view v-else class="bc-setup-cover-empty">
							<text class="bc-setup-cover-plus">＋</text>
							<text class="bc-setup-cover-hint">{{ copy.coverHint }}</text>
						</view>
					</view>
				</view>

				<view class="bc-setup-block">
					<view class="bc-setup-label-row">
						<text class="bc-setup-label">{{ copy.theme }}</text>
						<text class="bc-setup-count">{{ themeLen }}/50</text>
					</view>
					<textarea
						class="bc-setup-textarea"
						v-model="form.content"
						:placeholder="copy.themePlaceholder"
						placeholder-class="bc-setup-placeholder"
						maxlength="50"
						:adjust-position="true"
					/>
				</view>

				<view class="bc-setup-block">
					<text class="bc-setup-label">{{ copy.payment }}</text>
					<view class="bc-setup-seg">
						<view
							class="bc-setup-seg-item"
							:class="{ 'bc-setup-seg-item--on': form.is_paid === 0 }"
							@tap="setPaid(0)"
						>
							<text
								class="bc-setup-seg-txt"
								:class="{ 'bc-setup-seg-txt--on': form.is_paid === 0 }"
							>{{ copy.free }}</text>
						</view>
						<view
							class="bc-setup-seg-item"
							:class="{ 'bc-setup-seg-item--on': form.is_paid === 1 }"
							@tap="setPaid(1)"
						>
							<text
								class="bc-setup-seg-txt"
								:class="{ 'bc-setup-seg-txt--on': form.is_paid === 1 }"
							>{{ copy.paid }}</text>
						</view>
					</view>
					<view v-if="form.is_paid === 1" class="bc-setup-paid-fields">
						<view class="bc-setup-field">
							<text class="bc-setup-field-label">{{ copy.paidAmount }}</text>
							<input
								class="bc-setup-input"
								type="digit"
								v-model="form.paid_money"
								:placeholder="copy.paidAmountPh"
							/>
						</view>
						<view class="bc-setup-field">
							<text class="bc-setup-field-label">{{ copy.freePreview }}</text>
							<input
								class="bc-setup-input"
								type="number"
								v-model="form.free_look_time"
								:placeholder="copy.freePreviewPh"
							/>
						</view>
					</view>
				</view>
			</scroll-view>

			<view class="bc-setup-ft" :style="{ paddingBottom: safeBottom + 'px' }">
				<view class="bc-setup-submit" @tap="submit">
					<text class="bc-setup-submit-txt">{{ copy.start }}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import appSettings from '@/core/config/app-settings'
import { fetchUploadConfig, uploadImageFile } from '@/features/dynamics/publish-gateway'

export default {
	name: 'BroadcastSetupSheet',
	props: {
		visible: { type: Boolean, default: false },
		safeBottom: { type: Number, default: 0 }
	},
	data() {
		return {
			form: {
				image: '',
				content: '',
				is_paid: 0,
				paid_money: '',
				free_look_time: '',
				goods_ids: []
			},
			coverPreview: '',
			uploading: false
		}
	},
	computed: {
		copy() {
			const t = this.$t.bind(this)
			return {
				title: t('live.broadcastSetupTitle'),
				cover: t('live.broadcastCover'),
				coverHint: t('live.broadcastCoverHint'),
				theme: t('live.broadcastTheme'),
				themePlaceholder: t('live.broadcastThemePlaceholder'),
				payment: t('live.broadcastPayment'),
				free: t('live.broadcastFree'),
				paid: t('live.broadcastPaid'),
				paidAmount: t('live.broadcastPaidAmount'),
				paidAmountPh: t('live.broadcastPaidAmountPh'),
				freePreview: t('live.broadcastFreePreview'),
				freePreviewPh: t('live.broadcastFreePreviewPh'),
				start: t('live.broadcastStart')
			}
		},
		themeLen() {
			return String(this.form.content || '').length
		}
	},
	watch: {
		visible(val) {
			if (!val) return
			const user = (this.$store && this.$store.state.user) || {}
			if (!this.form.image && user.avatar) {
				this.form.image = user.avatar
				this.coverPreview = this.toPreview(user.avatar)
			}
		}
	},
	methods: {
		defaultCover() {
			const user = (this.$store && this.$store.state.user) || {}
			const avatar = user.avatar || ''
			if (!avatar) return ''
			if (/^https?:\/\//.test(avatar)) return avatar
			return `${appSettings.cdnurl || ''}${avatar.startsWith('/') ? avatar : `/${avatar}`}`
		},
		toPreview(url) {
			if (!url) return ''
			if (/^https?:\/\//.test(url)) return url
			return `${appSettings.cdnurl || ''}${url.startsWith('/') ? url : `/${url}`}`
		},
		onMaskTap() {
			this.close()
		},
		close() {
			this.$emit('close')
		},
		setPaid(flag) {
			this.form.is_paid = flag ? 1 : 0
		},
		pickCover() {
			if (this.uploading) return
			uni.chooseImage({
				count: 1,
				sourceType: ['album'],
				sizeType: ['compressed'],
				success: async (res) => {
					const path = res.tempFilePaths && res.tempFilePaths[0]
					if (!path) return
					this.uploading = true
					uni.showLoading({ title: this.$t('live.broadcastUploading'), mask: true })
					try {
						const cfg = await fetchUploadConfig()
						const url = await uploadImageFile(path, cfg)
						this.form.image = url
						this.coverPreview = this.toPreview(url)
					} catch (err) {
						uni.showToast({
							title: err?.message || this.$t('live.broadcastUploadFailed'),
							icon: 'none'
						})
					} finally {
						this.uploading = false
						uni.hideLoading()
					}
				}
			})
		},
		validate() {
			if (!this.form.image) {
				uni.showToast({ title: this.$t('live.broadcastCoverRequired'), icon: 'none' })
				return false
			}
			if (!String(this.form.content || '').trim()) {
				uni.showToast({ title: this.$t('live.broadcastThemeRequired'), icon: 'none' })
				return false
			}
			if (this.form.is_paid === 1) {
				const money = Number(this.form.paid_money)
				if (!money || money <= 0) {
					uni.showToast({ title: this.$t('live.broadcastPaidInvalid'), icon: 'none' })
					return false
				}
				const sec = Number(this.form.free_look_time)
				if (sec < 0 || Number.isNaN(sec)) {
					uni.showToast({ title: this.$t('live.broadcastFreePreviewInvalid'), icon: 'none' })
					return false
				}
			}
			return true
		},
		submit() {
			if (!this.validate()) return
			const payload = {
				image: this.form.image,
				content: String(this.form.content).trim(),
				is_paid: this.form.is_paid,
				paid_money: this.form.is_paid === 1 ? Number(this.form.paid_money) || 0 : 0,
				free_look_time: this.form.is_paid === 1 ? Number(this.form.free_look_time) || 0 : 0,
				goods_ids: []
			}
			this.$emit('start', payload)
			this.close()
		},
		reset() {
			this.form = {
				image: '',
				content: '',
				is_paid: 0,
				paid_money: '',
				free_look_time: '',
				goods_ids: []
			}
			this.coverPreview = ''
		}
	}
}
</script>

<style scoped>
.bc-setup-mask {
	position: fixed;
	left: 0;
	right: 0;
	top: 0;
	bottom: 0;
	z-index: 500;
	background-color: rgba(26, 29, 41, 0.45);
	display: flex;
	flex-direction: column;
	justify-content: flex-end;
}

.bc-setup-sheet {
	width: 100%;
	max-height: 88vh;
	background-color: #f4f6fb;
	border-radius: 28rpx 28rpx 0 0;
	overflow: hidden;
	display: flex;
	flex-direction: column;
}

.bc-setup-hd {
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: space-between;
	padding: 28rpx 32rpx 16rpx;
}

.bc-setup-title {
	font-size: 34rpx;
	font-weight: 700;
	color: #1a1d26;
}

.bc-setup-close {
	width: 56rpx;
	height: 56rpx;
	border-radius: 28rpx;
	background-color: #ffffff;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 4rpx 16rpx rgba(74, 140, 255, 0.1);
}

.bc-setup-close-txt {
	font-size: 40rpx;
	line-height: 1;
	color: #8a8d9e;
}

.bc-setup-scroll {
	flex: 1;
	max-height: 62vh;
	padding: 0 32rpx;
	box-sizing: border-box;
}

.bc-setup-block {
	margin-bottom: 28rpx;
}

.bc-setup-label-row {
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 16rpx;
}

.bc-setup-label {
	font-size: 28rpx;
	font-weight: 600;
	color: #1a1d26;
	margin-bottom: 16rpx;
}

.bc-setup-count {
	font-size: 24rpx;
	color: #8a8d9e;
}

.bc-setup-cover {
	width: 100%;
	height: 320rpx;
	border-radius: 24rpx;
	overflow: hidden;
	background-color: #ffffff;
	box-shadow: 0 8rpx 28rpx rgba(74, 140, 255, 0.08);
}

.bc-setup-cover-img {
	width: 100%;
	height: 100%;
}

.bc-setup-cover-empty {
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.bc-setup-cover-plus {
	font-size: 56rpx;
	color: #4a8cff;
	line-height: 1;
	margin-bottom: 12rpx;
}

.bc-setup-cover-hint {
	font-size: 24rpx;
	color: #8a8d9e;
}

.bc-setup-textarea {
	width: 100%;
	min-height: 160rpx;
	padding: 24rpx;
	box-sizing: border-box;
	border-radius: 20rpx;
	background-color: #ffffff;
	font-size: 28rpx;
	color: #1a1d26;
	line-height: 1.5;
	box-shadow: 0 8rpx 28rpx rgba(74, 140, 255, 0.06);
}

.bc-setup-placeholder {
	color: #b0b3c0;
}

.bc-setup-seg {
	display: flex;
	flex-direction: row;
	padding: 6rpx;
	border-radius: 16rpx;
	background-color: #e8edf5;
}

.bc-setup-seg-item {
	flex: 1;
	padding: 18rpx 0;
	border-radius: 12rpx;
	align-items: center;
	justify-content: center;
	display: flex;
}

.bc-setup-seg-item--on {
	background-color: #ffffff;
	box-shadow: 0 4rpx 12rpx rgba(74, 140, 255, 0.12);
}

.bc-setup-seg-txt {
	font-size: 28rpx;
	color: #8a8d9e;
}

.bc-setup-seg-txt--on {
	color: #4a8cff;
	font-weight: 600;
}

.bc-setup-paid-fields {
	margin-top: 20rpx;
}

.bc-setup-field {
	margin-bottom: 16rpx;
}

.bc-setup-field-label {
	display: block;
	font-size: 24rpx;
	color: #8a8d9e;
	margin-bottom: 10rpx;
}

.bc-setup-input {
	width: 100%;
	height: 80rpx;
	padding: 0 24rpx;
	box-sizing: border-box;
	border-radius: 16rpx;
	background-color: #ffffff;
	font-size: 28rpx;
	color: #1a1d26;
}

.bc-setup-ft {
	padding: 16rpx 32rpx 24rpx;
	background-color: #f4f6fb;
}

.bc-setup-submit {
	height: 96rpx;
	border-radius: 48rpx;
	background: linear-gradient(135deg, #4a8cff 0%, #6ea8ff 100%);
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 12rpx 32rpx rgba(74, 140, 255, 0.28);
}

.bc-setup-submit-txt {
	font-size: 32rpx;
	font-weight: 600;
	color: #ffffff;
}
</style>
