<template>
	<view class="make-music-detail">
		<!-- 顶部导航 -->
		<view class="nav-bar">
			<view class="left">
				<view class="uni-btn-icon" @click="goBack">&#xe601;</view>
				<view class="create">音乐制作</view>
				<image src="@/static/makedetail/cz_icon_lingganchuangzuo.png" class="edit"></image>
			</view>
			<view class="right">
				<view class="coinM" @click="isRecharge ? goPage('/pages/vip/M_purchase')  : ''">
					<image src="/static/icon/coin_m.png" mode="aspectFit"></image>
					<text>{{ myinfo.num_gmm | formatNumberToK }}</text>
					<view class="money-add" v-if="isRecharge">+</view>
				</view>
				<view class="coinC" @click="isRecharge ?goPage('/pages/my/job?type=recharge')  : ''">
					<image src="/static/icon/coin_cd.png" mode="aspectFit"></image>
					<text>{{ myinfo.num_gmd | formatNumberToK }}</text>
					<view class="money-add" v-if="isRecharge">+</view>
				</view>
			</view>
		</view>

		<!-- 排队预览区域 -->
		<view class="preview-section lineUp-section" v-if="queuing">
			<view class="section-title">
				<text>创作预览</text>
				<view class="member-box">
					<image src="@/static/makedetail/wd_icon_vip(1).png" mode="aspectFit"></image>
					升级会员插队加速
				</view>
			</view>
			<view class="preview-card">
				<image src="@/static/makedetail/cz_icon_jiazai.png" mode="aspectFit"></image>
				<view class="text1">{{ queueMessage }}</view>
				<view class="text2">退出不影响继续生成</view>
			</view>
		</view>

		<!-- 创作预览区域 -->
		<view class="preview-section" v-if="inQueue">
			<view class="section-title">创作预览</view>
			<view class="preview-card">
				<image src="@/static/makedetail/cz_icon_shengcheng.png" mode="aspectFit"></image>
				<view class="text1">生成中0%</view>
				<view class="text2">退出不影响继续生成</view>
			</view>
		</view>

		<!-- 主要内容区 -->
		<view class="content">
			<!-- 歌曲名称输入 -->
			<view class="input-section">
				<text class="label">歌曲名称</text>
				<input type="text" placeholder="请输入名称..." class="input-field" maxlength="30" v-model="songName"
					:disabled="doYouWantToEdit()" />
				<text class="count lyricCount">{{ songName.length }}/30</text>
			</view>

			<!-- 创作歌词输入 -->
			<view class="input-section">
				<text class="label">创作歌词</text>
				<textarea placeholder="请在此处输入您想要进行联想的内容或者歌词" class="textarea-field" maxlength="800" v-model="lyrics"
					:disabled="doYouWantToEdit()" :style="{ height: textareaHeight + 'px' }" @input="onTextareaInput" />
				<view class="textarea-footer">
					<text class="count">{{ lyrics.length }}/800</text>
					<text class="ai-btn" v-if="false">
						<image src="@/static/makedetail/cz_btn_airunse.png"></image>
					</text>
				</view>
			</view>

			<!-- 音乐风格选择 -->
			<view class="style-section">
				<text class="label">音乐风格</text>
				<view class="tabs">
					<text :class="{ 'active': selectedTab === 'emotion' }" @click="selectTab('emotion')">
						情感
						<view class="indicator-triangle">
						</view>
					</text>
					<text :class="{ 'active': selectedTab === 'genre' }" @click="selectTab('genre')">
						流派
						<view class="indicator-triangle">
						</view>
					</text>
					<text :class="{ 'active': selectedTab === 'era' }" @click="selectTab('era')">
						年代
						<view class="indicator-triangle">
						</view>
					</text>
					<text :class="{ 'active': selectedTab === 'instrument' }" @click="selectTab('instrument')">
						乐器
						<view class="indicator-triangle">
						</view>
					</text>
				</view>
				<view class="tags">
					<text v-for="(tag, index) in currentTags" :key="index"
						:class="['tag', { active: selectedTags[selectedTab].includes(tag) }]"
						@click="doYouWantToEdit() ? state() : toggleTag(tag)">
						{{ tag }}
					</text>
				</view>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="bottom-button">
			<button v-if="doYouWantToEdit" class="generate-btn" @click="generateMusic">立即生成
				<image src="/static/icon/coin_cd.png" mode="aspectFit"></image>
				10
			</button>

			<view v-else class="generate-btn prohibit">生成中 </view>

			<view v-if="isRecharge" class="promotion-link" @click="goPage('/pages/vip/index')">
				<image class="vip" src="/static/makedetail/wd_icon_vip(1).png" mode="aspectFit"></image>
				<text> 即刻开通订阅，获取各种福利! </text>
				<image class="jiantou" src="/static/makedetail/cz_icon_jiantou.png" mode="aspectFit"></image>
			</view>
		</view>

		<!-- 新手引导组件 -->
		<novice-guidance :step="step" v-if="isGuiding"></novice-guidance>
	</view>
