<template>
	<view class="content">
		<text v-if="process_show" class="title">x胸腔图病症识别器</text>
		<text v-else style="color: #666;">{{timeString}}</text>
		<view class="history">
			<image @click="$util.navigateTo('/pages/img_process/img_process_history/img_process_history')" src="@/static/img/history_bmi.png"></image>
			<p style="text-align: center;" class="head-text">历史</p>
		</view>
		<uv-gap height="10"></uv-gap>
		<view v-if="process_show" class="flex justify-center" style="align-items: center; padding: 20px;">
			<view class="flex justify-between align-center">
				<uv-upload
					@oversize="tip()"
					maxSize=2097152
					:compressed='false'
					:fileList="fileList1" 
					name="1" 
					:maxCount="1" 
					@afterRead="afterRead"
					@delete="deletePic"
					:previewFullImage="true"
					width="100" 
					height="100">
				</uv-upload>
				
				<image v-if="img_url" class="arrow" src="/static/img/右箭头.png" mode="widthFix" style="background-color: #fff;"></image>
				<image v-if="img_url" :src="img_url" mode="widthFix"></image>
				
			</view>
		</view>
		
		<uv-gap v-if="process_show" height="10"></uv-gap>
		
		<view v-if="process_show" class="flex justify-center">
			<uv-button @click="processImg()" color="#1678ff" text="确定" customStyle="width:85vw" customTextStyle="font-weight: 1000;"></uv-button>
		</view>
		
		<uv-gap height="10"></uv-gap>
		
		<view v-if="resInfo">
			<view v-if="resInfo['code']">
				<h3 v-if="process_show" style="font-weight: 1000;color: #53c21d;">处理成功：</h3>
				
				<uv-gap height="5"></uv-gap>
				
				<view style="font-size: 16px;">
					<text style="color: #666;">识别结果：</text>
					<text style="color: #f56c6c;margin-right: 10px;" v-for="(diseaseValue, diseaseKey) in resInfo['data']['disease']" :key="diseaseKey">{{diseaseValue}}</text>
				</view>
				
				<uv-gap v-if="!process_show" height="20"></uv-gap>
				
				<uv-gap height="10"></uv-gap>
				
				<view class="diseaseItem" v-for="(diseaseValue, diseaseKey) in resInfo['data']['disease']" :key="diseaseKey">
				    <text>{{diseaseValue}}：</text>
					<view>
				        <text>饮食建议:</text>
				        <view v-for="(dietValue, dietKey) in resInfo['data'][diseaseValue]['饮食建议']" :key="dietKey">
				            <text>{{dietValue}}</text>
				        </view>
				    </view>
				    <view>
				        <text>锻炼建议:</text>
				        <view v-for="(exerciseValue, exerciseKey) in resInfo['data'][diseaseValue]['锻炼建议']" :key="exerciseKey">
				            <text>{{exerciseValue}}</text>
				        </view>
				    </view>
				    <view>
				        <text>睡眠建议:</text>
				        <view v-for="(sleepValue, sleepKey) in resInfo['data'][diseaseValue]['睡眠建议']" :key="sleepKey">
				            <text>{{sleepValue}}</text>
				        </view>
				    </view>
				    <view>
				        <text>用药建议:</text>
				        <view v-for="(medicationValue, medicationKey) in resInfo['data'][diseaseValue]['用药建议']" :key="medicationKey">
				            <text>{{medicationValue}}</text>
				        </view>
				    </view>
				</view>
				
				<view class="aiSuggest" v-if="aiSuggest">
					<text>AI 建议</text>
					<view>
						<text>{{aiSuggest}}</text>
					</view>
				</view>
				<view v-else class="aiSuggest button-all center" style="height: 50vw;" @click="getAiSuggest">获得ai建议</view>
				<uv-gap height="30"></uv-gap>
				<uv-divider text="我是有底线的"></uv-divider>
				<uv-gap height="30"></uv-gap>
			</view>
			<view v-if="!resInfo['code']">
				<p style="color: #f56c6c; font-size: 18px;">处理失败</p>
			</view>
		</view>
	</view>
</template>

