<template>
	<div class="robot Guide_1_1_1" :class="[driver__.driver?'showEvents':'']" @mousemove="robotmax">
		<div class="robot_top" ref="robotDom" v-fade="robotTop,'block'">
			<div :class="[item.state == 1?'text_right':'text_left',item.img?'white':'']" v-for="item,index in record" ref="robotChildDom">
				<div class="robot_text">
					<span v-if="!driver__.driver">
						{{item.str}}
						<a v-if="item.src" :href="item.src" target="_blank"><i class="fi fi-br-link-alt"></i></a>
					</span>
					<span class="driver__" v-if="driver__.driver">
						{{item.str}}
					</span>
					<div class="driver__btn" v-if="item.driver">
						<span @click="setDriver(index)">
							Yes
						</span>
						<span @click="removeDriver(index)">
							No
						</span>
					</div>
					<div class="robot_img" :class="[item.img ?'img':'']">
						<div class="robot_img_item" v-for="imgItem,imgIndex in item.img">
							<img :src="imgItem.presignedUrl" alt="">					
							<div
								class="delete_like_file_block"
							>
								<i v-if="imgItem.id == null" class="fi fi-rr-heart" @click.stop="likeFile(imgItem,imgIndex,index)"></i>
								<i v-else class="fi fi-sr-heart" @click.stop="likeFile(imgItem,imgIndex,index)"></i>
							</div>
							<div class="delete_like_file_block left"  :class="[driver__.driver?'hideEvents':'']">
								<i class="fi fi-bs-expand-arrows-alt" @click.stop="scaleImage(item.img)"></i>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<div class="robot_content">
			<div :style="'width:'+bloodBars+'%;'"></div>
		</div>
		<div class="robot_bottom">
			<div class="robot_input" v-fade="robotInput,'flex'">
				<input
					:placeholder="$t('RobotAssist.inputContent1')"
					v-model="chatCentent"
					@keydown.enter="roborSend()"
					@input="robotmax"
				/>
				<div class="robot_btn">
					<i class="fi fi-ss-paper-plane-top" @click="roborSend"></i>
				</div>
				
			</div>
			<div class="robot_img">
				<img src="@/assets/images/homePage/robot.png" @click="robotBtn">
			</div>
		</div>
		<scaleImage ref="scaleImage"></scaleImage>
	</div>