</template>

<script>
import { mapState } from 'vuex'
export default {
	name: 'MakeMusicDetail',
	data() {
		return {
			songName: '',
			lyrics: '',
			selectedTags: {
				emotion: [],
				genre: [],
				era: [],
				instrument: []
			},
			textareaHeight: 120,
			minHeight: 120,
			selectedTab: 'emotion',
			tagOptions: {
				emotion: ['欢快', '悲伤', '积极', '浪漫', '忧郁', '华丽', '闪耀', '神秘', '惊怒', '紧张', '恐怖', '平静'],
				genre: ['流行', '摇滚', '民谣', '电子', 'R&B', '嘻哈', '古典', '爵士'],
				era: ['80年代', '90年代', '00年代', '10年代', '20年代'],
				instrument: ['钢琴', '吉他', '贝斯', '鼓', '小提琴', '萨克斯', '电子合成器']
			},
			inQueue: false,//是否创作中
			queuing: false,//是否排队中
			queueMessage: '',
			myinfo: {},
			step: {
				name: "makeMusicGuide",
				guideList: [
					{
						el: ".right",
						tips: "积分可在这里查看，每日签到可获得积分！",
						next: "知道了",
					},
					{
						el: ".input-field",
						tips: "在这里输入您想要创作的歌曲名称",
						next: "知道了",
					},
					{
						el: ".textarea-field",
						tips: "在这里输入歌词内容，AI将根据歌词生成音乐",
						next: "知道了",
					},
					{
						el: ".tabs",
						tips: "选择音乐风格，包括情感、流派、年代和乐器",
						next: "知道了",
					},
					{
						el: ".tags",
						tips: "点击选择具体的风格标签，可以多选",
						next: "知道了",
					},
					{
						el: ".generate-btn",
						tips: "点击这里开始生成您的音乐作品",
						next: "完成",
					}]
			}
		}
	},
	onLoad(e) {
		// this.checkQueueStatus();
		this.getMyInfo();
		if (e.id) {
			this.getQueueDetail(e.id)
		} 
						
	},
	computed: {
		currentTags() {
			return this.selectedTab ? this.tagOptions[this.selectedTab] : [];
		},
		...mapState('switchingModule', ['isRecharge', 'isGuiding'])
	},
	methods: {
		doYouWantToEdit() {
			return this.inQueue || this.queuing
		},
		goBack() {
			uni.navigateBack({
				delta: 1
			});
		},
		getMyInfo() {
			uni.request({
				url: this.$apiHost + '/My/getnum',
				method: 'GET',
				header: {
					'content-type': 'application/json',
					'sign': getApp().globalData.headerSign
				},
				data: {
					uuid: getApp().globalData.uuid
				},
				success: (res) => {
					console.log("获取用户信息：", res.data);
					this.myinfo = res.data
				}
			})

		},
		checkQueueStatus() {
			uni.request({
				url: this.$apiHost + '/WorkAI/queueStatus',
				method: 'GET',
				header: {
					'content-type': 'application/json',
					'sign': getApp().globalData.headerSign
				},
				data: {
					uuid: getApp().globalData.uuid,
					task_type: 2
				},
				success: (res) => {
					console.log("音乐队列状态：", res.data);
					if (res.data.success === "yes") {
						this.inQueue = res.data.in_queue
						if (this.inQueue) {
							this.queueMessage = res.data.str
						}
					}
				},
				fail: (err) => {
					console.log('获取队列状态失败：', err);
					uni.showToast({
						title: '获取状态失败',
						icon: 'none'
					});
				}
			})
			this.getMyInfo();
		},
		generateMusic() {
			if (!this.songName.trim()) {
				uni.showToast({
					title: '请输入歌曲名称',
					icon: 'none'
				})
				return
			}
			if (!this.lyrics.trim()) {
				uni.showToast({
					title: '请输入歌词内容',
					icon: 'none'
				})
				return
			}

			// 合并所有选中的标签
			let allSelectedTags = [
				...this.selectedTags.emotion,
				...this.selectedTags.genre,
				...this.selectedTags.era,
				...this.selectedTags.instrument
			];
			console.log(this.lyrics, this.songName,);

			let that = this
			uni.request({
				url: this.$apiHost + '/WorkAI/creatorMusic',
				data: {
					uuid: getApp().globalData.uuid,
					name: this.songName,
					lyrics: this.lyrics,
					style: allSelectedTags.join(',')
				},
				method: 'POST',
				header: {
					'Content-Type': 'application/x-www-form-urlencoded',
					'sign': getApp().globalData.headerSign
				},
				dataType: 'json',
				success: (res) => {
					console.log("生成结果：", res.data);
					uni.showToast({
						title: res.data.str || '请求成功',
						icon: 'none'
					});
					if (res.data.success == "yes") {
						setTimeout(function () {
							// that.checkQueueStatus()
							//返回上一页
							// uni.navigateBack()
							// 使用全局变量存储状态
							getApp().globalData.needSwitchToGenerating = true;
							uni.switchTab({ url: '/pages/my/my' });
						}, 1500);
					}
				},
				fail: (err) => {
					console.log('生成失败：', err);
					uni.showToast({
						title: '生成请求失败',
						icon: 'none'
					});
				}
			})
		},
		onTextareaInput(e) {
			const lineHeight = 20; // 假设每行高度为20px
			const padding = 30; // 上下padding各15px
			const value = e.detail.value;
			const lines = value.split('\n').length;
			// 计算每行的平均字符数
			const avgCharsPerLine = 30; // 根据实际输入框宽度调整
			const textLines = Math.ceil(value.length / avgCharsPerLine);

			// 取行数的最大值，确保有足够空间显示
			const totalLines = Math.max(lines, textLines);
			const newHeight = Math.max(totalLines * lineHeight + padding, this.minHeight);

			this.textareaHeight = newHeight;
		},
		selectTab(tab) {
			if (this.selectedTab !== tab) {
				this.selectedTab = tab;
				// 不再清空已选择的标签
			}
		},
		state() {
			if (this.inQueue) {
				uni.showToast({
					title: '正在创作中无法修改',
					icon: 'none'
				})
			} else if (this.queuing) {
				uni.showToast({
					title: '正在排队中无法修改',
					icon: 'none'
				})
			}
		},

		toggleTag(tag) {
			if (this.selectedTags[this.selectedTab].includes(tag)) {
				this.selectedTags[this.selectedTab] = this.selectedTags[this.selectedTab].filter(t => t !== tag);
			} else {
				this.selectedTags[this.selectedTab].push(tag);
			}
		},
		getQueueDetail(id) {
			if (!id) {
				return
			}
			let that = this
			uni.request({
				url: this.$apiHost + '/WorkAI/getQueueDetail',
				data: {
					uuid: getApp().globalData.uuid,
					id: id
				},
				header: {
					'Content-Type': 'application/x-www-form-urlencoded',
					'sign': getApp().globalData.headerSign
				},
				dataType: 'json',
				success: (res) => {
					console.log("查询单个结果：", res.data);
					if (res.data.success == "yes") {
						var { queuePosition, allPosition, song_name, lyrics, style } = res.data.data
						that.songName = song_name
						that.lyrics = lyrics

						const styles = style.split(',');
						styles.forEach(tag => {
							for (const [key, tags] of Object.entries(that.tagOptions)) {
								if (tags.includes(tag)) {
									that.selectedTags[key].push(tag);
									break;
								}
							}
						});

						if (queuePosition == allPosition) {
							// 创作中逻辑
							that.inQueue = true
						} else if (queuePosition < allPosition) {
							// 排队中逻辑
							that.queuing = true

						}
					}
				},
				fail: (err) => {
					console.log('查询失败失败：', err);
					uni.showToast({
						title: '查询失败请求失败',
						icon: 'none'
					});
				}
			})
		},
		goPage(page) {
			uni.navigateTo({
				url: page,
			});
		},
	}
}
</script>

<style lang="scss">
@import './makeMusicDetail.scss';
</style>