<template>
    <div class="intelligentSchScrView" v-if="whetherShow">

        <div class="intelligentSchScrView_leftView">
            <!-- 人工调度 -->
            <div class="intelligentSchScrView_leftView1">
                <div class="intelligentSchScrView_leftView_title">人工调度</div>
                <div class="intelligentSchScrView_leftView_content">
                    <div class="voiceAppContent_1">
                        <div>选择车队：</div>
                        <el-select v-model="selectCarFleet" placeholder="请选择车队" style="width:14vw;" @change="toSearchFn()">
                            <el-option v-for="(item,index) in carFleetData" :key="index" :label="item.name" :value="item.name" style="font-size:18px;"></el-option>
                        </el-select>
                    </div>
                    <div class="voiceAppContent_2">
                        <div class="voiceAppContent_2_title">选择车辆</div>
                        <div class="voiceAppContent_2_content">
                            <el-checkbox-group v-model="selectCarRadioArray">
                                <el-checkbox v-for="(item,index) in carsInforData" :label="item" :key="index" style="margin-top:7px;">
                                    <div style="width:12vw;margin-left:1.7vw;text-align: center;">{{item.number}}</div>
                                </el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </div>
                    <div class="voiceAppContent_3">
                        <div class="voiceAppContent_2_title">已选中车辆</div>
                        <div class="voiceAppContent_3_content">
                            <div v-for="(item,index) in selectCarRadioArray" :key="index" class="voiceAppContent_3_content_selectCar">
                                <div>{{item.number}}</div>
                                <div style="width:20px;height:20px;background-color: rgb(4,112,171);text-align: center;font-size:30px;line-height:20px;cursor: pointer;" @click="cancelSelect(index)">
                                    <span>×</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="voiceAppContent_4">
                        <el-button type="primary" @click="toNoticeFn('广播')">{{guangbo1}}</el-button>
                        <el-button type="primary" @click="toNoticeFn('紧急通知')">{{jinzhitongzhi1}}</el-button>
                        <el-button type="primary" @click="toNoticeFn('通话')">{{tonghua1}}</el-button>
                        <el-button type="primary" @click="todispatchChange()">{{dispatchBtnTitle}}</el-button>
                    </div>
                </div>
            </div>
            <!-- 近期通知列表-->
            <div  class="intelligentSchScrView_leftView2">
                <div class="intelligentSchScrView_leftView_title">近期通知列表</div>
                <div class="intelligentSchScrView_leftView_content">
                    <div class="rolling">
                        <div class="table-box">
                            <dl>
                                <dt>
                                    <div>通知类型</div>
                                    <div>开始时间</div>
                                    <div>录音回放</div>
                                </dt>
                                <dd v-for="(item,index) in recentNoticeData" :key="index">
                                    <div>{{item.noticeClass}}</div>
                                    <div>{{item.createTime}}</div>
                                    <div style="cursor: pointer;text-decoration:underline;" @click="selectSituation(item)">录音播放</div>
                                </dd>
                            </dl>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="intelligentSchScrView_rightView">
            <!-- 智能调度信息 -->
            <div>
                <div class="intelligentSchScrView_rightView_title">智能调度信息</div>
                <div class="intelligentSchScrView_rightView_content">
                    <div class="intelligentSchScrView_rightView_content_1_top">
                        <div>
                            <img src="../../../../assets/images/cutGraph/zhengzaijinxing1.png">
                            <div style="color:#F8D909;text-align: center;">
                                <div style="font-size:16px;">正在派送中</div>
                                <div style="font-size:22px;">{{dispatchLoadingNum}}</div>
                            </div>
                        </div>
                        <div>
                            <img src="../../../../assets/images/cutGraph/wanchengle1.png">
                            <div style="color:#01EDF7;text-align: center;">
                                <div style="font-size:16px;">已经完成的</div>
                                <div style="font-size:22px;">{{dispatchFinishNum}}</div>
                            </div>
                        </div>
                    </div>
                    <div class="intelligentSchScrView_rightView_content_1_bottom">
                        <div class="intelligentSchScrView_rightView_content_1_bottom_rolling">
                            <div class="table-box">
                                <dl>
                                    <dt>
                                        <div>车牌号</div>
                                        <div>起点</div>
                                        <div>调度时间</div>
                                        <div>状态</div>
                                        <div>目的地</div>
                                    </dt>
                                    <dd v-for="(item,index) in dispatchDetailsList" :key="index">
                                        <div>{{item.carNo}}</div>
                                        <div>{{item.startAdr}}</div>
                                        <div>{{item.createTime}}</div>
                                        <div>{{item.status == 0 ? '接单中' : item.status == 1 ? '已完成' : '未完成'}}</div>
                                        <div>{{item.destination}}</div>
                                    </dd>
                                </dl>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 车辆区域分布-->
            <div>
                <div class="intelligentSchScrView_rightView_title">车辆区域分布</div>
                <div class="intelligentSchScrView_rightView_content">
                    <div id="carsAreaDistributionView"></div>
                </div>
            </div>
            <!-- 各装点车铲比 -->
            <div>
                <div class="intelligentSchScrView_rightView_title">各装点车铲比</div>
                <div class="intelligentSchScrView_rightView_content">
                    <div id="carsProportionView"></div>
                </div>
            </div>
        </div>

        <!-- 语音所需内容，隐藏无需展示 -->
		<div class="main" style="display:none;">
				<slot name="top"></slot>

				<div class="mainBox">
					<div class="btns">
						<div>
							<button @click="recOpen">打开录音,请求权限</button>
							<button @click="recClose">关闭录音,释放资源</button>
						</div>
						
						<button @click="recStart">录制</button>
						<button @click="recStop" style="margin-right:80px">停止</button>
						
						<span style="display: inline-block;">
							<button @click="recPause">暂停</button>
							<button @click="recResume">继续</button>
						</span>
						<span style="display: inline-block;">
							<button @click="recPlayLast">播放</button>
							<button @click="recUploadLast">上传</button>
						</span>
					</div>
				</div>

				<div class="mainBox">
					<div style="height:100px;width:300px;border:1px solid #ccc;box-sizing: border-box;display:inline-block;vertical-align:bottom" class="ctrlProcessWave"></div>
					<div style="height:40px;width:300px;display:inline-block;background:#999;position:relative;vertical-align:bottom">
						<div class="ctrlProcessX" style="height:40px;background:#0B1;position:absolute;" :style="{width:powerLevel+'%'}"></div>
						<div class="ctrlProcessT" style="padding-left:50px; line-height:40px; position: relative;">{{ duration+"/"+powerLevel }}</div>
					</div>
				</div>
				
				<div class="mainBox">
					<audio ref="LogAudioPlayer" style="width:100%"></audio>

					<div class="mainLog">
						
					</div>
				</div>

				<div v-if="recOpenDialogShow" style="z-index:99999;width:100%;height:100%;top:0;left:0;position:fixed;background:rgba(0,0,0,0.3);">
					
				</div>

				<slot name="bottom"></slot>
		</div>
        
        <audio controls currentTime autoplay :src='srcUrl' style="display:none;"></audio>

        <!-- 语音发起dialog -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="recStart" style="font-size:18px;" :disabled='tonghuadisabled'>录制语音</el-button>
                <el-button type="primary" @click="recStop" style="font-size:18px;">结束语音</el-button>
                <el-button type="primary" @click="recUploadLast" style="font-size:18px;" :disabled='tonghuadisabled'>上传语音</el-button>
                <el-button @click="dialogVisible = false" style="font-size:18px;" :disabled='tonghuadisabled'>取 消</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
