<template>
	<view class="outerBox">
		<navBar title="首页" flex="cen" :navImg="navImg" :back="false" color="#333333" background="#FFFFFF" />
		<view class="upload">

			<view class="currModel" @click="show = true">
				<view class="left" v-if="currModalCon">
					当前模型：{{currModalCon.type+'-'+currModalCon.name}}
				</view>
				<view class="right" v-if="currModalCon">
				</view>
			</view>
			<view class="tipTxt">
				请按要求点击上传您的照片(至少5张)
			</view>
			<u-upload style="margin-top: 20px;" :fileList="fileList1" @afterRead="afterRead" @delete="deletePic"
				name="1" multiple :maxCount="20"></u-upload>
		</view>
		<view class="content">
			<u-divider text="照片示例"></u-divider>
			<view class="examplePic">
				<view class="item" v-for="(item,index) in exampleList" @click="previewImg(exampleList, index)">
					<image class="imagesRow" :src="item.url" mode="widthFix"></image>
					<u-icon :name="index==0?'checkmark':'close'" :label="item.text" labelPos="top" labelSize="12px"
						style="" color="#febb2b" size="18"></u-icon>
				</view>
			</view>
			<view class="botTipTxtBox">
				<u--text color="#aeaeae" size="12px" align="center" text="温馨提醒：目前婴儿、老人、眼镜等特征效果有不稳定性，我们正在努力优化"></u--text>
			</view>
			<view class="btnBox" v-if="isGen" style="display: flex;justify-content: space-between;margin-top: 20px;">
				<view class="btn b1" v-if="fileListUp.length!==0&&showGenBtn" @click="createRenwu()">
					立即生成
				</view>
				<view class="btn b2" v-else @click="reCreate">
					重新上传
				</view>
			</view>
		</view>



		<u-popup :show="show" @close="close" @open="open" :round="10">
			<view class="modelBox">

				<view class="mName">
					<view class="left">
						模型选择：
					</view>
					<u-icon @click="show=false" name="close" color="black" size="20" />

				</view>
				<view class="top1">
					<u-subsection fontSize="16" activeColor="orange" :list="manList" :current="current"
						@change="sectionChange"></u-subsection>
				</view>

				<view class="bot1" v-if="current==0">
					<view class="item1" :class="[manCurrIndex==index?'at':'']" v-for="(item,index) in styles.man"
						@click="selM(0,index,item)">
						{{item.name}}
					</view>

					<!-- 	<view class="item1" :class="[manCurrIndex==index?'at':'']" v-for="(item,index) in 20"
						@click="selM(0,index,item)">
						{{item}}
					</view> -->
					<view class="pos">
					</view>
				</view>
				<view class="bot1" v-else>
					<view class="item1" :class="[womanCurrIndex==index?'at':'']" v-for="(item,index) in styles.woman"
						@click="selM(1,index,item)">
						{{item.name}}
					</view>
					<view class="pos">
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		buildPic,
		getImage,
		getAiModel,
		// pushFile
		createTask,


	} from '@/api/genPic/index.js'
	import genAvatarCom from '@/components/genAvatarComp/index.vue'
	export default {
		components: {
			genAvatarCom
		},
		data() {
			return {
				exampleList: [{
						text: '五官清晰',
						url: require('@/static/images/WX20231024-110939.png')
					},
					{
						text: '不是正面',
						url: require('@/static/images/20231024-110955.png')
					},
					{
						text: '有遮挡',
						url: require('@/static/images/20231024-111008.png')
					},
					{
						text: '过于模糊',
						url: require('@/static/images/20231024-111021.png')
					},
				],

				show: false,

				userInfo: uni.getStorageSync('userInfo'),

				value: 0,
				is_show: false,
				fileList1: [],

				stepUrl: '',
				isGen: false,
				showGenBtn: true,

				fileListUp: [],
				aiPath: '',
				styles: {},
				manList: [],
				current: 0,

				manCurrIndex: 0,
				womanCurrIndex: -1,

				currModalCon: null
			}
		},
		async onLoad() {
			this.getAiPath()

			let res = await getAiModel({
				type: 2
			})
			if (res.code == 0) {

				this.styles = res.data.styles

				this.manList = Object.keys(res.data.styles)

				this.currModalCon = {
					type: this.manList[0],
					name: res.data.styles[this.manList[0]][0].name,
					index: res.data.styles[this.manList[0]][0].index
				}
				console.log('ai模型列表返回值：', res, this.styles, this.currModalCon);
			} else {
				uni.showToast({
					title: res.message,
					icon: "none"
				})
			}
		},

		onShareAppMessage(params) {
			if (params.from === 'button' || params.from === 'menu') {
				return {
					title: '思维定制相机-首页',
					imageUrl: '',
					path: '/pages/index/index',
					mpId: this.$appId,
					type: this.$shareType,
				}
			}
		},
		watch: {
			fileListUp(n, o) {
				let len = n.filter((item, index) => {
					return item == 'success'
				})

				// console.log('len----', n, len.length);

				if (len.length >= 5) {
					this.isGen = true
					this.showGenBtn = true
				} else {
					this.isGen = false
					this.showGenBtn = false
				}
			}
		},
		methods: {
			//点击预览图片
			previewImg(list, index) {
				let listr = []

				list.forEach((item, index) => {
					listr.push(item.url)
				})

				console.log('listr', listr);
				uni.previewImage({
					current: index,
					urls: listr, //存放图片的数组
					// urls: ["/static/images/WX20231024-110939.png", "/static/images/20231024-110955.png"],
					loop: true,
					indicator: 'default'
				})
			},

			selM(type, index, item) {
				if (type == 0) {
					this.manCurrIndex = index
					this.womanCurrIndex = -1
				} else {
					this.womanCurrIndex = index
					this.manCurrIndex = -1

				}

				this.currModalCon = {
					type: type ? 'woman' : 'man',
					name: item.name,
					index: index
				}

				console.log('当前选择的模型', type, index, item, this.currModalCon);

			},
			sectionChange(index) {
				this.current = index;
			},
			open() {

			},
			close() {
				this.show = false

			},

			testUp() {
				uni.switchTab({
					url: '/pages/main/index'
				})
			},

			async getAiPath() {
				let res = await getAiModel({
					type: 3
				})
				if (res.code == 0) {
					console.log('ai模型返回值：', res.data.data_path);
					this.aiPath = res.data.data_path

				} else {
					uni.showToast({
						title: '远程文件夹创建失败',
						icon: "none"
					})
				}
			},
			toGenPic() {
				uni.switchTab({
					url: '/pages/selAndGenPage/index'
				})
			},
			toMyPage() {
				uni.switchTab({
					url: '/pages/main/index'
				})
			},
			// 删除图片
			deletePic(event) {

				console.log('del', event);
				this[`fileList${event.name}`].splice(event.index, 1)
				this.fileListUp.splice(event.index, 1)
				console.log('1213', this.fileListUp);
			},
			// 新增图片
			async afterRead(event) {
				if (!uni.getStorageSync('token')) {
					this.$toast('请登录后上传')
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/main/index'
						})
					}, 1500)
					return
				}

				console.log('afterRead------:', event);
				if (this.aiPath) {
					// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
					let lists = [].concat(event.file)
					let fileListLen = this[`fileList${event.name}`].length
					lists.map((item) => {
						this[`fileList${event.name}`].push({
							...item,
							status: 'uploading',
							message: '上传中'
						})
					})
					for (let i = 0; i < lists.length; i++) {

						const result = await this.uploadFilePromise(lists[i].url)

						console.log('result------', result);

						let item = this[`fileList${event.name}`][fileListLen]
						this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
							// status: 'success',
							status: result.type,
							message: '',
							url: result.data,
							errTxt: result.errTxt ? result.errTxt : ""
						}))
						fileListLen++
					}
				}
			},

			async uploadFilePromise(url) {

				let _this = this
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: _this.$baseUrl + '/api/checkAndUploadImg', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						header: {
							Authorization: uni.getStorageSync('token'),
						},
						formData: {
							user: 'test',
							'tag': 'lamp',
							pathId: _this.aiPath,
						},
						success: (res) => {
							let result = JSON.parse(res.data)
							console.log('上传并校验图片返回值：', res);
							// console.log('res.data.data1：', res.data.data);

							if (result.code == 0) {
								if (!result.data.img_path) {
									// _this.fileList1.pop()
									_this.$toast('图片不符合标准，请检查后重新上传')
									_this.fileListUp.push('failed')
									setTimeout(() => {
										resolve({
											data: res.data.data,
											type: 'failed',
											errTxt: result.data.data[0].msg
										})
									}, 1000)
								} else {
									_this.fileListUp.push('success')
									setTimeout(() => {
										resolve({
											data: res.data.data,
											type: 'success'
										})
									}, 1000)
								}
							}
						}
					});
				})
			},

			async createRenwu() {
				if (this.fileListUp.length < 5) {
					return uni.showToast({
						title: '请上传5张图片以上',
						icon: 'none'
					})
				}
				uni.showLoading({
					title: '任务创建中...'
				})
				let _this = this
				console.log('创建任务参数：', {
					pathId: this.aiPath,
					cate: this.currModalCon.type,
					model_index: this.currModalCon.index,
					// -2返回20张
					output_level: '-2'
				});
				let res = await createTask({
					pathId: this.aiPath,
					// cate: 'man',
					// model_index: 0,
					cate: this.currModalCon.type,
					model_index: this.currModalCon.index,
					// -2返回20张
					output_level: '-2'
				})

				console.log('创建任务返回值：', res);
				if (res.code == 0 && res.data.task_id) {
					this.$toast('任务创建成功')

					this.showGenBtn = false
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/my/index'
						})
					}, 1500)
				}
			},

			async reCreate() {
				this.fileListUp = []
				this.fileList1 = []
				this.isGen = false

				this.getAiPath()
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import "./index.scss";
</style>