addBusi.js 19 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
// 商机信息页面 Vue 应用
const utils = new publicMethod()

new Vue({
    el: '#app',

    data: {
        isAlone: true,

        // 联系方式
        contactPhone: '138****1234',

        // 弹窗相关
        modifyPhone:{
            isShow: false,

            phone: '',
        },

        // 商机类型
        businessTypes: [
            {
                id: 1,
                name: '融合套餐',
                selected: false,
                nodeId: '6:270'
            },
            {
                id: 2,
                name: '家庭安防',
                selected: false,
                nodeId: '6:272'
            },
            {
                id: 3,
                name: '智能家居',
                selected: false,
                nodeId: '6:274'
            },
            {
                id: 4,
                name: '企业专线',
                selected: false,
                nodeId: '6:276'
            },
            {
                id: 5,
                name: '云服务',
                selected: false,
                nodeId: '6:278'
            },
            {
                id: 6,
                name: '宽带升级',
                selected: false,
                nodeId: '6:613'
            }
        ],

        // 语音录制状态
        isRecording: false,
        recordingTimer: null,
        recordingDuration: 0,
        recordingUrlArr: [], // 录音文件URL

        // 文字描述
        textDescription: '',

        // API相关
        isSubmitting: false,

        // 用户信息
        userInfo: null,
        mediaStream: ''
    },

    created() {
        // 页面初始化时获取用户信息
        
    },

    mounted() {
        this.getUserInfo()

        // 页面加载完成后的初始化
        console.log('商机信息页面已加载');

        // 添加页面可见性变化监听
        document.addEventListener('visibilitychange', this.handleVisibilityChange);
    },

    beforeDestroy() {
        // 页面销毁前的清理工作
        this.cleanup();
    },

    methods: {

        /**
         * 获取用户信息
         */
        getUserInfo() {
            try {
                const loginInfo = localStorage.getItem('appLoginInfo');
                if (loginInfo) {
                    this.userInfo = JSON.parse(loginInfo);
                    // 如果有用户手机号,可以脱敏显示
                    if (this.userInfo && this.userInfo.phone) {
                        this.contactPhone = this.maskPhone(this.userInfo.phone);
                    }
                }
            } catch (error) {
                console.error('获取用户信息失败:', error);
            }
        },

        /**
         * 手机号脱敏处理
         */
        maskPhone(phone) {
            if (!phone || phone.length < 11) {
                return '138****1234'; // 默认显示
            }
            return phone.substring(0, 3) + '****' + phone.substring(7);
        },

        /**
         * 编辑联系方式
         */
        editContact() {
            // 打开弹窗
            this.newPhone = '';
            this.modifyPhone.isShow = true;
        },
        /**
         * 关闭编辑弹窗
         */
        closeEditModal() {
            this.modifyPhone.newPhone = '';
            this.modifyPhone.isShow = false
        },

        submitPhone(){
            if(!this.modifyPhone.phone){
                util.toast('请输入手机号')
                return
            }

            if(!/^1[3-9]\d{9}$/.test(this.modifyPhone.phone)){
                util.toast('手机号格式不正确')
                return
            }


        },

        /**
         * 选择商机类型
         */
        selectBusinessType(typeId) {
            const type = this.businessTypes.find(t => t.id === typeId);
            if (type) {
                type.selected = !type.selected;

                // 限制最多选择3个商机类型
                const selectedCount = this.businessTypes.filter(t => t.selected).length;
                if (selectedCount > 3) {
                    type.selected = false;
                    utils.toast('最多只能选择3个商机类型');
                }

                // 添加触觉反馈
                this.addHapticFeedback();
            }
        },

        /**
         * 添加触觉反馈
         */
        addHapticFeedback() {
            // 如果设备支持震动反馈
            if (navigator.vibrate) {
                navigator.vibrate(10); // 短震动10ms
            }
        },

        /**
         * 切换录音状态
         */
        toggleRecording() {
            if (this.isRecording) {
                // 停止录音
                this.stopRecording();
            } else {
                // 开始录音
                this.startRecording();
            }
        },

        playAudio(index){
            let pa = this.recordingUrlArr[index]
            let __this = this

            const audioURL = URL.createObjectURL(pa.blob);
            __this.$refs.audioObj.src = audioURL

            __this.$refs.audioObj.onloadeddata = async () => {
                try {
                    await __this.$refs.audioObj.play()
                    console.log('音频自动播放');
                } catch (error) {
                    console.log('自动播放被阻止,需要用户交互');
                }
            };

            // const audioURL = URL.createObjectURL(pa.blob);
            // const audio = document.createElement('audio');
            // audio.controls = true;
            // audio.src = audioURL;
            // document.body.appendChild(audio);
        },
        removeAudio(index){
            this.recordingUrlArr.splice(index , 1)
        },
        getTimes(num){
            const minutes = Math.floor(this.duration / 60);
            const seconds = this.duration % 60;

            return 
        },

        /**
         * 开始录音
         */
        async startRecording() {
            let __this = this

            try {
                // 检查浏览器是否支持录音API
                if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                    __this.mediaStream = await navigator.mediaDevices.getUserMedia({ 
                        audio: {
                            echoCancellation: true,
                            noiseSuppression: true,
                            channelCount: 1,
                            sampleRate: 44100
                        } 
                     });
                    const mediaRecorder = new MediaRecorder(__this.mediaStream,{
                        mimeType: 'audio/webm;codecs=opus'
                    });
                    const chunks = [];
                    
                    mediaRecorder.ondataavailable = e => chunks.push(e.data);
                    mediaRecorder.onstop = () => {
                        const blob = new Blob(chunks, { type: 'audio/webm;codecs=opus' });

                        __this.recordingUrlArr.push({
                            blob: blob,
                            isPlay: false,
                            time: __this.recordingDuration
                        })
                    };
                    
                    mediaRecorder.start();

                    __this.isRecording = true;
                    __this.recordingDuration = 0;
                    utils.toast('开始录音');
                    // 生成音频波形条
                    __this.generateWaveformBars();
                    // 可以在这里添加音频处理逻辑
                    __this.setupAudioProcessing();
                }
            } catch (error) {
                __this.isRecording = false;
                utils.toast('无法访问麦克风,请检查权限设置');
            }
        },

        /**
         * 设置音频处理
         */
        setupAudioProcessing() {
            // 这里可以添加音频分析、可视化等高级功能
            // 暂时使用简单的计时器
            this.recordingTimer = setInterval(() => {
                this.recordingDuration++;
                if (this.recordingDuration >= 60*60) { // 限制最长录音一小时
                    this.stopRecording();
                    utils.toast('录音时间已到最长限制');
                }
            }, 1000);
        },

        /**
         * 停止录音
         */
        stopRecording() {
            this.isRecording = false;
            utils.toast('录音已停止');

            // 清理定时器
            if (this.recordingTimer) {
                clearInterval(this.recordingTimer);
                this.recordingTimer = null;
            }

            // 停止媒体流
            if (this.mediaStream) {
                this.mediaStream.getTracks().forEach(track => track.stop());
                this.mediaStream = null;
            }

            // 清理波形条
            this.cleanupWaveformBars();
        },

        /**
         * 清理波形条
         */
        cleanupWaveformBars() {
            this.$nextTick(() => {
                const waveformContainer = document.querySelector('.voice-waveform');
                if (waveformContainer) {
                    waveformContainer.innerHTML = '';
                }
            });
        },

        /**
         * 表单验证
         */
        validateForm() {
            // 检查是否选择了商机类型
            const selectedTypes = this.businessTypes.filter(t => t.selected);
            if (selectedTypes.length === 0) {
                utils.toast('请选择商机类型');
                return false;
            }

            // 检查是否填写了文字描述或录制了语音
            if (!this.textDescription.trim() && this.recordingDuration === 0) {
                utils.toast('请填写文字描述或录制语音');
                return false;
            }

            // 检查文字描述长度
            if (this.textDescription.trim().length > 500) {
                utils.toast('文字描述不能超过500字');
                return false;
            }

            return true;
        },

        /**
         * 获取选中的商机类型名称
         */
        getSelectedBusinessTypes() {
            return this.businessTypes
                .filter(type => type.selected)
                .map(type => type.name);
        },

        /**
         * 提交商机
         */
        async submitBusiness() {
            // 表单验证
            if (!this.validateForm()) {
                return;
            }

            if (this.isSubmitting) {
                utils.toast('正在提交,请稍候...');
                return;
            }

            this.isSubmitting = true;
            utils.toast('正在提交商机信息...');

            try {
                // 准备提交数据
                const businessData = {
                    // 商机类型
                    businessTypes: this.getSelectedBusinessTypes(),

                    // 描述信息
                    textDescription: this.textDescription.trim(),
                    voiceDuration: this.recordingDuration,

                    // 联系方式
                    contactPhone: this.contactPhone,

                    // 用户信息
                    userId: this.userInfo ? this.userInfo.userId : null,

                    // 提交时间
                    submitTime: new Date().toISOString(),

                    // 设备信息
                    deviceInfo: {
                        userAgent: navigator.userAgent,
                        isMobile: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),
                        platform: navigator.platform,
                        language: navigator.language
                    }
                };

                // 调用API提交
                const result = await this.submitBusinessAPI(businessData);

                if (result.success) {
                    utils.toast('商机提交成功!');
                    // 添加触觉反馈
                    this.addHapticFeedback();

                    // 延迟后重置表单或跳转
                    setTimeout(() => {
                        this.handleSubmitSuccess();
                    }, 2000);
                } else {
                    utils.toast(result.message || '提交失败,请重试');
                }

            } catch (error) {
                console.error('提交商机失败:', error);
                utils.toast('提交失败,请重试');
            } finally {
                this.isSubmitting = false;
            }
        },

        /**
         * 调用API提交商机数据
         */
        async submitBusinessAPI(data) {
            return new Promise((resolve, reject) => {
                // 使用项目中的工具方法进行HTTP请求
                if (typeof publicMethod !== 'undefined') {
                    utils.httpRequest({
                        url: '/api/business/submit',
                        data: data,
                        time: 15000 // 15秒超时
                    }).then(response => {
                        resolve(response);
                    }).catch(error => {
                        reject(error);
                    });

                } else {
                    // 如果没有工具方法,使用fetch作为备用
                    fetch('/api/business/submit', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(data)
                    })
                    .then(response => response.json())
                    .then(response => {
                        resolve(response);
                    })
                    .catch(error => {
                        reject(error);
                    });
                }
            });
        },

        /**
         * 重置表单
         */
        resetForm() {
            // 重置商机类型选择
            this.businessTypes.forEach(type => {
                type.selected = false;
            });

            // 重置文本描述
            this.textDescription = '';

            // 重置录音状态
            if (this.isRecording) {
                this.stopRecording();
            }
            this.recordingDuration = 0;
        },

        /**
         * 格式化录音时长(用于录音时显示)
         */
        formatRecordingTime(seconds) {
            const minutes = Math.floor(seconds / 60);
            const remainingSeconds = seconds % 60;
            return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
        },

        /**
         * 格式化录音时长(用于显示)
         */
        formatRecordingDuration(seconds) {
            if (seconds < 60) {
                return `${seconds}秒`;
            } else {
                const minutes = Math.floor(seconds / 60);
                const remainingSeconds = seconds % 60;
                return `${minutes}${remainingSeconds}秒`;
            }
        },

        /**
         * 生成音频波形条
         */
        generateWaveformBars() {
            this.$nextTick(() => {
                const waveformContainer = document.querySelector('.voice-waveform');
                if (waveformContainer) {
                    // 清空现有内容
                    waveformContainer.innerHTML = '';

                    // 生成50个波形条
                    for (let i = 1; i <= 50; i++) {
                        const bar = document.createElement('div');
                        bar.className = 'voice-waveform-bar';
                        waveformContainer.appendChild(bar);
                    }
                }
            });
        },

        /**
         * 处理页面可见性变化
         */
        handleVisibilityChange() {
            if (document.hidden) {
                // 页面隐藏时的处理
                if (this.isRecording) {
                    // 可以选择是否暂停录音
                    console.log('页面隐藏,录音状态:', this.isRecording);
                }
            } else {
                // 页面显示时的处理
                console.log('页面显示,录音状态:', this.isRecording);
            }
        },

        /**
         * 播放录音
         */
        playRecording() {
            if (this.recordingUrl) {
                utils.toast('播放录音');
                // 这里实现实际的播放逻辑
                console.log('播放录音:', this.recordingUrl);
            }
        },

        /**
         * 删除录音
         */
        deleteRecording() {
            if (confirm('确定要删除这条录音吗?')) {
                utils.toast('录音已删除');
                this.recordingDuration = 0;
                this.recordingUrl = '';

                // 清理波形条显示
                this.cleanupWaveformBars();
            }
        },

        /**
         * 获取波形条高度
         */
        getWaveformHeight(n) {
            // 为30个波形条生成不同的高度,模拟静态波形显示
            const heights = [
                0.12, 0.16, 0.08, 0.20, 0.24, 0.28, 0.32, 0.36, 0.40, 0.44, 0.48,
                0.44, 0.40, 0.36, 0.32, 0.28, 0.24, 0.20, 0.16, 0.12, 0.08, 0.04,
                0.08, 0.12, 0.16, 0.20, 0.24, 0.28, 0.32, 0.36, 0.40, 0.32, 0.24, 0.16, 0.08, 0.04
            ];
            return `${heights[n - 1] || 0.12}rem`;
        },

        /**
         * 清理资源
         */
        cleanup() {
            // 停止录音
            if (this.isRecording) {
                this.stopRecording();
            }

            // 清理定时器
            if (this.recordingTimer) {
                clearInterval(this.recordingTimer);
            }

            // 移除事件监听器
            document.removeEventListener('visibilitychange', this.handleVisibilityChange);
        }
    },

    // 计算属性
    computed: {
        /**
         * 已选择的商机类型数量
         */
        selectedTypesCount() {
            return this.businessTypes.filter(type => type.selected).length;
        },

        /**
         * 是否可以提交
         */
        canSubmit() {
            return this.selectedTypesCount > 0 &&
                   (this.textDescription.trim() || this.recordingDuration > 0) &&
                   !this.isSubmitting;
        },

        /**
         * 格式化的录音时长显示
         */
        formattedRecordingDuration() {
            return this.formatRecordingDuration(this.recordingDuration);
        }
    },

    // 监听器
    watch: {
        /**
         * 监听录音状态变化
         */
        isRecording(newVal) {
            if (newVal) {
                // 开始录音时的处理
                document.title = '正在录音...';
            } else {
                // 停止录音时的处理
                document.title = '商机信息';
            }
        }
    }
})