<template>
	<view class="content">
		<view class="upload">
			<view class="tipTxt">
				请按要求点击上传您的照片
			</view>
			<u-upload :deletable="showDelBtn" style="margin-top: 20px;" :fileList="fileList1" @afterRead="afterRead"
				@delete="deletePic" name="1" :maxCount="1" width="290" height="290"></u-upload>
		</view>


		<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="tipTxtBox">
			<u--text color="#aeaeae" size="12px" align="center" text="温馨提醒：目前婴儿、老人、眼镜等特征效果有不稳定性，我们正在努力优化"></u--text>
		</view>
		<!-- <view v-if="is_show" style="margin-top: 40px;"><u-button class="buttonCalss" type="warning" shape="circle"
				size="large" text="制作数字人分身" @click="buildPicTrue()"></u-button></view> -->

		<!-- <view class="" style="display: flex;justify-content: space-between;margin-top: 20px;">
			<button type="warn" style="" @click="reset">重新上传</button>
			<button type="primary" style="" @click="buildPicTrue()">生成图片</button>
		</view> -->

		<view class="btnBox" v-if="isGen" style="display: flex;justify-content: space-between;margin-top: 20px;">
			<view class="btn b1" v-if="stepUrl!==''&&showGenBtn" @click="buildPicTrue()">
				立即生成
			</view>
			<view class="btn b2" v-else @click="reset">
				重新上传
			</view>
		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				userInfo: uni.getStorageSync('userInfo'),

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

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

				fileListUp: [],
				aiPath: '',

				showDelBtn: true,

				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')
					},
				],
			}
		},
		onLoad() {

		},
		watch: {
			stepUrl(n, o) {
				if (n != '') {
					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'
				})
			},

			reset() {
				this.stepUrl = ''
				this.fileList1 = []
				this.isGen = false

				this.showDelBtn = true
			},
			change() {

			},
			click() {

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

				console.log('afterRead------:', event);
				// 当设置 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)
					// const result = await this.uploadFilePromise(lists[i])

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

			async uploadFilePromise(url) {

				let _this = this
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: _this.$baseUrl + '/api/attachments', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						header: {
							Authorization: uni.getStorageSync('token'),
						},
						formData: {
							// user: 'test',
							'tag': 'camera',
							// pathId: _this.aiPath,
						},
						success: (res) => {
							let result = JSON.parse(res.data)

							if (result.code == 0) {
								// _this.fileListUp.push(result.data.data)

								_this.stepUrl = result.data.file
								console.log('上传并校验图片返回值--头像：', _this.stepUrl);
								setTimeout(() => {
									resolve(res.data.data)
								}, 1000)
							}
						}
					});
				})
			},

			buildPicTrue() {
				if (!this.stepUrl) {
					return uni.showToast({
						title: '请上传图片',
						icon: 'none'
					})
				}
				uni.showLoading({
					title: '生成中...'
				})
				let _this = this
				uni.request({
					url: _this.$baseUrl + '/api/buildPicTrue', // 接口地址
					method: 'POST', // 请求方法，可以是 GET、POST 等
					data: {
						pathPictrue: this.stepUrl,
					},
					header: {
						Authorization: uni.getStorageSync('token'),
					},
					success: function(res) {
						uni.request({
							url: _this.$baseUrl + "/api/getImage",
							method: 'POST',
							data: {
								file_name: res.data.data.result,
							},
							header: {
								Authorization: uni.getStorageSync('token'),
							},
							success: function(res) {
								_this.showDelBtn = false
								// _this.stepUrl = ''
								_this.showGenBtn = false
								console.log(res)
								console.log('制作商城的图片地址：', res.data.data.url)
								_this.fileList1 = [{
									// url: 'http://mall.wangkuncheng.cn/upload/lamp/20231031/d8c96316c879464cae5f677824e0ac4d.jpg'
									url: res.data.data.url
								}]
								uni.hideLoading()
							}

						})
						// 请求成功时的回调函数
						console.log('请求成功', res.data);
						// 在这里处理接口返回的数据
					},
					fail: function(res) {
						// 请求失败时的回调函数
						console.log('请求失败', res);
						// 在这里处理请求失败的情况
					},
					complete: function() {
						// 请求完成时的回调函数，无论成功或失败都会执行
						console.log('请求完成');
					}
				});
			}
		}
	}
</script>
<style lang="scss" scoped>
	@import "./index.scss";
</style>