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

</template>
<script>
	const util = require('@/utils/util.js').default;
	const config = require('@/services/urlConfig.js');
    let webAudioSpeechRecognizer;
    import {
        Toast,Indicator
    } from 'mint-ui';
    import { Loading } from 'element-ui';
    import spaceTypes from '@/static/spaceTypesIE.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,	//每次变化的比例
				spaceList:[],
				showX:false,
                highColor1:window.highColor1,
                highColor2:window.highColor2,
                backgroundColor:window.backgroundColor,
                
                speechText: '', //语音识别的结果-文字
                recording: false, //语音识别是否开始
                touching:false,
                audioAuth:false, //录音权限
                loadingInstance:null,
			}
		},
		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();
						// }
						const spaceDetail = newVal;
						this.spaceList = JSON.parse(spaceDetail.houseJson);
                        this.initSpanceData();
					}
				},
			},
			curSpaceId: {
				handler(newVal,oldVal) {
					if (newVal) {
						console.warn("***curSpaceId-CHANGE-layout***", newVal)
						let space = this.spaceList.find(it=>it.spaceId==this.curSpaceId);
						if(space && space.spaceType==15){//X空间
							this.showX = true;
						}else{
							this.showX = false;
						}
					}
				},
			},
		},
		computed: {
			curSpaceId() {
				return this.$store.state.curSpaceId;
			},
		},
		async mounted() {
            this.getUserMedia();
			// this.getRecordAuth();//获取录音权限
			// this.initRecord();
			// var currPage = getCurrentPages()[getCurrentPages().length - 1] ? getCurrentPages()[getCurrentPages().length - 1].$vm : null;
			// currPage.updateSpanceData = this.initSpanceData;//页面注册变更方法
            // this.hexToRgba = window.hexToRgba;
		},
		// 页面被展示时执行
		onPageShow: function() {
			
		},
		//页面被隐藏时执行
		onPageHide: function() {
			console.warn("***detached-hide***")
		},
		methods: {
            onTouchFource(){
                return false;
            },
            hexToRgba(hex, opacity) {
                console.warn("**hexToRgba****",hex,opacity)
                if (!hex||!opacity){
                    return hex
                }
                let RGBA;
                if (hex.includes('#')&&hex.length==7){
                    RGBA = "rgba(" + parseInt("0x" + hex.slice(1, 3)) + "," + parseInt("0x" + hex.slice(3, 5)) + "," +
                        parseInt("0x" + hex.slice(5, 7)) + "," + opacity + ")";
                }else if (hex.includes('rgb(')){
            		var values = hex
            		  .replace(/rgb?\(/, '')
            		  .replace(/\)/, '')
            		  .replace(/[\s+]/g, '')
            		  .split(',')
            		  return `rgba(${values[0]},${values[1]},${values[2]},${opacity})`
                }else if(hex.includes('rgba(')){
            		var values = hex
            		  .replace(/rgba?\(/, '')
            		  .replace(/\)/, '')
            		  .replace(/[\s+]/g, '')
            		  .split(',')
            		  return `rgba(${values[0]},${values[1]},${values[2]},${opacity})`
            	}else{
                    return hex
                }
                return RGBA
            },
			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 = spaceTypes[item.spaceType - 1] || item.spaceName;
                    if(item.spaceType==15 && item.layoutSpaceType){
                    	text = spaceTypes[item.layoutSpaceType - 1]; 
                    }
					// let text = item.spaceName;
					if(text && !item.isSizeLock && (Number(maxArea) >= Number(curSpaceArea)) && !(maxArea==minArea && curSpaceArea==maxArea)){
						let res = await requestConfig("chineseToPinyin", {chinese:text},true);
						let pinyin = res.single;
						let data = {
							spaceId:item.spaceId,
							index:this.carefulList.length,
							name: text,
							namePY: pinyin,
							area:curSpaceArea,
							percent:null,
							minArea:minArea,	//最小面积
							maxArea:maxArea,	//最大面积
						}
						this.carefulList.push(data)
					}else{
                        // console.warn("***viewlayout-ini1t***", item.spaceId, text, maxArea, minArea, curSpaceArea,!item.isSizeLock, maxArea >= curSpaceArea,!(maxArea==minArea && curSpaceArea==maxArea))
                    }
				})
				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;
				let keyWord = this.$route.query.layer;
				if(keyWord){//如果存在结构特征，则定位到该模型大类下
					let item = this.seedLayoutList.find(it=>keyWord.includes(it.spaceName));
					if(item){
						this.selectSeedId = item.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)
			},
			//打开布局
			openLayout(style) {
				console.warn("***openLayout***",style,this.curSpaceId)
				let space = this.spaceList.find(it=>it.spaceId==this.curSpaceId);
				if(space && space.spaceType==15){//X空间
					this.showX = true;
				}else{
					this.showX = false;
				}
				if(style==3){
					if(this.showX){//X空间
						this.$emit("changeStyle",style);
					}else{
						Toast({
							message: '此空间无法更改功能',
						});
						return false
					}
				}else{
					this.$emit("changeStyle",style);
				}
				// util.trackRequest(param);
			},
			goRoam(){
				this.$parent.$refs.viewCareful.goRoam();
			},
            getUserMedia(){
                let self = this;
                if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                    //最新的标准API
                    navigator.mediaDevices.getUserMedia({
                        'audio':true,
                        'video':false//调用前置摄像头，后置摄像头使用video: { facingMode: { exact: "environment" } }
                    })
                        .then(success)
                        .catch(error)
                } else if (navigator.webkitGetUserMedia) {
                    //webkit核心浏览器
                    navigator.webkitGetUserMedia(constraints, success, error)
                } else if (navigator.mozGetUserMedia) {
                    //firfox浏览器
                    navigator.mozGetUserMedia(constraints, success, error);
                } else if (navigator.getUserMedia) {
                    //旧版API
                    navigator.getUserMedia(constraints, success, error);
                }
                function success(stream) {
                    //兼容webkit核心浏览器
                    let CompatibleURL = window.URL || window.webkitURL;
                    //将视频流设置为video元素的源
                    console.log(stream);
                    self.audioAuth = true;
                }
                function error(error) {
                    console.log(`访问用户媒体设备失败${error.name}, ${error.message}`);
                    self.audioAuth = false;
                    Toast({
                        message: '已拒绝麦克风授权，无法使用录音功能',
                    });
                }
                console.warn("****getUserMedia****")
            },
            //求最长公共子集
            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 (!text) {
                    Toast({
                        message: '未识别到语音',
                    });
                    return false;
                }
                if(!this.carefulList || this.carefulList.length==0){
                    console.warn("****textChange***", this.carefulList)
                    return false;
                }
                let param = {
                    type: 'CLK', //埋点类型
                    clkId: 'clk_2cmina_24082901', //点击ID
                    clkName: 'user_talk_clk', //点击前往的页面名称
                    clkParams: {
                        locusValue: text,
                    }
                };
                util.trackRequest(param);
                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) {
                    curSpace = this.carefulList.find(it=>it.spaceId == this.curSpaceId);
                    // Toast({
                    //     message: '请再说一次',
                    // });
                    // 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) { //都没命中
                    Toast({
                        message: '请再说一次',
                    });
                    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);
                Toast({
                    message: '正在变化，请稍后',
                });
                // this.sendMessageAction(JSON.stringify(parmas));
                this.$parent.$parent.callBackFun = this.callBack;//向父页面注册通知回调函数
                this.$emit("curSpaceChange", data); //通知父组件-当前已经选中了户型大类
            },
            //语音识别
            speechRecognizer() {
                if(this.audioAuth==false){
                    Toast({
                        message: '已拒绝麦克风授权，无法使用录音功能',
                    });
                    return false;
                }
                this.touching = true;//用户开始触摸语音按钮
                console.warn('speechRecognizer', this.recording)
                // if (!webAudioSpeechRecognizer) {
                    const params = {
                        // signCallback: signCallback, // 鉴权函数，若直接使用默认鉴权函数。可不传此参数
                        // 用户参数
                        secretid: $config.secretId,
                        secretkey: $config.secretKey,
                        appid: $config.txappId,
                        // 临时密钥参数，非必填
                        // token: config.token,
                        // 实时识别接口参数
                        engine_model_type: '16k_zh', // 因为内置WebRecorder采样16k的数据，所以参数 engineModelType 需要选择16k的引擎，为 '16k_zh'
                        // 以下为非必填参数，可跟据业务自行修改
                        // voice_format : 1,
                        // hotword_id : '08003a00000000000000000000000000',
                        // needvad: 1,
                        // filter_dirty: 1,
                        // filter_modal: 2,
                        // filter_punc: 0,
                        // convert_num_mode : 1,
                        // word_info: 2
                    }
                    webAudioSpeechRecognizer = new WebAudioSpeechRecognizer(params);
                    // Indicator.open({
                    //     text: '正在链接...',
                    //     spinnerType: 'fading-circle'
                    // });
                    this.loadingInstance = Loading.service({
                        lock: true,
                        text: '正在链接...',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });
                    // 开始识别
                    webAudioSpeechRecognizer.OnRecognitionStart = (res) => {
                        console.log('开始识别',this.recording, res);
                    };
                    // 一句话开始 socket链接成功了
                    webAudioSpeechRecognizer.OnSentenceBegin = (res) => {
                        console.log('一句话开始',this.touching,res);
                        if(this.touching==false){//用户没有触摸
                            return false;
                        }else{//正常开始识别语句了
                            this.speechText = "";
                            this.loadingInstance && this.loadingInstance.close();
                            this.recording = true;//显示正在录音视图
                            this.$parent.showCareful = false;//隐藏
                        }
                        
                    };
                    // 识别变化时
                    webAudioSpeechRecognizer.OnRecognitionResultChange = (res) => {
                        console.log('识别变化时', res);
                        // const currentText = `${resultText}${res.result.voice_text_str}`;
                    };
                    // 一句话结束
                    webAudioSpeechRecognizer.OnSentenceEnd = (res) => {
                        console.log('一句话结束',this.recording, res);
                        // resultText = res.result.voice_text_str;
                        let text = res.result.voice_text_str.replaceAll(/，|。/ig, "");
                        this.textChange(text);
                        // this.speechText += resultText;
                    };
                    // 识别结束
                    webAudioSpeechRecognizer.OnRecognitionComplete = (res) => {
                        console.log('识别结束', res);
                        this.recording = false; //录音结束
                        this.$parent.showCareful = true;//显示
                    };
                    // 识别错误
                    webAudioSpeechRecognizer.OnError = (res) => {
                        console.log('识别失败', res)
                        this.recording = false; //录音结束
                        this.$parent.showCareful = true;//显示
                        this.loadingInstance && this.loadingInstance.close();
                    };
                    // webAudioSpeechRecognizer = webAudioSpeechRecognizer;
                // }
                webAudioSpeechRecognizer.start();
            },
            //结束识别
            streamRecordEnd() {
                this.touching = false;//用户没有触摸了
                console.log('主动结束识别', this.recording)
                if(webAudioSpeechRecognizer){
                    webAudioSpeechRecognizer.stop();//关闭
                }
                // webAudioSpeechRecognizer = null;
                this.loadingInstance && this.loadingInstance.close();
                this.$parent.showCareful = true;//显示
            },
            callBack(type){
                console.warn("***viewlayout-callBack***",type)
                // this.initSpanceData();
                this.$parent.$refs.viewCareful.initData();//注销父页面的通知回调函数
            },
			//评估按钮处理
			assessmentHandle(){
                Toast({
                	message: '敬请期待！',
                });
			},
		}
	}
</script>
<style lang="scss" scoped>
	@import "./viewlayout.scss";
	/* @import "@/common/css/common.css"; */
</style>