import { Tools, HttpReq, Dates} from '@/assets/js/common.js';
import * as echarts from 'echarts';
//加载必须要的core，demo简化起见采用的直接加载类库，实际使用时应当采用异步按需加载
import Recorder from 'recorder-core'
// //需要使用到的音频格式编码引擎的js文件统统加载进来，这些引擎文件会比较大
import 'recorder-core/src/engine/mp3'
import 'recorder-core/src/engine/mp3-engine'
// //可选的扩展
import 'recorder-core/src/extensions/waveview'

export default {
    data() {
		return {
            intelligentSchedulTimer:null,
            heartbeatTimer:null,
            websocket: null,
			whetherShow:false,
            selectCarFleet:'', //搜索对应车队
			carFleetData:[], //车队信息
			carsInforData:[], //车辆信息
			selectCarRadioArray:[], //多选选中车辆
            recentNoticeData:[], //近期通知列表
            dispatchLoadingNum:0, //智能调度进行中
            dispatchFinishNum:0, //智能调度已完成
            dispatchDetailsList:[], //智能调度情况表
            dispatchBtnTitle:'人工调度',
            dispatchBtnTitle1:'人工调度',
            //车辆区域分布Echarts
            carsAreaDistributionData:{
                name:[],
                kache:[],
                chanche:[],
                qitache:[],
            },
            //各装点车铲比Echarts
            carsProportionData:[
                [28, 3, '采区一'],
                [50, 7, '采区二'],
                [22, 0, '卸区一'],
                [2, 0, '卸区二'],
            ],
            guangbo1:'广播',
            jinzhitongzhi1:'紧急通知',
            tonghua1:'通话',
            dialogTitle:'',
            dialogTitle1:'',
            dialogVisible:false,
            tonghuadisabled:false,
            srcUrl:null,
            resultBlob:null,

            type:"mp3",
            bitRate:16,
            sampleRate:16000,
            rec:0,
            duration:0,
            powerLevel:0,
            recOpenDialogShow:0,
            logs:[],

		}
	},
	methods: {
        //获取总数据
		loadData(text){
            if(text == true){
                this.whetherShow = true;
                this.srcUrl = null;
                this.selectCarFleet = '';
                this.selectCarRadioArray = [];

                this.$nextTick(()=>{
                    //车队信息
                    HttpReq.truckDispatching.carFleetQuery({size:9999}).then((res) => {
                        if(res.code == 200){
                            this.carFleetData = res.data.content;
                        };
                    })
                    //车辆信息
                    this.loadData2();
                    //近期通知列表
                    HttpReq.truckDispatching.recentNoticeQuery({size:50,sort:'id,desc'}).then((res) => {
                        if(res.code == 200){
                            this.recentNoticeData = res.data.content;
                            let flag0 = [];
                            this.recentNoticeData.forEach((item)=>{
                                if(item.flag == 0){
                                    flag0.push(item);
                                }
                            })
                            if(flag0.length == 0){
                                this.dispatchBtnTitle = '人工调度';
                            }else{
                                this.dispatchBtnTitle = flag0[0].noticeClass;
                            }
                        };
                    })
                    //智能调度情况
                    HttpReq.truckDispatching.getLargeScreen1({size:100,sort:'createTime,desc'}).then((res) => {
                        this.dispatchDetailsList = res;
                    })
                    //获取智能调度情况中的进行中数量
                    HttpReq.truckDispatching.getLargeScreenUnder1({size:9999}).then((res) => {
                        if(res.length == 0){
                            this.dispatchLoadingNum = 0;
                        }else{
                            this.dispatchLoadingNum = res[0].under;
                        }
                    })
                    //获取智能调度情况中的已完成数量
                    HttpReq.truckDispatching.getLargeScreenRound1({size:9999}).then((res) => {
                        if(res.length == 0){
                            this.dispatchFinishNum = 0;
                        }else{
                            this.dispatchFinishNum = res[0].round;
                        }
                    })
                    //车辆区域分布Echarts
                    HttpReq.truckDispatching.getLargeScreenfenbu1({size:9999}).then((res) => {
                        if(res.code == 200){
                            let name = [];
                            let kache = [];
                            let chanche = [];
                            let qitache = [];
                            res.data.forEach((item,index)=>{
                                name.push(item.name);
                                kache.push(item.truck);
                                chanche.push(item.shovel);
                                qitache.push(item.other);
                            })
                            this.carsAreaDistributionData.name = name;
                            this.carsAreaDistributionData.kache = kache;
                            this.carsAreaDistributionData.chanche = chanche;
                            this.carsAreaDistributionData.qitache = qitache;
                            this.carsAreaDistributionEcharts();
                        }
                    })
                    //各装点车铲比Echarts
                    HttpReq.truckDispatching.getLargeScreenchechanbi1({size:9999}).then((res) => {
                        if(res.code == 200){
                            this.carsProportionData = res.data;
                            this.carsProportionEcharts();
                        }
                    })

                    //定时器
                    this.intelligentSchedulTimer = setInterval(() => {
                        //车队信息
                        HttpReq.truckDispatching.carFleetQuery({size:9999}).then((res) => {
                            if(res.code == 200){
                                this.carFleetData = res.data.content;
                            };
                        })
                        //车辆信息
                        this.loadData2();
                        //近期通知列表
                        HttpReq.truckDispatching.recentNoticeQuery({size:50,sort:'id,desc'}).then((res) => {
                            if(res.code == 200){
                                this.recentNoticeData = res.data.content;
                                let flag0 = [];
                                this.recentNoticeData.forEach((item)=>{
                                    if(item.flag == 0){
                                        flag0.push(item);
                                    }
                                })
                                if(flag0.length == 0){
                                    this.dispatchBtnTitle = '人工调度';
                                }else{
                                    this.dispatchBtnTitle = flag0[0].noticeClass;
                                }
                                
                            };
                        })
                        //智能调度情况
                        HttpReq.truckDispatching.getLargeScreen1({size:100,sort:'createTime,desc'}).then((res) => {
                            this.dispatchDetailsList = res;
                        })
                        //获取智能调度情况中的进行中数量
                        HttpReq.truckDispatching.getLargeScreenUnder1({size:9999}).then((res) => {
                            if(res.length == 0){
                                this.dispatchLoadingNum = 0;
                            }else{
                                this.dispatchLoadingNum = res[0].under;
                            }
                        })
                        //获取智能调度情况中的已完成数量
                        HttpReq.truckDispatching.getLargeScreenRound1({size:9999}).then((res) => {
                            if(res.length == 0){
                                this.dispatchFinishNum = 0;
                            }else{
                                this.dispatchFinishNum = res[0].round;
                            }
                        })
                        //车辆区域分布Echarts
                        HttpReq.truckDispatching.getLargeScreenfenbu1({size:9999}).then((res) => {
                            if(res.code == 200){
                                let name = [];
                                let kache = [];
                                let chanche = [];
                                let qitache = [];
                                res.data.forEach((item,index)=>{
                                    name.push(item.name);
                                    kache.push(item.truck);
                                    chanche.push(item.shovel);
                                    qitache.push(item.other);
                                })
                                this.carsAreaDistributionData.name = name;
                                this.carsAreaDistributionData.kache = kache;
                                this.carsAreaDistributionData.chanche = chanche;
                                this.carsAreaDistributionData.qitache = qitache;
                                this.carsAreaDistributionEcharts();
                            }
                        })
                        //各装点车铲比Echarts
                        HttpReq.truckDispatching.getLargeScreenchechanbi1({size:9999}).then((res) => {
                            if(res.code == 200){
                                this.carsProportionData = res.data;
                                this.carsProportionEcharts();
                            }
                        })
                    }, 10000)

                })
                //开启录音
                this.recOpen();
            }else{
                if(this.intelligentSchedulTimer) {
                    clearInterval(this.intelligentSchedulTimer);
                }
                //关闭录音
                this.recClose();
                this.whetherShow = false;
                this.srcUrl = null;
            }
        },
        //获取车辆信息
		loadData2() {
			let query = {};
			query.size = 9999;
			query.page = 0;
			query.road = this.selectCarFleet;
			//车辆
			HttpReq.truckDispatching.carInformationQuery(query).then((res) => {
				if(res.code == 200){
					this.carsInforData = res.data.content;
				};
			})
		},
        //页面刚进入时开启长连接
		loadData3(){
			this.initWebSocket();
			this.heartbeatTimer = setInterval(() => {
				this.reconnect();
			}, 20000)
		},
        //关闭心跳以及关闭长连接
		xintiaoCloseFn(){
			//页面销毁时关闭长连接
        	this.websocketclose();
			//关闭心跳
			if(this.heartbeatTimer) {
				clearInterval(this.heartbeatTimer);
			}
		},
        //车辆多选取消
		cancelSelect(index){
			let handleArray = [...this.selectCarRadioArray];
			handleArray.splice(index,1);
			this.selectCarRadioArray = handleArray;
		},
        //搜索车辆
        toSearchFn(){
            this.loadData2();
        },
        //发起通知
        toNoticeFn(text){
            this.dialogTitle = '发起' + text;
            this.dialogTitle1 = text;
            this.dialogVisible = true;
        },
        //人工调度和智能调度切换
        todispatchChange(){
            if(this.dispatchBtnTitle == '人工调度'){
                this.dispatchBtnTitle = '智能调度';
                this.dispatchBtnTitle1 = '人工调度';
            }else{
                this.dispatchBtnTitle = '人工调度';
                this.dispatchBtnTitle1 = '智能调度';
            }
            HttpReq.truckDispatching.recentNoticeAdd({noticeClass:this.dispatchBtnTitle1,flag:0}).then((res) => {
				if(res.code == 200){
					this.$notify({
						title: this.dispatchBtnTitle1 + '发起成功!',
						type: 'success',
						duration: 2500
					});
					//近期通知列表
                    HttpReq.truckDispatching.recentNoticeQuery({size:50,sort:'id,desc',}).then((res) => {
                        if(res.code == 200){
                            this.recentNoticeData = res.data.content;
                        };
                    })
                    //发起添加调度类型
                    HttpReq.truckDispatching.screenDispatchWayAdd({dispatcher:this.dispatchBtnTitle1}).then((res) => { })
				}else{
					this.$notify({
						title: res.msg,
						type: 'error',
						duration: 2500
					})
				}
			}).catch(function(error) { });
        },
        //播放录音
        playSoundRecordingFn(id){
            console.log(id);
        },
        //车辆区域分布Echarts
        carsAreaDistributionEcharts(){
            echarts.init(document.getElementById('carsAreaDistributionView')).dispose();
            var myChart = echarts.init(document.getElementById('carsAreaDistributionView'));
            var option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow' 
                    }
                },
                legend: {
                    textStyle:{
                        color: 'white',
                        fontSize:16,
                    }
                },
                grid: {
                    top: '13%',
                    left: '1%',
                    right: '1%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: this.carsAreaDistributionData.name,
                    axisLabel: {
                        show: true,
                        textStyle: {
                            color: '#A6F6F9',
                            fontSize:14,
                        }
                    },
                    axisLine: {
                        lineStyle: {
                            color: '#A6F6F9',
                            width: 1
                        }
                    },
                },
                yAxis: {
                    type: 'value',
                    axisLabel: {
                        show: true,
                        textStyle: {
                            color: '#A6F6F9',
                            fontSize:14,
                        }
                    },
                    axisLine: {
                        lineStyle: {
                            color: '#A6F6F9',
                            width: 0
                        }
                    },
                },
                series: [
                    {
                        name: '卡车',
                        type: 'bar',
                        stack: 'total',
                        label: {
                            show: true
                        },
                        data: this.carsAreaDistributionData.kache,
                        barWidth: 30,
                        itemStyle: {
							color: '#2BBFA8'
						},
                    },
                    {
                        name: '铲车',
                        type: 'bar',
                        stack: 'total',
                        label: {
                            show: true
                        },
                        data: this.carsAreaDistributionData.chanche,
                        barWidth: 35,
                        itemStyle: {
							color: '#DB972D'
						},
                    },
                    {
                        name: '其他车辆',
                        type: 'bar',
                        stack: 'total',
                        label: {
                            show: true
                        },
                        data: this.carsAreaDistributionData.qitache,
                        barWidth: 35,
                        itemStyle: {
							color: '#158DFD'
						},
                    }
                ]
            };
            option && myChart.setOption(option);
        },
        //各装点车铲比Echarts
        carsProportionEcharts(){
            echarts.init(document.getElementById('carsProportionView')).dispose();
            var myChart = echarts.init(document.getElementById('carsProportionView'));
            var option;

            const data = [this.carsProportionData];
            option = {
                grid: {
                    top:'15%',
                    left: '5%',
                    right: '8%',
                    bottom: '9%',
                    containLabel: true
                },
                xAxis: {
                    name: '铲',
                    nameTextStyle: { fontSize: 14 },
                    splitLine: {
                        show: false,
                        lineStyle: {
                            type: 'dashed'
                        }
                    },
                    axisLabel: {
                        show: true,
                        textStyle: {
                            color: '#A6F6F9',
                            fontSize:14,
                        },
                    },
                    axisLine: {
                        lineStyle: {
                            color: '#A6F6F9',
                            width: 1
                        }
                    },
                },
                yAxis: {
                    name: '卡车',
                    nameTextStyle: { fontSize: 14 },
                    splitLine: {
                        lineStyle: {
                            type: 'dashed'
                        }
                    },
                    scale: true,
                    axisLabel: {
                        show: true,
                        textStyle: {
                            color: '#A6F6F9',
                            fontSize:14,
                        }
                    },
                    axisLine: {
                        lineStyle: {
                            color: '#A6F6F9',
                            width: 0
                        }
                    },
                },
                series: [
                    {
                        data: data[0],
                        type: 'scatter',
                        symbolSize: 15,
                        emphasis: {
                            focus: 'series',
                            label: {
                                show: true,
                                formatter: function (param) {
                                    return param.data[2];
                                },
                                position: 'top',
                                fontSize:16,
                            }
                        },
                        itemStyle: {
                            color: '#4BF3F9',
                        }
                    }
                ]
            };
            option && myChart.setOption(option);
        },

        //初始化weosocket 
        initWebSocket(){
            //const wsuri = "ws://114.116.108.246:81/websocket/socketServer?userId="+userId;//连接地址，可加参数
            const wsuri = process.env.VUE_APP_WS_API + "/" + 'pcBigScreen';
            this.websocket = new WebSocket(wsuri); 
            this.websocket.onopen = this.websocketonopen;
            this.websocket.onerror = this.websocketonerror;
            this.websocket.onmessage = this.websocketonmessage; 
            this.websocket.onclose = this.websocketclose;
            this.websocketonmessage();
        },
        //WebSocket连接成功
        websocketonopen() {
            console.log("WebSocket连接成功");
        },
        //WebSocket连接错误
        websocketonerror(e) { 
            console.log("WebSocket连接发生错误");
        },
        //WebSocket数据接收 
        websocketonmessage(e){ 
            console.log("e",e);
			if(e == undefined){
				return
			}else{
				let obj1 = JSON.parse(e.data);
                HttpReq.truckDispatching.recentNoticeAdd({noticeClass:obj1.fromUserId,flag:1,videoContent:obj1.contentText}).then((res) => {
                	if(res.code == 200){
                		//近期通知列表
                        HttpReq.truckDispatching.recentNoticeQuery({size:50,sort:'id,desc',}).then((res) => {
                            if(res.code == 200){
                                this.recentNoticeData = res.data.content;
                            };
                        })
                	}else{
                		this.$notify({
                			title: res.msg,
                			type: 'error',
                			duration: 2500
                		})
                	}
                }).catch(function(error) { });
			}  
        }, 
        //WebSocket数据发送 
        websocketsend(agentData){
            this.websocket.send(agentData); 
        }, 
        //WebSocket关闭 
        websocketclose(e){
            console.log("connection closed (" + e.code + ")"); 
        },
        //WebSocket重连
		reconnect(){
			var This=this;
			if (this.websocket.readyState === 1) { // that.websock.readyState = 1 表示连接成功，可以立即发送信息
				This.websocketonmessage();
			} else if (this.websocket.readyState === 0) { // 表示正在连接，设置300ms后发送信息
				setTimeout(function () {
					This.websocketonmessage();
				}, 300);
			} else { // 连接未创建或者创建失败，则重新创建连接，并设置500ms后发送信息
				This.initWebSocket();
				setTimeout(function () {
					This.websocketonmessage();
				}, 500);
			}
		},

        recOpen:function(){
            var This=this;
            var rec=this.rec=Recorder({
                type:This.type
                ,bitRate:This.bitRate
                ,sampleRate:This.sampleRate
                ,onProcess:function(buffers,powerLevel,duration,sampleRate){
                    This.duration=duration;
                    This.powerLevel=powerLevel;

                    This.wave.input(buffers[buffers.length-1],powerLevel,sampleRate);
                }
            });

            This.dialogInt=setTimeout(function(){//定时8秒后打开弹窗，用于监测浏览器没有发起权限请求的情况
                This.showDialog();
            },8000);

            rec.open(function(){
                This.dialogCancel();
                This.reclog("已打开:"+This.type+" "+This.sampleRate+"hz "+This.bitRate+"kbps",2);
                
                This.wave=Recorder.WaveView({elem:".ctrlProcessWave"});
            },function(msg,isUserNotAllow){
                This.dialogCancel();
                This.reclog((isUserNotAllow?"UserNotAllow，":"")+"打开失败："+msg,1);
            });

            This.waitDialogClickFn=function(){
                This.dialogCancel();
                This.reclog("打开失败：权限请求被忽略，用户主动点击的弹窗",1);
            };
        },
		recClose:function(){
            var rec=this.rec;
            this.rec=null;
			if(rec){
				rec.close();
				this.reclog("已关闭");
			}else{
				this.reclog("未打开录音",1);
			};
		},
        recStart:function(){
			
            if(!this.rec||!Recorder.IsOpen()){
                //this.reclog("未打开录音",1);
				this.recOpen()
                //return;
            }
            this.rec.start();

            var set=this.rec.set;
            this.reclog("录制中："+set.type+" "+set.sampleRate+"hz "+set.bitRate+"kbps");
			this.$notify({
				title: '录制中！',
				type: 'success',
				duration: 5000
			});
            this.tonghuadisabled = true;
			
        },
		recPause:function(){
			if(this.rec&&Recorder.IsOpen()){
				this.rec.pause();
			}else{
				this.reclog("未打开录音",1);
			};
		},
		recResume:function(){
			if(this.rec&&Recorder.IsOpen()){
				this.rec.resume();
			}else{
				this.reclog("未打开录音",1);
			};
		},
        recStop:function(){
            if(!(this.rec&&Recorder.IsOpen())){
                This.reclog("未打开录音",1);
				This.$notify({
					title: '未打开录音！',
					type: 'warning',
					duration: 2500
				});
                return;
            }
			
            var This=this;
            var rec=This.rec;
            rec.stop(function(blob,duration){
                This.reclog("已录制:","",{
                    blob:blob,
                    duration:duration,
                    rec:rec
                });
				This.$notify({
					title: '已录制！',
					type: 'success',
					duration: 2500
				});
            },function(s){
				This.$notify({
					title: '录音失败,'+s,
					type: 'warning',
					duration: 2500
				});
                This.reclog("录音失败："+s,1);
            });
			this.recOpen();
            this.tonghuadisabled = false;
        },
		

		recPlayLast:function(){
			if(!this.recLogLast){
				this.reclog("请先录音，然后停止后再播放",1);
				return;
			};
			
			this.recplay(this.recLogLast.idx);
		},
		recUploadLast:function(){
			let carNumberString = '';
			this.selectCarRadioArray.forEach((item,index)=>{
				carNumberString = carNumberString + item.number + ';';
			})
			carNumberString = carNumberString + 'pcBigScreen';
			this.carAllNumberString = carNumberString;

			var This=this;
			if(!this.recLogLast){
				this.reclog("请先录音，然后停止后再上传",1);
				This.$notify({
					title: '请先录音，然后停止后再上传！',
					type: 'warning',
					duration: 2500
				});
				return;
			};
			
			var blob=this.recLogLast.res.blob;
			this.blobToDataURI(blob);

			/***方式一：将blob文件转成base64纯文本编码 ***/
			var reader=new FileReader();
			reader.onloadend=function(){
				var postData="";
				// postData+="mime="+encodeURIComponent(blob.type);//告诉后端，这个录音是什么格式的，可能前后端都固定的mp3可以不用写
				// postData+="&upfile_b64="+encodeURIComponent((/.+;\s*base64\s*,\s*(.+)$/i.exec(reader.result)||[])[1]) //录音文件内容，后端进行base64解码成二进制
				//postData = btoa(reader.result); //录音文件内容
				postData = This.resultBlob; //录音文件内容

				//发送语音数据
				if (This.websocket.readyState == 1) { // that.websock.readyState = 1 表示连接成功，可以立即发送信息
					This.websocketsend(`{"toUserId":"${This.carAllNumberString}","contentText":"${postData}","fromUserId":"${This.dialogTitle1}"}`);
					This.$notify({
						title: '上传成功！',
						type: 'success',
						duration: 2500
					});
				} else if (This.websocket.readyState == 0) { // 表示正在连接，设置300ms后发送信息
					setTimeout(function () {
						This.websocketsend(`{"toUserId":"${This.carAllNumberString}","contentText":"${postData}","fromUserId":"${This.dialogTitle1}"}`);
						This.$notify({
							title: '上传成功！',
							type: 'success',
							duration: 2500
						});
					}, 300);
				} else { // 连接未创建或者创建失败，则重新创建连接，并设置500ms后发送信息
					This.initWebSocket();
					setTimeout(function () {
						This.websocketsend(`{"toUserId":"${This.carAllNumberString}","contentText":"${postData}","fromUserId":"${This.dialogTitle1}"}`);
						This.$notify({
							title: '上传成功！',
							type: 'success',
							duration: 2500
						});
					}, 500);
				}
			};
			reader.readAsDataURL(blob);


			/***方式二：使用FormData用multipart/form-data表单上传文件***/
			// let form = new FormData();
			// form.append("upfile",blob,"recorder.mp3"); //和普通form表单并无二致，后端接收到upfile参数的文件，文件名为recorder.mp3
			// console.log('form',form);
            
            this.dialogVisible = false;

		},


        reclog:function(msg,color,res){
			var obj={
                idx:this.logs.length
                ,msg:msg
                ,color:color
                ,res:res

                ,playMsg:""
                ,down:0
                ,down64Val:""
            };
			if(res&&res.blob){
				this.recLogLast=obj;
			};
            this.logs.splice(0,0,obj);
        },
        recplay:function(idx){
            var This=this;
            var o=this.logs[this.logs.length-idx-1];
            o.play=(o.play||0)+1;
            var logmsg=function(msg){
                o.playMsg='<span style="color:green">'+o.play+'</span> '+This.getTime()+" "+msg;
            };
            logmsg("");

            var audio=this.$refs.LogAudioPlayer;
            audio.controls=true;
            if(!(audio.ended || audio.paused)){
                audio.pause();
            };
            audio.onerror=function(e){
                logmsg('<span style="color:red">播放失败['+audio.error.code+']'+audio.error.message+'</span>');
            };
            audio.src=(window.URL||webkitURL).createObjectURL(o.res.blob);
            audio.play();
        },
        recdown:function(idx){
            var This=this;
            var o=this.logs[this.logs.length-idx-1];
            o.down=(o.down||0)+1;

            o=o.res;
            var name="rec-"+o.duration+"ms-"+(o.rec.set.bitRate||"-")+"kbps-"+(o.rec.set.sampleRate||"-")+"hz."+(o.rec.set.type||(/\w+$/.exec(o.blob.type)||[])[0]||"unknown");
            var downA=document.createElement("A");
            downA.href=(window.URL||webkitURL).createObjectURL(o.blob);
            downA.download=name;
            downA.click();
        },
        recdown64:function(idx){
            var This=this;
            var o=this.logs[this.logs.length-idx-1];
            var reader = new FileReader();
            reader.onloadend = function() {
                o.down64Val=reader.result;
            };
            reader.readAsDataURL(o.res.blob);
        },
        getTime:function(){
            var now=new Date();
            var t=("0"+now.getHours()).substr(-2)
                +":"+("0"+now.getMinutes()).substr(-2)
                +":"+("0"+now.getSeconds()).substr(-2);
            return t;
        },
        intp:function(s,len){
            s=s==null?"-":s+"";
            if(s.length>=len)return s;
            return ("_______"+s).substr(-len);
        },


        showDialog:function(){
            //我们可以选择性的弹一个对话框：为了防止移动端浏览器存在第三种情况：用户忽略，并且（或者国产系统UC系）浏览器没有任何回调
            if(!/mobile/i.test(navigator.userAgent)){
                return;//只在移动端开启没有权限请求的检测
            };
            this.recOpenDialogShow=1;
        },
        dialogCancel:function(){
            clearTimeout(this.dialogInt);
            this.recOpenDialogShow=0;
        },
        waitDialogClick:function(){
            this.dialogCancel();
            this.waitDialogClickFn();
        },


        //解析base64编码到blob流
		dataURItoBlob(base64Data) {
			//console.log(base64Data);
			var byteString;
			if(base64Data.split(',')[0].indexOf('base64') >= 0)
				byteString = atob(base64Data.split(',')[1]);//base64 解码
			else{
				byteString = unescape(base64Data.split(',')[1]);
			}
			var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];//mime类型 -- image/png

			// var arrayBuffer = new ArrayBuffer(byteString.length); //创建缓冲数组
			// var ia = new Uint8Array(arrayBuffer);//创建视图
			var ia = new Uint8Array(byteString.length);//创建视图
			for(var i = 0; i < byteString.length; i++) {
				ia[i] = byteString.charCodeAt(i);
			}
			var blob = new Blob([ia], {
				type: mimeString
			});
			return blob;
		},
		//blob流转base64编码
		blobToDataURI(blob) {
			let that = this;
			var reader = new FileReader();
		    reader.readAsDataURL(blob);
			reader.onload = function(){
				that.resultBlob = reader.result;
			}
		},
        //播放语音
		selectSituation(item){
            //注意base64的最后面中括号和引号是不转译的
			let bstr = this.dataURItoBlob(item.videoContent);
			const reader1 = new FileReader();
			reader1.readAsArrayBuffer(bstr);
			reader1.onload = (e) => {
				const bufer = e.srcElement.result;
				const blob = this.addWavHeader(bufer, 16000, 16, 1);
				this.srcUrl = (window.URL||webkitURL).createObjectURL(blob);
			};
		},
		addWavHeader(samples, sampleRateTmp, sampleBits, channelCount) {
			const dataLength = samples.byteLength;
			/* 新的buffer类，预留44bytes的heaer空间 */
			const buffer = new ArrayBuffer(44 + dataLength);
			/* 转为 Dataview, 利用API来填充字节 */
			const view = new DataView(buffer);
			let offset = 0;
			/* ChunkID, 4 bytes,  资源交换文件标识符 */
			this.writeString(view, offset, 'RIFF'); offset += 4;
			/* ChunkSize, 4 bytes, 下个地址开始到文件尾总字节数,即文件大小-8 */
			view.setUint32(offset, /* 32 */ 36 + dataLength, true); offset += 4;
			/* Format, 4 bytes, WAV文件标志 */
			this.writeString(view, offset, 'WAVE'); offset += 4;
			/* Subchunk1 ID, 4 bytes, 波形格式标志 */
			this.writeString(view, offset, 'fmt '); offset += 4;
			/* Subchunk1 Size, 4 bytes, 过滤字节,一般为 0x10 = 16 */
			view.setUint32(offset, 16, true); offset += 4;
			/* Audio Format, 2 bytes, 格式类别 (PCM形式采样数据) */
			view.setUint16(offset, 1, true); offset += 2;
			/* Num Channels, 2 bytes,  通道数 */
			view.setUint16(offset, channelCount, true); offset += 2;
			/* SampleRate, 4 bytes, 采样率,每秒样本数,表示每个通道的播放速度 */
			view.setUint32(offset, sampleRateTmp, true); offset += 4;
			/* ByteRate, 4 bytes, 波形数据传输率 (每秒平均字节数) 通道数×每秒数据位数×每样本数据位/8 */
			view.setUint32(offset, sampleRateTmp * channelCount * (sampleBits / 8), true); offset += 4;
			/* BlockAlign, 2 bytes, 快数据调整数 采样一次占用字节数 通道数×每样本的数据位数/8 */
			view.setUint16(offset, channelCount * (sampleBits / 8), true); offset += 2;
			/* BitsPerSample, 2 bytes, 每样本数据位数 */
			view.setUint16(offset, sampleBits, true); offset += 2;
			/* Subchunk2 ID, 4 bytes, 数据标识符 */
			this.writeString(view, offset, 'data'); offset += 4;
			/* Subchunk2 Size, 4 bytes, 采样数据总数,即数据总大小-44 */
			view.setUint32(offset, dataLength, true); offset += 4;
			if (sampleBits === 16) {
				this.floatTo16BitPCM(view, samples);
			} else if (sampleBits === 8) {
				this.floatTo8BitPCM(view, samples);
			} else {
				this.floatTo32BitPCM(view, samples);
			}
			return new Blob([view], { type: 'audio/wav' });
		},
		writeString(view, offset, string) {
			for (let i = 0; i < string.length; i += 1) {
				view.setUint8(offset + i, string.charCodeAt(i));
			}
		},
		floatTo32BitPCM(output, input) {
			const oinput = new Int32Array(input);
			let newoffset = 44;
			for (let i = 0; i < oinput.length; i += 1, newoffset += 4) {
				output.setInt32(newoffset, oinput[i], true);
			}
		},
		floatTo16BitPCM(output, input) {
			const oinput = new Int16Array(input);
			let newoffset = 44;
			for (let i = 0; i < oinput.length; i += 1, newoffset += 2) {
				output.setInt16(newoffset, oinput[i], true);
			}
		},
		floatTo8BitPCM(output, input) {
			const oinput = new Int8Array(input);
			let newoffset = 44;
			for (let i = 0; i < oinput.length; i += 1, newoffset += 1) {
				output.setInt8(newoffset, oinput[i], true);
			}
    	},

	},
    beforeDestroy() {
        if(this.intelligentSchedulTimer) {
			clearInterval(this.intelligentSchedulTimer);
		}
    },
}
</script>

