<template>
	<view class="camera-container">
		<u-navbar :custom-back="btnback" :is-back="true" title='识图' title-color="#000" :border-bottom="false"
			:background="bgc" id="navbar">
		</u-navbar>

		<camera :device-position="cameraPosition" flash="off" :show-button="false" @error="handleCameraError"
			style="height: 70vh;"></camera>
		<view class="mask" v-if="maskpic">
			<image :src="maskpic" mode=""></image>
		</view>
		<text class="wz">请将你要识别的植物置于镜头范围内</text>
		<view class="zujbox">
			<view class="xc" @click="uploadPictrue">
				<image src="https://api.ccttiot.com/smartmeter/img/static/u3PADZHrrztQlEo818kp" mode=""></image>
			</view>
			<view class="pz" @click="photo">
				<image src="https://api.ccttiot.com/smartmeter/img/static/u6FYMnTIGvUbImJHZy8c"></image>
			</view>
			<view class="qieh" @click="switchCamera">
				<image src="https://api.ccttiot.com/smartmeter/img/static/udoIFL8o1xO0dH7ZfFSl" mode=""></image>
			</view>
		</view>

		<view>
			<!-- #ifdef MP-WEIXIN -->
			<ws-wx-privacy id="privacy-popup"></ws-wx-privacy>
			<!-- #endif -->
		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				cameraPosition: 'back', // 初始摄像头位置为后置
				src: "",
				photoUrl: "",
				tempFilePathpic: '',
				zwlist: [],
				token: '',
				userid: '',
				picdomain: '',
				maskpic: ''
			}
		},
		// 分享到好友（会话）
		onShareAppMessage: function() {
			return {
				title: '绿小能',
				path: '/pages/index/index'
			}
		},
		
		// 分享到朋友圈  
		onShareTimeline: function() {
			return {
				title: '绿小能',
				query: '',
				path: '/pages/index/index'
			}
		},
		onLoad() {
			this.gettiken()
			this.getinfo()
		},
		onShow() {
			this.maskpic = ''
		},
		onUnload(){
			uni.switchTab({
				url:'/pages/index/index'
			})
		},
		methods: {
			// 获取用户信息
			getinfo() {
				this.$u.get(`/appVerify/profile`).then((res) => {
					if (res.code == 200) {
						this.userid = res.data.userId
					}
				})
			},

			btnback() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			},
            // 点击拍照
			photo() {
				let that = this
				const cameraContext = uni.createCameraContext();
				cameraContext.takePhoto({
					quality: 'high',
					success: (res) => {
						console.log(res);
						const tempFilePath = res.tempImagePath;
						that.maskpic = res.tempImagePath
						that.tempFilePathpic = res.tempImagePath
						uni.showLoading({
							title: '正在识别...'
						});
						uni.uploadFile({
							url: 'https://up-z2.qiniup.com', // 上传图片的接口地址
							filePath: tempFilePath, //所要上传的图片地址
							name: 'file', //所要上传的文件类型
							header: {
								accept: 'application/json'
							},
							formData: {
								token: that.token,
							},
							success: (res) => { //成功的回调函数
								let urlpic = that.picdomain + '/' + JSON.parse(res.data).key
								// 识别植物的请求参数
								let data = {
									url:urlpic,
									userId:that.userid
								}
								that.$u.get(`/app/plant/identify`,data).then((res) => {
										if (res.code == 200) {
											that.zwlist = res.data
											uni.hideLoading()
											// 跳转到植物列表
											uni.navigateTo({
												url: '/page_user/photolist?list=' + JSON.stringify(that.zwlist) + '&cart=' + JSON.stringify(that.tempFilePathpic)
											})
										} else {
											uni.showToast({
												title: '网络波动异常，请重新识别',
												icon: 'none',
												duration: 1000
											})
										}
									})
							}
						})
					}
				})
			},

			handleCameraError(e) {
				console.error('相机出错：', e.detail);
				// 处理相机错误情况  
			},
			switchCamera() {
				this.cameraPosition = this.cameraPosition == 'back' ? 'front' : 'back'; // 切换摄像头位置  
			},
            // 从相册选择图
			uploadPictrue() {
				let that = this
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album'],
					success: function(res) {
						// 获取上传的图片路径
						const tempFilePath = res.tempFiles[0].path
						that.tempFilePathpic = res.tempFiles[0].path
						uni.showLoading({
							title: '正在识别...'
						});
						uni.uploadFile({
							url: 'https://up-z2.qiniup.com', // 上传图片的接口地址
							filePath: tempFilePath, //所要上传的图片地址
							name: 'file', //所要上传的文件类型
							header: {
								accept: 'application/json'
							},
							formData: {
								token: that.token,
							},
							success: (res) => {
								let urlpic = that.picdomain + '/' + JSON.parse(res.data).key
								let data = {
									url:urlpic,
									userId:that.userid
								}
								that.$u.get(`/app/plant/identify`,data).then((res) => {
										if (res.code == 200) {
											that.zwlist = res.data
											uni.hideLoading()
											// 跳转到植物列表
											uni.navigateTo({
												url: '/page_user/photolist?list=' + JSON.stringify(that.zwlist) + '&cart=' + JSON.stringify(that.tempFilePathpic)
											})
										} else {
											uni.showToast({
												title: '网络波动异常，请重新识别',
												icon: 'none',
												duration: 1000
											})
										}
									})
							 }
						})
					}
				})
			},

            // 获取七牛云token
			gettiken() {
				this.$u.get("/common/qiniu/uploadInfo").then(res => {
					this.token = res.token
					this.picdomain = res.domain
				})
			},


		}
	};
</script>

<style lang="scss">
	/deep/ .u-title {
		margin-bottom: 22rpx;
	}

	/deep/ .uicon-nav-back {
		margin-bottom: 22rpx;
	}

	.mask {
		width: 100%;
		height: 82vh;
		position: absolute;
		top: 0;
		left: 0;
		z-index: 99;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.xc {
		image {
			width: 92rpx;
			height: 92rpx;
		}
	}

	.zujbox {
		margin-top: 62rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 92rpx;
		box-sizing: border-box;
	}

	.pz {
		image {
			width: 104rpx;
			height: 104rpx;
		}
	}

	.qieh {
		image {
			width: 92rpx;
			height: 92rpx;
		}
	}

	.wz {
		display: block;
		margin-top: 20rpx;
		width: 100%;
		text-align: center;
		color: #999;
	}

	.camera-container {
		position: fixed;
		width: 100%;
		height: 100vh;
		/* 设置相机预览区域的高度 */
		overflow: hidden;
	}
</style>