<template>
	<view class="makedetail-container">
		<view class="status-bar"></view>
		<!-- 顶部导航 -->
		<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">排队中{{ queuePosition + '/' + allPosition }}</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">生成中{{ progress }}%</view>
				<view class="text2">退出不影响继续生成</view>
			</view>
		</view>

		<!-- 以下区域在非排队状态下显示 -->
		<view>
			<!-- 创作描述输入区 -->
			<view class="description-section">
				<view class="section-header">
					<text class="section-title">创作描述<text style="display: none;" class="required">*</text></text>
					<view class="clear-text" @click="doYouWantToEdit() ? state() : clearDescription">
						<image src="/static/clear.png" mode="aspectFit"></image>
						<view class="clear-box">
							<image src="@/static/makedetail/cz_icon_qingkongwenben.png" class="edit"></image>
							<text>清空文本</text>
						</view>
					</view>
				</view>
				<textarea auto-height class="input-area" v-model="description" placeholder="请输入描述语,例如:穿着白色运动服,外表俊朗..."
					maxlength="1000" @input="onDescriptionInput" :disabled="doYouWantToEdit()"></textarea>
				<view class="word-count">{{ descriptionLength }}/1000</view>
			</view>

			<!-- 行为动作选择区 -->
			<view class="action-section">
				<view class="section-title">行为动作</view>
				<input :disabled="doYouWantToEdit()" class="input-box" v-model="action" placeholder="可输入也可点击推荐词" />
				<view class="tag-group">
					<text class="tag" v-for="(item, index) in actionTags" :key="index"
						@click="doYouWantToEdit() ? state() : selectAction(item)" :class="{ active: action == item }">{{
							item }}</text>
				</view>
			</view>

			<!-- 主体环境选择区 -->
			<view class="environment-section">
				<view class="section-title">主体环境</view>
				<input class="input-box" v-model="environment" :disabled="doYouWantToEdit()" placeholder="可输入也可点击推荐词" />
				<view class="tag-group">
					<text class="tag" v-for="(item, index) in environmentTags" :key="index"
						@click="doYouWantToEdit() ? state() : selectEnvironment(item)"
						:class="{ active: environment == item }">{{ item }}</text>
				</view>
			</view>

			<!-- 主体形象选择区 -->
			<view class="image-section">
				<view class="section-title">主体形象</view>
				<input class="input-box" v-model="image" :disabled="doYouWantToEdit()" placeholder="可输入也可点击推荐词" />
				<view class="tag-group">
					<text class="tag" v-for="(item, index) in imageTags" :key="index"
						@click="doYouWantToEdit() ? state() : selectImage(item)" :class="{ active: image == item }">{{
							item
						}}</text>
				</view>
			</view>
			<!-- 参考风格选择区 -->
			<view class="style-section">
				<view class="section-title">选择参考风格<text style="display: none;" class="required">*</text></view>
				<scroll-view class="style-scroll" scroll-x>
					<view class="style-item" v-for="(item, index) in styleList" :key="index"
						:class="{ 'active': selectedStyle === index }"
						@click="doYouWantToEdit() ? state() : selectStyle(index)">
						<image :src="item.image" mode="aspectFill"></image>
						<text>{{ item.name }}</text>
					</view>
				</scroll-view>

			</view>

			<!-- 底部按钮 -->
			<view class="bottom-button">
				<button v-if="doYouWantToEdit" class="generate-btn" @click="generateImage">立即生成
					<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>
		</view>
		<!-- 新手引导组件 -->
		<novice-guidance :step="step" v-if="isGuiding"></novice-guidance>
	</view>
</template>

