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

</template>
<script>
    const util = require('@/utils/util.js').default;
    const config = require('@/services/urlConfig.js');
    import {
        Toast
    } from 'mint-ui';
    // 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,duo,kuan,da",
                smaillWord: "变小,缩放,小一点,小,少,窄",
                smaillWordPY: "bianxiao,suofang,xiaoyidian,xiao,shao,zhai",
                changeRate: 0.05, //每次变化的比例
                spaceList: [],
                showX: false,

                webAudioSpeechRecognizer: null, //语音识别的对象
                speechText: '', //语音识别的结果-文字
                recording: false, //语音识别是否开始
                isCanStop:false,    //socket是否已经链接好了
            }
        },
        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.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: pinyin,
                            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;
                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);
                }
            },
            goRoam() {
                this.$parent.$refs.viewCareful.goRoam();
            },
            //求最长公共子集
            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) {
                //     Toast({
                //         message: '请慢一点',
                //     });
                //     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) {
                    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.$emit("curSpaceChange", data); //通知父组件-当前已经选中了户型大类
            },
            //语音识别
            speechRecognizer() {
                this.recording = true;
                console.warn('speechRecognizer', this.webAudioSpeechRecognizer,this.recording)
                if (!this.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
                    }
                    const webAudioSpeechRecognizer = new WebAudioSpeechRecognizer(params);
                    let resultText = '';
                    // 开始识别
                    webAudioSpeechRecognizer.OnRecognitionStart = (res) => {
                        console.log('开始识别',this.recording, res);
                    };
                    // 一句话开始 socket链接成功了
                    webAudioSpeechRecognizer.OnSentenceBegin = (res) => {
                        console.log('一句话开始',this.recording, res);
                        this.speechText = "";
                        this.isCanStop = true;
                    };
                    // 识别变化时
                    webAudioSpeechRecognizer.OnRecognitionResultChange = (res) => {
                        console.log('识别变化时',this.recording, res);
                        const currentText = `${resultText}${res.result.voice_text_str}`;
                        this.speechText = currentText;
                    };
                    // 一句话结束
                    webAudioSpeechRecognizer.OnSentenceEnd = (res) => {
                        console.log('一句话结束',this.recording, res);
                        resultText = res.result.voice_text_str;
                        let param = {
                            type: 'CLK', //埋点类型
                            clkId: 'clk_2cmina_23080407', //点击ID
                            clkName: 'voice_clk', //点击前往的页面名称
                            clkParams: {
                                locusName: "语音调整",
                                text: resultText
                            }
                        };
                        util.trackRequest(param);
                        let text = resultText.replaceAll(/，|。/ig, "");
                        this.textChange(text);
                        this.speechText += resultText;
                    };
                    // 识别结束
                    webAudioSpeechRecognizer.OnRecognitionComplete = (res) => {
                        console.log('识别结束', res);

                        this.recording = false; //录音结束
                    };
                    // 识别错误
                    webAudioSpeechRecognizer.OnError = (res) => {
                        console.log('识别失败', res)
                        this.recording = false; //录音结束
                    };
                    this.webAudioSpeechRecognizer = webAudioSpeechRecognizer;
                }
                this.webAudioSpeechRecognizer.start();
            },
            //结束识别
            streamRecordEnd() {
                this.recording = false; //录音结束
                console.log('主动结束识别', this.recording,this.isCanStop)
                if (this.isCanStop) {//链接成功才能关闭
                    this.webAudioSpeechRecognizer.stop();//关闭
                    this.isCanStop = false; //已经关闭了，不能在此打开
                    this.webAudioSpeechRecognizer = null;
                }
            },
        }
    }
</script>
<style lang="scss" scoped>
    @import "./viewlayout.scss";
</style>