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

<script>
    const util = require('@/utils/util.js').default;
    const config = require('@/services/urlConfig.js');
    import router from "@/router";
    import {
        setStorage,
        getStorage,
    } from '@/utils/localStorage';
    import {
        Toast
    } from 'mint-ui';
    // import houseList from "../../components/houseList/houseList.vue";
    // import houseList2 from "../../components/houseList/houseList2.vue";
    import commonPageMethod from '@/mixins/commonPageMethod.js';
    export default {
        mixins: [commonPageMethod],
        name: 'webgl_rxdz_recognizer_houseList',
        data() {
            return {
                pvId: 'p_2cmina_24012401',
                locusBehaviorName: "空间偏好",
                locusValue: "",
                locusName: "",
                pvCurPageName: "space_set",
                pvCurPageParams: null,
                navbar: {
                    showCapsule: 1,
                    title: '空间偏好',
                    titleColor: '#fff',
                    navPadding: 0,
                    navPaddingBg: 'transparent',
                    navBarColor: 'transparent',
                    navBackColor: 'transparent',
                    haveCallback: false, // 如果是 true 会接手 navbarBackClk
                    fromShare: false,
                    fromProject: 0,
                    shareToken: "",
                    pageName: this.pvCurPageName,
                },
                id: '', //题目id
                houseId: '',
                houseList: [], //户型列表
                optionIndex: -1, //选项选中的序号
                tabData: [], //
                curHouseObj: null, //用户选择的户型
                selectIndex: -1, //用户选择的户型序号
                queryObj: null, //页面参数

                webAudioSpeechRecognizer: null, //语音识别的对象
                speechText: '', //语音识别的结果-文字
                recording: false, //语音识别是否开始
                isCanStop:false,    //socket是否已经链接好了
            }
        },
        // components: {
        // 	houseList,
        // },
        watch: {},
        computed: {
            userId() {
                return this.$store.state.userId;
            },
        },
        mounted(options) {
            console.log("***onLoad-webgl_rxdz_houseList***", this.$route.query)
            this.queryObj = getStorage('queryObj') ? JSON.parse(getStorage('queryObj')) : null;
            this.houseId = this.$route.query.houseId ? this.$route.query.houseId : (this.$store.state.houseId || '');
            this.id = this.$route.query.id2 ? this.$route.query.id2 : (this.queryObj && this.queryObj.id2 ? this
                .queryObj.id2 : '110');
            this.findHouseTypeSpaceList();
            // this.queryTestcaseSingle();
            document.title = this.navbar.title;
        },
        methods: {
            backFun() {
                uni.navigateBack({
                    url: 'pages/groupIndex2/groupIndex2'
                })
            },
            // selectHouseObj(obj) {
            // 	console.log("户型", obj);
            // 	this.enterAction(obj, 0, 0);
            // },
            //切换选项
            changeOption(idx, idx1) {
                if (idx1 == this.tabData[idx].checkedIndex) {
                    return false;
                }
                this.tabData[idx].checkedIndex = idx1;
                // console.warn("***changeOption***", this.tabData,this.allSelect)
                // let param = {
                // 	type: 'CLK', //埋点类型
                // 	clkId: 'clk_2cmina_24012401', //点击ID
                // 	clkName: 'option_clk', //点击前往的页面名称
                // 	clkParams: {
                // 		type: this.tabData[idx].options[idx1].content,
                // 		locusName: "选项选择",
                // 	}
                // };
                // util.trackRequest(param);
                this.submitAnswer(idx, idx1);
            },
            submitAnswer(tabIndex, optionIndex) {
                let userId = this.userId || '';
                let params = {
                    "answerContent": [{
                        "optionTitle": this.tabData[tabIndex].options[optionIndex].content,
                        "questionTitle": this.tabData[tabIndex].subContent, //问题标题
                        "subOptionId": this.tabData[tabIndex].options[optionIndex].id,
                        "subQuestionId": this.tabData[tabIndex].id,
                    }],
                    brandId: $config.brandId,
                    houseId: this.houseId,
                    channel: this.queryObj ? this.queryObj.channel : '',
                    city: this.queryObj ? this.queryObj.city : '',
                    district: this.queryObj ? this.queryObj.district : '',
                    province: this.queryObj ? this.queryObj.province : '',
                    paperTitle: '', //试卷id
                    testThemeId: '',
                    testcaseId: this.id,
                    uuid: userId,
                    xcxCustomerId: userId,
                };
                requestConfig('submitAnswer', params, true);
                let param = {
                    type: 'CLK', //埋点类型
                    clkId: 'clk_2cmina_24022002', //点击ID
                    clkName: 'option_clk', //点击前往的页面名称
                    clkParams: {
                        locusValue: this.tabData[tabIndex].options[optionIndex].content,
                        locusName: "选项选择",
                    }
                };
                util.trackRequest(param);
            },
            changeHouse(index) {
                this.curHouseObj = this.houseList[index];
                this.selectIndex = index;
                console.log("changeHouse: ", this.curHouseObj, this.selectIndex);
                let param = {
                    type: 'CLK', //埋点类型
                    clkId: 'clk_2cmina_24012401', //点击ID
                    clkName: 'option_clk', //点击前往的页面名称
                    clkParams: {
                        houseType: this.curHouseObj.houseType,
                        name: this.curHouseObj.name,
                        note: this.curHouseObj.note,
                        area: this.curHouseObj.houseArea,
                        id: this.curHouseObj.id,
                        locusValue: this.curHouseObj.houseType,
                        locusName: "空间选择",
                    }
                };
                util.trackRequest(param);
            },
            //查询题目数据
            // async queryTestcaseSingle() {
            // 	let params = {
            // 		id: this.id,
            // 		brandId: $config.brandId,
            // 		houseId: this.houseId,
            // 	};
            // 	const res = await requestConfig('queryTestcaseSingle', params);
            // 	if (res.success) {
            // 		let list = res.list;
            // 		list.forEach(it => it.checkedIndex = -1); //增加当前题目用户选择的需要，默认不选中
            // 		this.tabData = list;
            // 	}
            // },
            // 查询户型列表
            async findHouseTypeSpaceList() {
                // const { houseId, brandId } = getApp().globalData;
                var parmas = {
                    brandId: $config.brandId,
                    houseId: this.houseId,
                    pageNo: 1,
                    pageSize: 2000,
                    isCloud: 1,
                };
                let res = await requestConfig("findHouseTypeSpaceList", parmas);
                if (res.success && res.pageModel) {
                    let list = res.pageModel.resultSet || [];
                    list && list.forEach((item, index) => {
                        if (item.houseJson) {
                            let spaceList = JSON.parse(item.houseJson);
                            // 交换centerX， centerY
                            for (let index = 0; index < spaceList.length; index++) {
                                var element = spaceList[index];
                                const {
                                    centerX,
                                    centerY
                                } = element;
                                element.centerX = centerY;
                                element.centerY = centerX;
                                //默认布局和实际默认布局对不上时的处理方案
                                if (element.layouts.length > 1) {
                                    let layout = element.layouts.find(it => it.isDefault == true);
                                    if (layout) {
                                        element.layoutId = layout.layoutId;
                                    }
                                }
                            }
                            item.houseJson = JSON.stringify(spaceList);
                            console.log("户型详情列表: ", spaceList);
                        }
                    })
                    this.houseList = res.pageModel.resultSet || [];
                }
            },
            //进入下一步
            enterAction() {
                if (!this.curHouseObj) {
                    Toast({
                        message: '请选择喜欢的空间',
                    });
                    return false;
                }
                console.log("进入订制户型: ", this.curHouseObj);
                setStorage('curHouseObj', this.curHouseObj);
                this.$store.dispatch('setCurHouseObj', this.curHouseObj);
                let data = {
                    houseId: this.houseId,
                }
                router.push({
                    name: "webgl_rxdz_test",
                    query: data
                });
            },
            //求最长公共子集
            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 "";
            },
            //中文数字转为阿拉伯数字
            convertChineseToArabic(str) {
                const chineseNums = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
                const arabicNums = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
             
                const chineseNumRegex = new RegExp(`(${chineseNums.join('|')})+`, 'g');
             
                return str.replace(chineseNumRegex, (match) => {
                    let result = '';
                    for (let i = 0; i < match.length; i++) {
                        const charIndex = chineseNums.indexOf(match[i]);
                        result += charIndex !== -1 ? arabicNums[charIndex] : '';
                    }
                    return result;
                });
            },
            extractNumber(text) {  
                const parts = text.split('第')[1]; // 分割并获取数字部分  
                return parts ? parseInt(parts, 10) : null; // 转换为整数  
            },
            backwardNumber(text) {
                const parts = text.split('倒数第')[1]; // 分割并获取数字部分  
                return parts ? parseInt(parts, 10) : null; // 转换为整数  
            },
            async textChange(text) {
                text = text.replaceAll(/ |，|。/ig, "");
                if (!text) {
                    Toast({
                        message: '请再说一次',
                    });
                    return false;
                }
                // let res = await requestConfig("chineseToPinyin", {
                //     chinese: text
                // });
                // let pinyin = res.single;
                // console.warn("****pinyin***", pinyin)
                // text = pinyin;
                //全匹配轮一遍
                text = this.convertChineseToArabic(text);
                let houseIndex = this.backwardNumber(text);//获取文字里面的数字 倒数第三个 类似这样的
                if(houseIndex){
                    houseIndex = this.houseList.length - houseIndex;
                    if(houseIndex < 0){//越界了
                        Toast({
                            message: '数据不合法，请再说一次',
                        });
                    }else{
                        this.changeHouse(houseIndex);
                    }
                    return false;
                }else{
                    houseIndex = this.extractNumber(text);//获取文字里面的数字 第三个 类似这样的
                }                

                if (!houseIndex) {
                    let list = this.houseList.map((space, index) => {
                        let comStr = this.findSubStr(text, space.houseType + ' ' + space.houseArea + "㎡ " +
                            space.note);
                        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的序号
                        houseIndex = index; //
                    }
                }
                //没有找到语音操作对象
                if (!houseIndex) {
                    Toast({
                        message: '请再说一次',
                    });
                    return false;
                }
                if(houseIndex > this.houseList.length){
                    Toast({
                        message: '数据不合法，请再说一次',
                    });
                   return false; 
                }
                this.changeHouse(houseIndex - 1);
                console.log("textChange：", houseIndex);


                // this.$emit("curSpaceChange", data); //通知父组件-当前已经选中了户型大类
            },
            //用户语音为空
            showRecordEmptyTip() {
                this.recording = false; //录音结束
                Toast({
                    message: '告诉我您的想法',
                });
            },
            //语音识别
            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;
                        this.speechText = resultText;
                        let param = {
                            type: 'CLK', //埋点类型
                            clkId: 'clk_2cmina_23080407', //点击ID
                            clkName: 'voice_clk', //点击前往的页面名称
                            clkParams: {
                                locusName: "语音调整",
                                text: resultText
                            }
                        };
                        util.trackRequest(param);
                        this.textChange(resultText);
                    };
                    // 识别结束
                    webAudioSpeechRecognizer.OnRecognitionComplete = (res) => {
                        console.log('识别结束', res);
                    };
                    // 识别错误
                    webAudioSpeechRecognizer.OnError = (res) => {
                        console.log('识别失败', res)
                    };
                    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 "./webgl_rxdz_recognizer_houseList.scss";
</style>