<script>
import { mapState } from 'vuex'
export default {
	data() {
		return {
			queuePosition: '0',
			allPosition: '0',
			progress: '', //创作进度 
			description: '',
			descriptionLength: 0,
			action: '',
			environment: '',
			image: '',
			selectedStyle: -1,
			actionTags: ['跳舞', '唱歌', '喝咖啡', '看书', '运动'],
			environmentTags: ['都市大道', '大树底下', '办公室', '厨房'],
			imageTags: ['戴着墨镜', '戴着耳机', '戴着帽子', '手持冲浪板'],
			styleList: [{
				name: '国风新绎',
				image: '../../static/makedetail/style-1.png'
			},
			{
				name: '休闲自然',
				image: '../../static/makedetail/style-2.png'
			},
			{
				name: '西方魔法',
				image: '../../static/makedetail/style-3.png'
			},
			{
				name: '可爱甜蜜',
				image: '../../static/makedetail/style-4.png'
			} 
			],
			inQueue: false,//是否创作中
			queuing: false,//是否排队中
			queueMessage: '',
			myinfo: {},
			step: {
				name: "makeImgGuide",
				guideList: [
					{
						el: ".right",
						tips: "积分可在这里查看，每日签到可获得积分！",
						next: "知道了",
						// style: "width: 120px; left: 490rpx;"
					},
					{
						el: ".input-area",
						tips: "输入关键词，描述我想要的画面！",
						next: "知道了",
					},
					{
						el: ".action-section",
						tips: "选择或输入主体的行为动作！",
						next: "知道了",
					},
					{
						el: ".environment-section",
						tips: "选择或输入主体所处的环境场景",
						next: "知道了",
					},
					{
						el: ".image-section",
						tips: "选择或输入主体形象特征",
						next: "知道了",
					},
					{
						el: ".style-scroll",
						tips: "选择您喜欢的参考风格",
						next: "知道了",
					},
					{
						el: ".generate-btn",
						tips: "点击这里开始生成您的图片作品",
						next: "完成",
					}]
			}
		}
	},
	computed: {
		...mapState('switchingModule', ['isRecharge', 'isGuiding'])
	},
	onLoad(e) {
		// this.checkQueueStatus()
		this.getMyInfo();
		if (e.id) {
			this.getQueueDetail(e.id)
		}
	},
	methods: { 
		doYouWantToEdit() {
			return this.inQueue || this.queuing
		},
		state() {
			if (this.inQueue) {
				uni.showToast({
					title: '正在创作中无法修改',
					icon: 'none'
				})
			} else if (this.queuing) {
				uni.showToast({
					title: '正在排队中无法修改',
					icon: 'none'
				})
			}
		},
		goBack() {
			uni.navigateBack()
		},
		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/x-www-form-urlencoded',
					'sign': getApp().globalData.headerSign
				},
				data: {
					uuid: getApp().globalData.uuid,
					task_type: 1
				},
				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'
					});
				}
			})
		},
		clearDescription() {
			this.description = ''
			this.descriptionLength = 0
		},
		onDescriptionInput(e) {
			this.descriptionLength = e.detail.value.length
		},
		selectAction(tag) {
			this.action = tag
		},
		selectEnvironment(tag) {
			this.environment = tag
		},
		selectImage(tag) {
			this.image = tag
		},
		selectStyle(index) {
			this.selectedStyle = index
		},

		generateImage() {
			if (!this.description) {
				uni.showToast({
					title: '请输入创作描述',
					icon: 'none'
				})
				return
			}
			// if (this.selectedStyle === -1) {
			//   uni.showToast({
			//     title: '请选择参考风格',
			//     icon: 'none'
			//   })
			//   return
			// }
			let style = '';
			if (this.selectedStyle !== -1) {
				style = this.styleList[this.selectedStyle].name
			}

			let that = this
			uni.request({
				url: this.$apiHost + '/WorkAI/creatorLG',
				data: {
					uuid: getApp().globalData.uuid,
					description: this.description,
					action: this.action,
					environment: this.environment,
					subject: this.image,
					style: style
				},
				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") {
						// TODO: 处理生成成功后的逻辑
						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'
					});
				}
			})
		},
		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, progress, description, action, environment, environment, style } = res.data.data
						that.queuePosition = queuePosition
						that.allPosition = allPosition
						that.progress = progress
						that.description = description
						that.action = action
						that.environment = environment
						that.selectedStyle = that.styleList.findIndex(item => item.name == style)
						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 './makeImgDetail.scss';
</style>