</template>
<script lang="ts">
import { defineComponent, createVNode,computed, ref,Ref} from "vue";
import { UserOutlined, DownOutlined } from "@ant-design/icons-vue";
import { Https } from "@/tool/https";
import { getCookie,setCookie } from "@/tool/cookie";
import { useStore } from "vuex";
import { message } from "ant-design-vue";
import { openGuide,driverObj__,setDestroy } from "@/tool/guide";
import scaleImage from "@/component/HomePage/scaleImage.vue";
import { useI18n } from "vue-i18n";
export default defineComponent({
    components: {
        DownOutlined,
        UserOutlined,
		scaleImage,
    },
	setup() {
		const robotDom = ref<HTMLElement | null>(null);
		const robotChildDom = ref<HTMLElement | null>(null);
		let chatCentent = ref<string>('');
		const robotTop = ref(false)
		const robotInput = ref(false)
        let timeTop:any =  0;
        let timeInput:any =  0;
		let record:any = ref([
			
		])
		const userInfo:any =  {}
		let bloodBars:any = ref(0)
		let {t} = useI18n()
		let isTest = ref()
		let store = useStore()
		let workspace:any = ref({})
		let driver__:any = computed(()=>{
			return store.state.Guide.guide
		})
		let driver__Time:any = ref()
		return {
		robotTop,
		robotInput,
		chatCentent,
		record,
		robotDom,
		robotChildDom,
		timeTop,
		timeInput,
		userInfo,
		bloodBars,
		t,
		isTest,
		store,
		workspace,
		driver__,
		driver__Time
		};
	},
    data() {
        return {
        };
    },
	watch:{
		driver__:{
			handler: function(newval) {
				if(this.driver__.driver && this.driver__.index == 0){
					this.robotTop = true
					this.robotInput = true
					driverObj__.refresh();
					this.record.push({
						state:1,
						str:"Welcome to AiDA. I am your friendly fashion design assistant. If you have any questions or need assistance, please don't hesitate to ask. ",
						driver:false,
					})
					this.textScroll()
					setTimeout(() => {
						this.record.push({
							state:1,
							str:"I see you might be new here, and I'd love to guide you through a tutorial to help you get acquainted with our new and improved AiDA system. Would you like to start the tutorial now?",
							driver:true,
						})
						this.textScroll()
					}, 1000);
				
					this.driver__Time = setInterval(() => {
						this.$nextTick().then(()=>{
							driverObj__.refresh();
						})
						this.createTimer()
					}, 3000);

				}else{
					clearTimeout(this.driver__Time)
				}
				if(!newval.driver && this.driver__.index != 0){
					this.record.push({
						state:1,
						str:"You can start the tutorial at any time by simply telling me that you want to. ",
						driver:false,
					})
					clearTimeout(this.driver__Time)
				}
			}
		}
	},
    mounted() {
		this.textScroll()
		let userInfo:any = getCookie("userInfo")
        let isTest:any = getCookie('isTest')
        this.isTest =JSON.parse(isTest)|| ''
        this.userInfo = JSON.parse(userInfo);
		if (sessionStorage.getItem("record") == null) {
			this.record = []
		}else{
			this.record = JSON.parse(sessionStorage.getItem("record") as string)
		}
		this.getBloodBars()
		this.workspace = computed(()=>{
			return  this.store?.state?.Workspace?.workspace
		})
		
		
	},
	directives:{
		fade:{
			updated (el,oldVal){
				if(oldVal.value){
					el.style.display = oldVal.arg
					setTimeout(() => {
						el.classList.add("active")
					}, 100);
				}else{
					el.classList.remove("active")
					setTimeout(() => {
					el.style.display="none"
					}, 100);
				}
			}
		}
	},
    methods: {
		robotBtn(){
			if(!this.robotTop||!this.robotInput){
				this.robotTop = true
				this.robotInput = true
				
			}else{
				this.robotTop = false
				this.robotInput = false
			}
			// let noRefresh = false;
            // this.$router.push({ name: 'library', params: { noRefresh: false } });
			this.textScroll()//聊天定位到最低部
			this.createTimer()
		},
		getBloodBars(){
			Https.axiosGet(Https.httpUrls.getBloodBars,{params:{userId:this?.userInfo?.userId}}).then((rv: any) => {
				if (rv) {
					this.bloodBars = rv*100
				}
			})
		},
		textScroll(){
			this.$nextTick(()=>{
				if(this.robotDom && this.robotChildDom){
					// const items = this.robotChildDom._rawValue
					let num = 0
					for (let index = 0; index < (this.$refs.robotChildDom as any).length; index++) {
						const height = (this.$refs.robotChildDom as any)[index].clientHeight;
						num = num+40+height
					}
					this.robotDom.scrollTop = num
				}
			})
		},
		scaleImage(img){
			let scaleImage:any = this.$refs.scaleImage
			img.forEach((item:any) => {
				item.imgUrl = item.presignedUrl
			});
			scaleImage.init(img)
			scaleImage.scaleImageMask = true
		},
		robotmax(){//点击内容就设置为true显示 重置定时器
			this.createTimer()
		},
		roborSend (){
			this.clearTimer()
			if(!this.chatCentent){
                message.info(this.t('RobotAssist.jsContent1'));
				return
			}
			this.record.push({
				state:2,
				str:this.chatCentent
			})
			this.textScroll()
			let sessionId
			if(sessionStorage.getItem("sessionId") == null){
				let randomNum:any = Math.floor(Math.random() * 9000000000000000) + 1000000000000000;
				sessionStorage.setItem('sessionId', randomNum);  
				sessionId = randomNum
			}else{
				sessionId = sessionStorage.getItem("sessionId")
			}
		// sessionStorage.setItem('username', '23123123123');  
		// sessionStorage.getItem("username")  
		// sessionStorage.removeItem
			let a = true
			let data = {
				"user_id" : this.userInfo?.userId,
				"session_id":sessionId,
				"message" : this.chatCentent,
				gender:this.workspace.sexEnum.name,
			}
			let interaction = {onDownloadProgress: (progressEvent:any) => {
					this.clearTimer()
					// console.log(progressEvent.event.currentTarget.response);
				//   if(a){
				// 	this.record.push({
				// 		state:1,
				// 		str:progressEvent.event.currentTarget.response
				// 	})
				// 	a = false
				//   }else{
				// 	this.record[this.record.length].str = progressEvent.event.currentTarget.response
				//   }
                },
            }
			if(this.isTest){//试用用户禁止使用
				// message.warning(
				// 	this.t('isTest.available')
				// 	);
				this.record.push({
					state:1,
					str:this.t('isTest.src'),
					src:'https://code-create.com.hk/aida/'
				})
				this.createTimer()
				this.textScroll()
				this.chatCentent = ""
				return
			}
			Https.axiosPost(Https.httpUrls.chatStreamTest, data).then(
			// Https.axiosPost(Https.httpUrls.pythonChatStream, data,interaction).then(
                (rv) => {
					
					if(rv){
						if(rv.isTutorial){
							this.record.push({
								state:1,
								str:"We need to refresh the page before starting the tutorial. Would you like to start the tutorial now?",
								driver:true,
							})
						}else{
							if(rv.chatRobotLibraryList != null){
								this.record.push({
									state:1,
									img:rv.chatRobotLibraryList
								})
							}else{
								this.record.push({
									state:1,
									str:rv.output,
								})
							}
						}
						
						sessionStorage.setItem('record', JSON.stringify(this.record));  
						this.createTimer()
						this.textScroll()
						this.getBloodBars()
						// if(rv.isTutorial){
						// 	window.location.reload()
						// 	setCookie("isBeginner", true);
						// }
					}
                }
            ).catch(res=>{
            });
			this.chatCentent = ""
		},
		setDriver(index:number){
			if(this.driver__.driver){
				driverObj__.moveNext();
				this.robotTop = false
				this.robotInput = false
			}else{
				window.location.reload()
				setCookie("isBeginner", true);
				setCookie("isBeginnerNum", 1);
			}
			this.record[index].driver = false
			sessionStorage.setItem('record', JSON.stringify(this.record));  
			this.textScroll()
		},
		removeDriver(index:number){
			// let data = {
			// 	index : 0,
			// 	driver : false,
			// }
			// this.store?.commit("setGuide", data);
			// driverObj__.destroy();
			// setCookie("isBeginner", false);
			setDestroy()
			this.record[index].driver = false
			sessionStorage.setItem('record', JSON.stringify(this.record));  
			this.createTimer()
			this.textScroll()
		},
		likeFile(item:any,imgIndex:number,index:number){
			let data = {
				...item,
				"userId" : this.userInfo?.userId,
			}
			Https.axiosPost(Https.httpUrls.pictureLikeOrUnLike, data).then(
				(rv) => {
					if(this.record[index].img[imgIndex].id == null){
						this.record[index].img[imgIndex].id = rv.id
					}else{
						this.record[index].img[imgIndex].id = null
					}
					sessionStorage.setItem('record', JSON.stringify(this.record));  
				}
			).catch(res=>{
			});
		},
		//创建定时器
        createTimer() {
			if (this.robotTop || this.robotInput) {
				this.clearTimer()
				this.timeTop = setInterval(() => {
					this.robotTop = false
				}, 15000);
				this.timeInput = setInterval(() => {
					this.robotInput = false
				}, 10000);

			}
           
        },
        //清除定时器
        clearTimer() {
			clearInterval(this.timeTop);
			clearInterval(this.timeInput);
        },
    },
});
</script>
<style lang="less" scoped>
.robot{
	position: absolute;
	bottom: .5rem;
	// bottom: 2.5rem;
	right: 2.5rem;
	// right: 5rem;
	z-index: 10003;
	// width: 400px;
	.robot_top{
		// width: 25rem;
		width: 30rem;
		margin-left: auto;
		// height: 20rem;
		overflow-x: hidden;
		transition: .3s all;
		opacity: 0;
		height: auto;
		max-height: 30rem;
		display: none;
		&.active{
			opacity: 1;
		}
		&.robot_top::-webkit-scrollbar{display: none;}
		.robot_text{
			font-size: 1.4rem;
			padding: 1rem 1.5rem;
			display: inline-block;
			border-radius: 2rem;
			max-width: 80%;
			.robot_img{
				display: flex;
				flex-wrap: wrap;
				align-items: center;
				justify-content: center;
				&.img{
					width: 18rem;
				}
				.robot_img_item{
					max-height: 100%;
					position: relative;
					width: 40%;
					overflow: hidden;
					margin: 0 5%;
					margin-bottom: 5%;
					&:hover .delete_like_file_block{
						display: block;
					}
				}
				img{
					width: 100%;
					height: 8rem;
					object-fit: contain;
					cursor: auto;
					// width: auto;
				}
				img:nth-child(2n-1){
					// margin-right: 5%;
				}
			}
			// .driver__{
				
			// }
			.driver__btn{
				width: 100%;
				margin-top: 1rem;
				display: flex;
				justify-content: space-around;
				span{
					font-size: 1.4em;
					color: #9efff4;
					cursor: pointer;
				}
			}
		}
		.text_left,.text_right{
			margin: 2rem 0;
			font-size: 1.2rem;
		}
		.text_left{
			display: flex;
			justify-content: flex-start;
			>div{
				background-color: #e8e8ea;
				color: #000;
			}
		}
		.text_right{
			display: flex;
			justify-content: flex-end;
			>div{
				background-color: #835ff7;
				color: #fff;
			}
			&.white{
				>div{
					background-color: #fff;
				}
			}

		}
	}
	.robot_content{
		opacity: 0;
		width: 8rem;
		height: 1.1rem;
		border-radius: 2rem;
		overflow: hidden;
		border: .2rem solid;
		background: #341e57;
		display: flex;
		justify-content: flex-end;
		margin-left: auto;
		transition: all .3s;
		>div{
			background: linear-gradient(45deg, #eee4f3, #f3f4e6);
			height: 100%;
			width: 80%;
			border-radius: 2rem;
		}
	}
	&.robot:hover .robot_content{
		opacity: 1;
	}
	.robot_bottom{
		display: flex;
		align-items: center;
	}
	.robot_input{
		border: 1px solid #d5d5d7;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: .5rem 1rem;
		background: #fff;
		border-radius: 5px;
		// height: 32px;
		transition: .3s all;
		opacity: 0;
		display: none;
		margin-right: 4rem;
		&.active{
			opacity: 1;
		}
		input{
			border: none;
			font-size: 1.2rem;
			width: 25rem;
		}
		.robot_btn{
			display: flex;
			height: 100%;
			cursor: pointer;
		}
		.fi-ss-paper-plane-top{
			display: flex;
			align-items: center;
		}
		.fi-ss-paper-plane-top::before{
			color: #835df8;
		}
	}
	.robot_img{
		    margin-left: auto;
		img{
			width: 8rem;
			// margin-left: 40px;
			cursor: pointer;

		}
	}
}
</style>
