<template src="./viewlayout.html">

</template>
<script>
	// const util = require('@/static/utils/util.js');
	const config = require('@/services/urlConfig.js');
	// import Bus from '@/common/bus';
	// import commonMethod from '@/common/commonMethod.js';
	// import requestConfig from '@/static/lib/requestConfig';
	// import { language } from '@/static/utils/conf.js'
	// const plugin = requirePlugin("WechatSI");
	// 获取**全局唯一**的语音识别管理器**recordRecoManager**
	// const manager = plugin.getRecordRecognitionManager()
	// import bgLoading from "@/components/bgLoading/bgLoading.vue"
	// import { nextTick } from "vue";
	// const app = getApp(); //获取应用实例
	// let positions = new Set();
	export default {
		data: function() {
			return {
				seedLayoutList: [],
				selectSeedId: null, //当前选中的种子户型id
				currentTranslate: {
					// 当前语音输入内容
					create: '04/27 15:37',
					text: '等待说话',
				},
				recording: false, // 正在录音
				startX:0,
				startY:0,
				clientX:0,
				clientY:0,
				defaultIndex:0,//默认选中的户型大类
				carefulList:[],
				lastSpace:null,	//上一个语音操作的空间对象
				bigWord:"变大,放大,大一点,变宽",
				bigWordPY:"bianda,fangda,dayidian,biankuan",
				smaillWord:"变小,缩放,小一点,变窄",
				smaillWordPY:"bianxiao,suofang,xiaoyidian,bianzhai",
				changeRate:0.05,	//每次变化的比例
			}
		},
		props: {
			houseList: {//当前户型所有的户型详情，可以切换
				type: Array,
				default: () => {
					return []
				}
			},
			curHouseObj: {//当前展示的户型
				type: Object,
				default: () => {
					return null
				}
			},
			overChange: {//当前选中的户型类型
				type: Boolean,
				default: false,
			},
			styleType:{
				type: [String, Number],
				default: '',
			}
		},
		watch: {
			houseList: {
				handler(newVal) {
					if (newVal) {
						console.warn("***houseList-change***", newVal)
						this.initData(newVal);
					}
				},
			},
			curHouseObj: {
				handler(newVal,oldVal) {
					if (newVal) {
						console.warn("***curHouseObj-CHANGE-layout***", newVal)
						if((oldVal && oldVal.id != newVal.id) || !oldVal){
							this.initSpanceData();
						}
					}
				},
			},
		},
		async mounted() {
			// this.getRecordAuth();//获取录音权限
			// this.initRecord();
			// var currPage = getCurrentPages()[getCurrentPages().length - 1] ? getCurrentPages()[getCurrentPages().length - 1].$vm : null;
			// currPage.updateSpanceData = this.initSpanceData;//页面注册变更方法
		},
		// 页面被展示时执行
		onPageShow: function() {
			
		},
		//页面被隐藏时执行
		onPageHide: function() {
			console.warn("***detached-hide***")
		},
		methods: {
			initSpanceData(){
				this.carefulList = [];
				// var currPage = getCurrentPages()[getCurrentPages().length - 1] ? getCurrentPages()[getCurrentPages().length - 1].$vm : null;
				const spaceDetail = this.curHouseObj;
				const spaceList = JSON.parse(spaceDetail.houseJson);
				spaceList && spaceList.forEach(async (item,index)=>{
					let curSpaceArea = parseFloat(
						(item.spaceWidth * item.spaceHeight) / 10000
					).toFixed(1);
					let minArea = 0;
					let maxArea = 100;
					if(item.hasOwnProperty('spaceWidthMin') && item.hasOwnProperty('spaceHeightMin')){
						minArea = parseFloat((item.spaceWidthMin * item.spaceHeightMin) / 10000).toFixed(1);
					}
					if(item.hasOwnProperty('spaceWidthMax') && item.hasOwnProperty('spaceHeightMax')){
						maxArea = parseFloat((item.spaceWidthMax * item.spaceHeightMax) / 10000).toFixed(1);
					}
					let text = item.spaceName;
					if(text && !item.isSizeLock){
						// let res = await requestConfig("chineseToPinyin", {chinese:text},true);
						// let pinyin = res.single;
						let data = {
							spaceId:item.spaceId,
							index:this.carefulList.length,
							name:text,
							namePY:'',
							area:curSpaceArea,
							percent:null,
							minArea:minArea,	//最小面积
							maxArea:maxArea,	//最大面积
						}
						this.carefulList.push(data)
					}
				})
				console.warn("***viewlayout-init***", this.carefulList)
			},
			initData(houseList){
				this.seedLayoutList = [];
				houseList && houseList.forEach(item=>{
					let data = {
						spaceStructure: item.spaceStructure,
						spaceName: item.spaceName,
						set: false, //是否已经设置过
					};
					this.seedLayoutList.push(data);
				})
				// var currPage = getCurrentPages()[getCurrentPages().length - 1] ? getCurrentPages()[getCurrentPages().length - 1].$vm : null;
				// if(currPage.curHouseType){//获取当前页面选中的户型类型
				// 	this.selectSeedId = currPage.curHouseType
				// } else if(this.seedLayoutList && this.seedLayoutList[this.defaultIndex]){//默认选中第一个
				// 	this.selectSeedId = this.seedLayoutList[this.defaultIndex].spaceStructure;
				// }
				this.selectSeedId = this.seedLayoutList[this.defaultIndex].spaceStructure;
				if(this.selectSeedId){
					let item = this.seedLayoutList.find(it=>{
						return it.spaceStructure == this.selectSeedId
					})
					this.$emit("seedChange", item);//通知父组件-当前已经选中了户型大类
					let param = {
						type: 'CLK', //埋点类型
						clkId: 'clk_2cmina_23080402', //点击ID
						clkName: 'seedroom_clk', //点击前往的页面名称
						clkParams: {
							type: item.spaceName,
							locusValue: item.spaceStructure,
							locusName: "切换种子户型",
						}
					};
					// util.trackRequest(param);
				}
				console.warn("***curHouseType-init***",this.seedLayoutList)
			},
			// seedItemCheck(item) {
			// 	if (!item || !item.spaceStructure) {
			// 		return false;
			// 	}
			// 	if (item.spaceStructure == this.selectSeedId) {
			// 		return false;
			// 	}
			// 	this.selectSeedId = item.spaceStructure;
			// 	this.$emit("seedChange", item);
			// 	let param = {
			// 		type: 'CLK', //埋点类型
			// 		clkId: 'clk_2cmina_23080402', //点击ID
			// 		clkName: 'seedroom_clk', //点击前往的页面名称
			// 		clkParams: {
			// 			type: item.spaceName,
			// 			locusValue: item.spaceStructure,
			// 			locusName: "切换种子户型",
			// 		}
			// 	};
			// 	// util.trackRequest(param);
			// },
			//上划触发
			upCom() {
				console.warn("***upCom***")
				this.$emit("upCom");
				let param = {
					type: 'CLK', //埋点类型
					clkId: 'clk_2cmina_23080403', //点击ID
					clkName: 'adjust_clk', //点击前往的页面名称
					clkParams: {
						locusName: "精细调整",
					}
				};
				// util.trackRequest(param);
			},
			//获取录音权限
			getRecordAuth: function() {
				uni.getSetting({
					success(res) {
						console.log("succ")
						console.log(res)
						if (!res.authSetting['scope.record']) {
							uni.authorize({
								scope: 'scope.record',
								success() {
									// 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
									console.log("succ auth")
								},
								fail() {
									console.log("fail auth")
								}
							})
						} else {
							console.log("record has been authed")
						}
					},
					fail(res) {
						console.log("fail")
						console.log(res)
					}
				})
			},
			//求最长公共子集
			findSubStr(str1, str2){
			    if (str1.length > str2.length) {
			      var temp = str1;
			      str1 = str2;
			      str2 = temp;
			    }
			    let len1 = str1.length;
			    let len2 = str2.length;
			    for (var j = len1; j > 0; j--) {
			      for (var i = 0; i < len1 - j; i++) {
			        var current = str1.substr(i, j);
			        if (str2.indexOf(current) >= 0) {
			          return current;
			        }
			      }
			    }
			    return "";
			},
			//声音变化
			async textChange(text) {
				if(this.overChange){
					uni.showToast({
						title: '请慢一点',
						icon: 'none',
						duration: 2000
					})
					return false;
				}
				let res = await requestConfig("chineseToPinyin", {chinese:text});
				let pinyin = res.single;
				console.warn("****pinyin***",pinyin)
				text = pinyin;
				//全匹配轮一遍
				let curSpace = this.carefulList.find(space=>{
					return text.includes(space.namePY)
				})
				if(!curSpace){
					let list = this.carefulList.map((space,index)=>{
						let comStr = this.findSubStr(text, space.namePY + ' ');
						return {
							spaceId:space.spaceId,
							namePY:space.namePY,
							name:space.name,
							comStr,
							index,
						}
					})
					//寻找5个字符串以上的
					let tmpList = list.filter(it=>{
						return it.comStr.length > 5;
					})
					if(tmpList && tmpList.length>0){
						tmpList.sort((a, b) => a.comStr.length - b.comStr.length);
						let index = tmpList[tmpList.length-1].index;//最大值在carefulList的序号
						curSpace = this.carefulList[index];//
					}else{
						curSpace = this.lastSpace;
					}
				}
				
				//没有找到语音操作对象
				if(!curSpace){
					uni.showToast({
						title: '请再说一次',
						icon: 'none',
						duration: 2000
					})
					return false;
				}
				this.lastSpace = curSpace;
				
				console.log("textChange：", curSpace,this.carefulList,text,this.bigWordPY,this.smaillWordPY);
				
				let biglist = this.bigWordPY.split(',').map(word=>{
					return text.lastIndexOf(word)
				})
				let smalllist = this.smaillWordPY.split(',').map(word=>{
					return text.lastIndexOf(word)
				})
				let a = Math.max(...biglist);
				let b = Math.max(...smalllist);
				let big = false;
				if(a==-1 && b==-1){//都没命中
					uni.showToast({
						title: '请再说一次',
						icon: 'none',
						duration: 2000
					})
					return false;
				}else if(a>-1 && b>-1){//两个都命中了
					if(a > b){//放大靠后-命中靠后
						big = true;
					}else{
						big = false;
					}
				}else if(a>-1){
					big = true;
				}
				let _area = parseFloat(curSpace.area) * this.changeRate;
				let data = {
					spaceId:curSpace.spaceId,
					area:_area,
					isZoomIn:big,//true 放大 false 缩放
				}
				console.log("viewlayout-发送消息-空间变化: ",data,curSpace.area,big);
				uni.showToast({
					title: '正在变化，请稍后',
					icon: 'none',
					duration: 2000
				})
				// this.sendMessageAction(JSON.stringify(parmas));
				this.$emit("curSpaceChange",data);//通知父组件-当前已经选中了户型大类
			},
			/**
			 * 初始化语音识别回调
			 * 绑定语音播放开始事件
			 */
			initRecord: function() {
				// var currPage = getCurrentPages()[getCurrentPages().length - 1] ? getCurrentPages()[getCurrentPages().length - 1].$vm : null;
				//有新的识别内容返回，则会调用此事件
				manager.onRecognize = (res) => {
					let currentData = Object.assign({}, this.currentTranslate, {
						text: res.result,
					})
					this.currentTranslate = currentData;
					console.warn("***manager-正在录音***",this.currentTranslate)
				}
				// 识别结束事件
				manager.onStop = (res) => {
					console.warn("***manager-识别结束0***",this.recording,res)
					// this.textChange("客厅大一点");
					if(this.recording==false){//已经强制结束识别了
						return false;//不识别
					}
					let text = res.result
					if (text == '') {//识别内容为空时的反馈
						this.showRecordEmptyTip()
						return
					}
					console.warn("***manager-识别结束***",text);
					let param = {
						type: 'CLK', //埋点类型
						clkId: 'clk_2cmina_23080407', //点击ID
						clkName: 'voice_clk', //点击前往的页面名称
						clkParams: {
							locusName: "语音调整",
							text:text
						}
					};
					// util.trackRequest(param);
					text = text.replaceAll(/，|。/ig, "");
					this.textChange(text);
					this.stopRecordHandle();
					//翻译
					// this.translateText(currentData, this.dialogList.length)
				}

				// 识别错误事件
				manager.onError = (res) => {
					console.warn("***manager-识别错误***",this.recording,res)
					if(this.recording == false){
						return false;
					}
					this.stopRecordHandle();
					uni.showToast({
						title: '请再说一次',
						icon: 'none',
						duration: 2000
					})
				}
				// 语音播放开始事件
				uni.onBackgroundAudioPlay(res => {
					const backgroundAudioManager = uni.getBackgroundAudioManager()
					let src = backgroundAudioManager.src
					
					this.currentTranslateVoice = src;
				})
			},
			//执行停止录音的方法
			stopRecordHandle(){
				// var currPage = getCurrentPages()[getCurrentPages().length - 1] ? getCurrentPages()[getCurrentPages().length - 1].$vm : null;
				this.recording = false;
				this.$emit("streamRecordEnd");//通知父组件
				// currPage.voiceMaskChange(false);//关闭蒙层
			},
			//用户语音为空
			showRecordEmptyTip(){
				this.stopRecordHandle();
				uni.showToast({
					title: '告诉我您的想法',
					icon: 'none',
					duration: 2000
				})
			},
			catchTapEvent:function(){
				return false;
			},
			/**
			 * 按住按钮开始语音识别
			 */
			streamRecord: function(e) {
				// this.getRecordAuth();//获取录音权限
				console.warn("streamrecord", e)
				let currPage = getCurrentPages()[getCurrentPages().length - 1] ? getCurrentPages()[getCurrentPages().length - 1].$vm : null;
				// let buttonItem = detail.buttonItem || {}
				manager.start({
					lang: language[0].lang_content,
				})
				// this.recordStatus = 0;
				this.clientX = 0;
				this.clientY = 0;
				this.startX = e.changedTouches[0].clientX;
				this.startY = e.changedTouches[0].clientY;
				this.recording = true;//录音中
				currPage.voiceMaskChange(true);//显示蒙层
				this.$emit("streamRecord");
			},
			mytouchmove(e) {
				let startX = this.startX // 开始x坐标 
				let startY = this.startY //开始y坐标
				let touchMoveX = e.changedTouches[0].clientx //滑动变化坐标 
				let touchMoveY = e.changedTouches[0].clientY //滑动变化坐标 
				this.clientX = touchMoveX - startX;
				this.clientY = touchMoveY - startY;
			},
			angle(start,end){
				let _X = end.X - start.X;
				let _Y = end.Y - start.Y;
				if(_X == 0) return 90;
				return 360 * Math.atan((_Y / _X) / (2*Math.PI))
			},
			/**
			 * 松开按钮结束语音识别
			 */
			streamRecordEnd: function(e) {
				console.warn("streamRecordEnd" ,this.recording,e)
				// let detail = e.detail || {} // 自定义组件触发事件时提供的detail对象
				// let buttonItem = detail.buttonItem || {}

				// 防止重复触发stop函数
				if (this.recording==false) {
					console.warn("has finished!")
					return
				}
				let startX = this.startX; // 开始x坐标
				let startY = this.startY; //开始y坐标
				let touchMoveX = e.changedTouches[0].clientX; //滑动变化坐标 
				let touchMoveY = e.changedTouches[0].clientY; //滑动变化坐标 
				let angle = this.angle(
				{
					X: startX,
					Y: startY
				}, {
					X: touchMoveX,
					Y: touchMoveY
				})
				//滑动角度超过45retrun
				// console.log(Math.abs(angle), "Math.abs(angle)")
				if (Math.abs(angle) > 45){//上下滑动
					if (startY > touchMoveY && (startY - touchMoveY)>20) { //上滑
						console.warn("***touchend-上滑***",startY - touchMoveY);
						this.stopRecordHandle();//停止录音了
						manager.stop()
						uni.showToast({
							title: '识别已取消!',
							icon: 'none',
							duration: 2000
						})
					}else{
						this.stopRecordHandle();//停止录音了
						manager.stop()
						console.warn("streamRecordEnd-stop1" ,this.recording)
					}
				}else{
					this.stopRecordHandle();//停止录音了
					manager.stop();
					console.warn("streamRecordEnd-stop2" ,this.recording)
				}
			},
		}
	}
</script>
<style lang="css" scoped>
	@import "./viewlayout.css";
	/* @import "@/common/css/common.css"; */
</style>