<style scoped>
.intelligentSchScrView{
    position: absolute;
    z-index: 1;
    width: 100%;
    height: 100%;
    overflow: hidden;
    display: flex;
    justify-content: space-between;
}
.intelligentSchScrView_leftView{
    height: 100%;
    width: 20%;
}
.intelligentSchScrView_rightView{
    height: 100%;
    width: 20%;
}
.intelligentSchScrView_leftView1{
    width: 100%;
    height: 64vh;
    /* background:no-repeat center center url('~@/assets/images/cutGraph/yuanjianjuxing1.png');
	background-size:100% 100%; */
    background-color: rgba(32,42,67,0.8);
    padding: 5px 7px;
    box-sizing: border-box;
    overflow: hidden;
}
.intelligentSchScrView_leftView2{
    width: 100%;
    height: 32vh;
    /* background:no-repeat center center url('~@/assets/images/cutGraph/yuanjianjuxing1.png');
	background-size:100% 100%; */
    background-color: rgba(32,42,67,0.8);
    padding: 5px 7px;
    box-sizing: border-box;
    overflow: hidden;
}
.intelligentSchScrView_rightView>div{
    width: 100%;
    height: 31.8vh;
    /* background:no-repeat center center url('~@/assets/images/cutGraph/yuanjianjuxing1.png');
	background-size:100% 100%; */
    background-color: rgba(32,42,67,0.8);
    padding: 5px 7px;
    box-sizing: border-box;
    overflow: hidden;
}
.intelligentSchScrView_leftView_title,.intelligentSchScrView_rightView_title{
    margin-bottom: 5px;
    width: 100%;
    height: 3.5vh;
    background:no-repeat center center url('~@/assets/images/cutGraph/biaoti1.png');
	background-size:100% 100%;
    padding-left: 10px;
    box-sizing: border-box;
    font-size: 18px;
    line-height: 3.5vh;
    color: #FAFAFB;
    letter-spacing: 1px;
    text-shadow: 1px 1px 1px #92CBFF;
}
.intelligentSchScrView_leftView_content,.intelligentSchScrView_rightView_content{
    width: 100%;
}
/* .table-box{
	margin-top: -10px;
} */
dl{
	display:table;
	width:100%;
}
dt{
	margin-top: 20px;
	display:table-row;
	background-color: #274088;
}
dt>div{
	display:table-cell;
	padding:7px 3px;
	font-size: 16px;
	font-weight: 500;
	color: rgb(24,228,240);
}
dd{
	display:table-row;
}
dd>div{
	display:table-cell;
	padding:5px 3px;
	font-size: 15px;
	color: #A6F6F9;
}
.rolling{
    text-align: center;
	height: 25vh;
	overflow-y:auto;
    scrollbar-width: none;
}
.rolling::-webkit-scrollbar {
  display: none;
}