<script>
	import img_api from '@/data/img_api';
	import send_message_ai from "@/data/medical_ai.js"
	import disease_suggest from '@/static/disease_suggest.js'
	
	export default {
		onLoad(options) {
			// 获取传递的对象参数，使用decodeURIComponent解码，并转为对象
			if ('timestamp' in options) {
				this.process_show = false;
				
				let timestamp = JSON.parse(decodeURIComponent(options.timestamp));
				this.timestamp = timestamp;
				console.log('timestamp: ',timestamp);
				
				let img_process_history = uni.getStorageSync('img_process_history');
				
				let img_process = img_process_history[timestamp];
				let resInfo = {code: 1, data: {disease: img_process['disease']}};
				
				for (let disease of img_process['disease']) {
					resInfo['data'][disease] = disease_suggest[disease];
				}
				this.resInfo = resInfo;
				
				this.timeString = img_process['time_string'];
				
				if(img_process['ai_suggest']) this.aiSuggest = img_process['ai_suggest'];
				
			}
		},
		data() {
			return {
				process_show: true,
				uploading: false,
				style:null,
				fileList1: [],
				resInfo: null,
				img_url: null,
				request: 1,
				aiSuggest: null,
				timestamp: null,
				timeString: null
			}
		},
		methods: {
			getAiSuggest(){
				let disease = '';
				for (let value of this.resInfo['data']['disease']) disease += '、' + value;
				
				// 去掉第一个多余的 "、"
				disease = disease.substring(1);
				
				const content = '通过x胸腔图，已知患者有' + disease + "症状，请给出一些建议";
				console.log('content: ',content);
				
				if(this.request == 0){
					uni.showToast({duration:1000,icon:'none',title: '消息发送中，请稍等...'});
					setTimeout(() => uni.showLoading({title:'正在发送...'}), 1500);
					return ;
				}
				
				this.request = 0;
				uni.showLoading({title:'正在发送...'});
				
				send_message_ai(content).then(res => {
					console.log('send: res: ',res);
					this.aiSuggest = res;
					uni.hideLoading();
					this.request = 1;
					
					let img_process_history = uni.getStorageSync('img_process_history');
					img_process_history[this.timestamp]['ai_suggest'] = res;
					uni.setStorageSync('img_process_history', img_process_history);
				}).catch(err => {
					console.log('send: err: ',err);
					uni.hideLoading();
					uni.showToast({duration:1500,icon:'error',title: '获得失败'});
					this.request = 1;
				});
			},
			// 删除图片
			deletePic(event) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这个照片吗？',
					cancelText: '再看看',
					confirmText: '删除',
					success: res => {
						if (res.confirm) {
							this[`fileList${event.name}`].splice(event.index, 1)
						}
					}
				})
			}, 
			// 新增图片
			async 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 = '';
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++;
				}
			},
			tip(){
				uni.showToast({
					icon:"error",
					title: '图片不能超过2M',
				})
			},
			processImg() {
				if(!this.request){
					uni.showToast({
						icon:"none",
						title: '图片处理中，请稍后...',
					});
				}
				else if(!this.fileList1.length){
					uni.showToast({
						icon:"error",
						title: '请选择图片',
					})
				}
				else{
					this.request = 0;
					uni.showLoading({title: '图片处理中...'});
					img_api(this.fileList1[0]['thumb']).then(res => {
						console.info('processImg: res: ',res);
						this.request = 1;
						this.resInfo = res;
						this.img_url = 'data:image/png;base64,' + res['data']['image'];
						uni.hideLoading();
						uni.showToast({icon:'success',title: '处理成功',duration:1500});
						
						let img_process_history = uni.getStorageSync('img_process_history');
						const timestamp = Date.now();
						this.timestamp = timestamp;
						
						if(!img_process_history || Object.keys(img_process_history).length === 0) img_process_history = {};
						
						img_process_history[timestamp] = {disease: res['data']['disease'], time_string: this.$util.formatDateTime(timestamp)};
						
						uni.setStorageSync('img_process_history', img_process_history);
						
					}).catch(err => {
						this.request = 1;
						this.resInfo = err;
						
						console.error('processImg: err: ',err);
						uni.hideLoading();
						if(err === 'img_api: 没有token') uni.showToast({icon:'error',title: '未登陆',duration:1500});
						else uni.showToast({icon:'error',title: '处理失败',duration:1500});
					});
				}
			}
		}
	}
</script>

<style lang="less">
	image{
		height: 100px;
		width: 100px;
		background-color: #fff;
	}
	.history{
		position: fixed;
		top: 10px;
		right: 20px;
		background-color: rgba(0, 0, 0, 0);
		font-size: 12px;
		color: #666;
		
		image{
			width: 35px;
			height: 35px;
			background-color: rgba(0, 0, 0, 0);
		}
	}
	.history:active{
		opacity: 0.6;
	}
	.content{
		padding:20px;
	}
	.arrow{
		height: 30px;
		width: 30px;
		margin: 20px;
	}
	.title{
		color: #777;
		font-size: 20px;
		font-weight: 600;
	}
	.diseaseItem{
		background-color: #f1f3f2;
		border-radius: 30px;
		padding: 20px;
		color: #333;
		letter-spacing: 1px;
		margin-bottom: 20px;
		
		> text{
			color: #000;
			font-size: 18px;
			font-weight: 600;
		}
		
		> view{
			border-radius: 20px;
			margin: 15px 0 5px;
			background-color: #ffffff;
			border-radius: 20px;
			padding: 15px;
			
			> text{
				font-size: 16px;
				color: #222;
			}
			view{
				padding: 1px 0;
				text{
					font-size: 15px;
				}
			}
		}
	}
	
	.aiSuggest{
		background-color: #f1f3f2;
		border: none;
		border-radius: 30px;
		padding: 20px;
		letter-spacing: 1px;
		margin-bottom: 20px;
		font-weight: 1000;
		color: #666;
		font-size: 28px;
		
		> text{
			color: #000;
			font-size: 18px;
			font-weight: 600;
		}
		
		> view{
			border-radius: 20px;
			margin: 10px 0;
			background-color: #ffffff;
			border-radius: 20px;
			padding: 15px;
			
			> text{
				font-size: 15px;
			}
		}
	}
</style>