.voiceAppContent_1{
	display: flex;
	justify-content: space-around;
}
.voiceAppContent_1>div{
	height: 40px;
	line-height: 40px;
	color: rgb(24,228,240);
	font-size: 16px;
    font-weight: 600;
}
.voiceAppContent_2{
    width: 100%;
    height: 27vh;
    border: 2px solid rgb(24,228,240);
    border-radius: 10px;
}
.voiceAppContent_2_title{
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
	background-color: rgb(25,41,94);
	height: 3vh;
	line-height: 3vh;
	color: rgb(24,228,240);
	display: flex;
	justify-content: space-around;
	font-size: 16px;
}
.voiceAppContent_2_content{
	height: 23vh;
	width: 100%;
	overflow-y:auto;
	padding: 0px 10px;
	box-sizing: border-box;
}
.voiceAppContent_2_content::-webkit-scrollbar {
  /*滚动条整体样式*/
  width : 8px;  /*高宽分别对应横竖滚动条的尺寸*/
  height: 1px;
}
.voiceAppContent_2_content::-webkit-scrollbar-thumb {
	/*滚动条里面小方块*/
	border-radius   : 10px;
	background-color: #274088;
	background-image: -webkit-linear-gradient(
		45deg,
		rgba(255, 255, 255, 0.2) 25%,
		transparent 25%,
		transparent 50%,
		rgba(255, 255, 255, 0.2) 50%,
		rgba(255, 255, 255, 0.2) 75%,
		transparent 75%,
		transparent
	);
}
.voiceAppContent_2_content::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
	box-shadow   : inset 0 0 5px rgba(0, 0, 0, 0.2);
	background   : #ededed;
	border-radius: 10px;
}
.el-checkbox__label{
	vertical-align: -3px;
}
.el-checkbox__label>div{
	display: inline-block;
	color: rgb(24,228,240);
	font-size: 17px;
}
.el-checkbox{
	display: block;
}
.el-checkbox__inner{
	width: 30px !important;
	height: 30px !important;
}
.el-checkbox__input .el-checkbox__inner::after {
    border: 2px solid #fff;
    box-sizing: content-box;
    content: "";
    border-left: 0;
    border-top: 0;
    height: 12px;
	width: 5px;
    position: absolute;
    top: 1px;
	left: 8px;
    transform: rotate(45deg) scaleY(1);
}
.voiceAppContent_3{
    margin-top: 1vh;
    width: 100%;
    height: 18vh;
    border: 2px solid rgb(24,228,240);
    border-radius: 10px;
}
.voiceAppContent_3_content{
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    align-content:flex-start;
	height: 14vh;
	width: 100%;
	overflow-y:auto;
	padding: 0px 10px;
	box-sizing: border-box;
}
.voiceAppContent_3_content::-webkit-scrollbar {
  /*滚动条整体样式*/
  width : 8px;  /*高宽分别对应横竖滚动条的尺寸*/
  height: 1px;
}
.voiceAppContent_3_content::-webkit-scrollbar-thumb {
	/*滚动条里面小方块*/
	border-radius   : 10px;
	background-color: #274088;
	background-image: -webkit-linear-gradient(
		45deg,
		rgba(255, 255, 255, 0.2) 25%,
		transparent 25%,
		transparent 50%,
		rgba(255, 255, 255, 0.2) 50%,
		rgba(255, 255, 255, 0.2) 75%,
		transparent 75%,
		transparent
	);
}
.voiceAppContent_3_content::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
	box-shadow   : inset 0 0 5px rgba(0, 0, 0, 0.2);
	background   : #ededed;
	border-radius: 10px;
}
.voiceAppContent_3_content_selectCar{
    width: 45%;
	margin-top: 5px;
	color: rgb(24,228,240);
	font-size: 16px;
	display: flex;
	justify-content: space-between;
}
.voiceAppContent_3_content_selectCar>div{
	height: 20px;
	line-height: 20px;
    font-size: 18px;
}
.voiceAppContent_4{
    margin-top: 1vh;
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    align-content:flex-start;
}
.voiceAppContent_4 button{
    margin: 0px 2vw 10px;
    width: 25%;
    font-size: 14px;
}
.intelligentSchScrView_rightView_content_1_top{
    width: 100%;
    display: flex;
    justify-content: space-between;
}
.intelligentSchScrView_rightView_content_1_top>div{
    width: 49%;
    height: 6vh;
    background:no-repeat center center url('~@/assets/images/cutGraph/sijirenshu1.png');
	background-size:100% 100%;
    display: flex;
    align-items: center;
    justify-content: space-evenly;
}
.intelligentSchScrView_rightView_content_1_bottom{
    width: 100%;
    height: 21.5vh;
}
.intelligentSchScrView_rightView_content_1_bottom_rolling{
    text-align: center;
	height: 21.5vh;
	overflow-y:auto;
    scrollbar-width: none;
}
.intelligentSchScrView_rightView_content_1_bottom_rolling::-webkit-scrollbar {
    display: none;
}
#carsAreaDistributionView{
    width: 19vw;
    height: 27.5vh;
}
#carsProportionView{
    width: 19vw;
    height: 27.5vh;
}
</style>