<template>
    <div id="dddsc">
        <van-sticky>
            <yd-navbar :title="(name !== 'null' && name) ? name : imei">
                <router-link to="/chat" slot="left">
                    <yd-navbar-back-icon></yd-navbar-back-icon>
                </router-link>
                <router-link to="#" slot="right">
                    <div class="switch-area">
                        <van-switch v-model="deviceAuthorize" active-color="#1989fa" size="0.3rem" @change="setAuthorize"/>
                        <span>开放后台</span>
                    </div>
                </router-link>
            </yd-navbar>
        </van-sticky>


        <van-pull-refresh
        v-model="isLoading"
        success-text="加载成功"
        @refresh="pullLoadMore"
        >
    
        <div class="chatlist chatlist-bottom" ref="chatlist" >
                <ul>
                    <template v-for="(item, index) in audioList">

                        <li class="chat-mine" v-if="item.type==2" :key="item.id">
                            <div class="chat-user">
                                <van-image
                                class="chat-user"
                                round
                                width="1rem"
                                height="1rem"
                                fit="cover"
                                src="https://img01.yzcdn.cn/vant/cat.jpeg"
                                />
                            </div>
                            <div class="time"><cite><i>{{item.created_at}}</i>我</cite></div>
                            <div class="chat-text"  @click.stop="handlePlay(item.file, $event)">
                                <img
                                    style="height: 0.5rem;"
                                    src ="https://rlfd.oss-cn-hangzhou.aliyuncs.com/wxt_school/pause.png"
                                />
                                <span >{{ item.time || 0 }}"</span>
                            </div>
                        </li>
                        <li v-if="item.type==1" :key="item.id" class="chat-counter">
                            <!-- <div class="chat-user"><img src="https://rlfd.oss-cn-hangzhou.aliyuncs.com/wxt_school/student_alarm.png"></div> -->
                                <van-image
                                class="chat-user"
                                round
                                width="1rem"
                                height="1rem"
                                fit="cover"
                                src="https://img01.yzcdn.cn/vant/cat.jpeg"
                                />
                            <div class="time"><cite><i>{{item.created_at}}</i></cite></div>
                            <!-- <div class="chat-text" v-html="replaceFace(item.content)"></div> -->

                            <div class="chat-text"  @click.stop="handlePlay(item.file, $event, item.id, item.type, index)">
                                <img
                                    style="height: 0.5rem;"
                                    src ="https://rlfd.oss-cn-hangzhou.aliyuncs.com/wxt_school/pause.png"
                                />
                                <span >{{ item.time || 0 }}"</span>
                            </div>
                            <span v-if="item.hasread==0" style="color:darkgray;margin-left:2px">未读</span>
                        </li>
                    </template>
                </ul>

        <!-- </yd-pullrefresh> -->
            <!-- </mt-loadmore> -->
            <div style="height:1rem;width:100%"></div>
        </div>

</van-pull-refresh>

        <div class="voice-input">
            <!-- <van-button icon="service-o" plain type="info" size="small" @touchstart.native="startRec" @touchend.native="stopRec">按住发言</van-button>              -->
            <button class="voice-button" @touchstart="startRec($event)" @touchend="stopRec">
                <van-icon size="16" name="service-o" />
                <span class="voice-text">按住发言</span> 
            </button>
            <div class="appen-new" @click="appendNewMsg">
                <van-icon size="14px" name="exchange" />
                <span>最新</span>  
            </div>    
        </div>

        <div class="working-gif" v-show="isRecording">
            <img style="width:200px" src="@/assets/image/recording.gif">
            录音中...
        </div>
    </div>
</template>

<script>
import Vue from 'vue';
import { Button,Cell,CellGroup,Image as VanImage,Icon, PullRefresh,Sticky,Notify, Dialog, Switch } from 'vant';

import Recorder from 'recorder-core-rlian'

//需要使用到的音频格式编码引擎的js文件统统加载进来
// import 'recorder-core-rlian/src/engine/mp3'
// import 'recorder-core-rlian/src/engine/mp3-engine'
import 'recorder-core-rlian/src/engine/wav'



//以上三个也可以合并使用压缩好的recorder.xxx.min.js
//比如 import Recorder from 'recorder-core-rlian/recorder.mp3.min' //已包含recorder-core-rlian和mp3格式支持

//可选的扩展支持项
// import 'recorder-core-rlian/src/extensions/waveview'

Vue.use(Cell);
Vue.use(CellGroup);
Vue.use(VanImage);
Vue.use(Icon);
Vue.use(PullRefresh );
Vue.use(Sticky  );

Vue.use(Button);
Vue.use(Switch);


export default {
    name: 'chatlist',
    watch: {
    },
    data() {
        return {
            imei: '',
            name: '',
            content:'',
            isPlaying: false,
            duration: 5,
            audio: null,

            deviceAuthorize: false,

            isLoading: false,
            audioList: [],
            afterid: '',
            beforeid: '',

            //录音
            rec: null,
            blob: null,
            isRecording: false
        }
    },
    methods: {
        getDeviceInfo(){
            let that= this;
            console.log(that.imei)
            this.$http
            .get("/getDeviceInfoSingle&imei=" + that.imei )
            .then(res => {
            let resp = res.data;

            if(!resp.success){
                that.$dialog.toast({
                    mes:resp.message
                });
                that.deviceAuthorize = !val;
                return;
            }
            let deviceInfo = resp.data

            that.deviceAuthorize = parseInt(deviceInfo.authorize) ? true : false ;
            
            })
            .catch(res => {
                console.log(res);
            });
        },
        setAuthorize(val){
            let that = this;
        
            if(val){
                Dialog.confirm({
                    title: '提醒',
                    message: '开放后台权限后,<span style="color:#1989fa">【管理员和机构运营人员】</span>将被允许<span style="color:red">『查看您与设备的语音』</span>,请谨慎考虑,确认此举是必要的！',
                })
                .then(() => {
                    that.updateDeviceAuthorize(val);
                })
                .catch(() => {
                    that.deviceAuthorize = !val;
                });
            }else{
                that.updateDeviceAuthorize(val);
            }

            

        },
        updateDeviceAuthorize(val){
            let that = this;
            that.$http
            .get("/changeAuthorize&imei=" + that.imei + '&authorize=' + (val ? 1 : 0) )
            .then(res => {
                let resp = res.data;

                if(!resp.success){
                    that.$dialog.toast({
                        mes:resp.message
                    });
                    that.deviceAuthorize = !val;
                    return;
                }
                        
                that.deviceAuthorize = val;
                that.$dialog.toast({
                    mes: '后台权限修改成功'
                });
            
            })
            .catch(res => {
                console.log(res);
                that.$dialog.toast({
                    mes: '权限修改出错,操作失败'
                });
                that.deviceAuthorize = !val;
            });
        },
        getAudioList(way = null){
            let that = this;
            that.$http
            .get("/getAudioListByImei&imei=" + that.$route.params.imei + '&beforeid=' + that.beforeid + '&afterid=' + that.afterid)
            .then(res => {
                let resp = res.data;
                if(!resp.success){
                    that.isLoading = false;
                    Notify( {type: 'primary', message: resp.message});
                    return;
                }
                if(way == 'unshift'){
                    

                    setTimeout(() => {
                        that.isLoading = false;
                        that.audioList = resp.data.concat(that.audioList);
                        // var newHeight=chatlist.scrollHeight;
                        // chatlist.scrollTop=newHeight-oldHeight;
                        // this.scrollToBottom()
                    }, 500);
                }else{
                    that.audioList = that.audioList.concat(resp.data);
                    this.scrollToBottom()
                }
                
                console.log(resp)
            })
            .catch(res => {
                console.log(res);
            });
        },
        updateAudioStatus(id, index){
            if(!id){
                return
            }
            let that = this;
            that.$http
            .get("/updateAudioStatus&vid=" + id)
            .then(res => {
                let resp = res.data;
                console.log(res)
                if(!resp.success){
                    this.$dialog.toast({
                        mes:resp.message
                    });
                    return;
                }
                
                let vdata = that.audioList[index];
                vdata.hasread = 1;
                Vue.set(that.audioList, index, vdata);

            })
            .catch(res => {
                console.log(res);
            });
        },
        pullLoadMore(){
            var chatlist = document.getElementsByClassName('chatlist')[0];
            var oldHeight=chatlist.scrollHeight;


            if(this.audioList.length === 0){
                this.afterid = '';
                this.beforeid = '';
                this.getAudioList();
                return;
            }
            this.afterid = '';
            this.beforeid = this.audioList[0].id;
            this.getAudioList('unshift');
        },
        appendNewMsg(){
            if(this.audioList.length === 0){
                this.afterid = '';
                this.beforeid = '';
                this.getAudioList();
                return;
            }
            this.beforeid = '';
            this.afterid = this.audioList[ (this.audioList.length - 1) ].id;
            this.getAudioList('append');

            this.scrollToBottom();
        },
        scrollToBottom:function(){
            setTimeout(function(){
                var chatlistDND = document.documentElement;
                var chatlistNODND = document.body;
                chatlistDND.scrollTop=chatlistDND.scrollHeight;
                chatlistNODND.scrollTop=chatlistNODND.scrollHeight;
                console.log('dddd')
            },500);
            // this.$nextTick(() =>{
            //     // console.log this.$refs.chatlist.scrollHeight;
            //     this.$refs.chatlist.scrollTop = 860
            // })
            // let page = document.getElementsByClassName('chatlist')[0]
            // page.scrollIntoView()

            // // 动画效果
            // page.scrollIntoView({ behavior: 'smooth' })

            
        },

        initRecorder(){
            this.rec =Recorder({ //本配置参数请参考下面的文档，有详细介绍
                type:"wav",sampleRate:8000,bitRate:128 //mp3格式，指定采样率hz、比特率kbps，其他参数使用默认配置；注意：是数字的参数必须提供数字，不要用字符串；需要使用的type类型，需提前把格式支持文件加载进来，比如使用wav格式需要提前加载wav.js编码引擎
                ,onProcess:function(buffers,powerLevel,bufferDuration,bufferSampleRate,newBufferIdx,asyncEnd){
                    //录音实时回调，大约1秒调用12次本回调
                    //可利用extensions/waveview.js扩展实时绘制波形
                    //可利用extensions/sonic.js扩展实时变速变调，此扩展计算量巨大，onProcess需要返回true开启异步模式
                }
            });

    //var dialog=createDelayDialog(); 我们可以选择性的弹一个对话框：为了防止移动端浏览器存在第三种情况：用户忽略，并且（或者国产系统UC系）浏览器没有任何回调，此处demo省略了弹窗的代码

        },
        startRec(event){
            event.preventDefault()//清除默认事件
            let that = this;
            
            if(!this.rec){
                this.initRecorder()
            }
            this.rec.open(function(){//打开麦克风授权获得相关资源
                //dialog&&dialog.Cancel(); 如果开启了弹框，此处需要取消
                //rec.start() 此处可以立即开始录音，但不建议这样编写，因为open是一个延迟漫长的操作，通过两次用户操作来分别调用open和start是推荐的最佳流程
                console.log('录音已打开')
                that.isRecording = true;
                that.rec.start()
                // success&&success();
            },function(msg,isUserNotAllow){//用户拒绝未授权或不支持
                //dialog&&dialog.Cancel(); 如果开启了弹框，此处需要取消
                console.log((isUserNotAllow?"UserNotAllow，":"")+"无法录音:"+msg);
                that.isRecording = false;

                if(isUserNotAllow){
                    Dialog({ message: (isUserNotAllow?"UserNotAllow，":"")+"无法录音:"+msg +', 建议重进公众号重试以允许授权，若没有授权提示，建议升级手机系统版本以获得支持'});
                }else{
                     Dialog({ message: "无法录音:"+msg});
                }
                
            });

        },
        stopRec(){
            let that = this;
            that.isRecording = false;
            this.rec.stop(function(blob,duration){
                console.log(blob,(window.URL||webkitURL).createObjectURL(blob),"时长:"+duration+"ms");
                that.rec.close();//释放录音资源，当然可以不释放，后面可以连续调用start；但不释放时系统或浏览器会一直提示在录音，最佳操作是录完就close掉
                that.rec=null;

                that.blob = blob;
                that.upload()

            },function(msg){
                console.log("录音失败:"+msg);
                that.rec.close();//可以通过stop方法的第3个参数来自动调用close
                that.rec=null;
            });
        },
        upload(){
            let that= this;
            var form=new FormData();
            let blob = that.blob, imei = that.$route.params.imei;
            let fileName = 'rec-' + imei + '-' + new Date().getTime() + '.wav';
            console.log(fileName)
            form.append("upfile",blob,fileName);
            form.append('imei', imei);
            form.append('userid', localStorage.getItem("userid"));
            console.log(form);
                    //上传
            that.$http({
                method: "post",
                url: "/saveParentUploadAudio",
                data: form,
                headers: { 'content-type': 'multipart/form-data' },
                })
            .then(({ data }) => {
                that.appendNewMsg()
            });
        },
        //播放相关
        handlePlay(src, e, id, type, index) {
            console.log(e, 'event')
            let el = e.currentTarget.firstChild
            let that = this;

            if(this.currentMsg){
                this.currentMsg.src = 'https://rlfd.oss-cn-hangzhou.aliyuncs.com/wxt_school/pause.png';
            }
            
            el.src = 'https://rlfd.oss-cn-hangzhou.aliyuncs.com/wxt_school/playing.gif';
            this.currentMsg = el;

            if(!src){
                this.$dialog.toast({
                    mes: '检测不到音频源'
                });
                return;
            }

            if(this.audio.src != src){
                this.audio.src=  src
                if(type == 1 && id){
                    that.updateAudioStatus(id, index)
                }
                
            }

            if(this.audio.ended || this.audio.paused){
                this.audio.load()
                this.audio.play()
                this.isPlaying = true
            }else{
                this.audio.pause()
                this.isPlaying = false
            }
            
            
        },
        handlePause() {
            this.audio.pause()
            this.isPlaying = false;
        },

    },
    mounted:function(){
        // this.initRequest()
        this.initRecorder()
        
        // this.scrollToBottom()
        this.imei = this.$route.params.imei;
        this.name = this.$route.params.name;
        this.getAudioList();
        this.getDeviceInfo();
        this.audio = new Audio();



        let that = this;
        this.audio.oncanplay =  function(){
            console.log(that.audio.duration, 'audio时长')
            that.duration =  parseInt(that.audio.duration)
        }
        this.audio.onended =  function(){
            // that.isPlaying = false;
            if(that.currentMsg){
                that.currentMsg.src = 'https://rlfd.oss-cn-hangzhou.aliyuncs.com/wxt_school/pause.png';
            }
            
        }
    }
}
</script>
<style scoped>
.switch-area{
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    color: gray;
    font-size: 12px;
}
    .voice-input{
        position: fixed;
        bottom: 0;
        height: 1rem;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        width: 100%;
        background: white;
        display: flex;
        justify-content: center;
        align-items: center;
            user-select: none;
    }
    .voice-button{
        height: 32px;
        padding: 0 8px;
        font-size: 12px;
        border: 1px solid #1989fa;
        color: #1989fa;
        display: flex;
        align-items: center;
        justify-content: center;
        user-select: none;
        border-radius: 2px;
    }
    .voice-text{
        -webkit-touch-callout: none;
        -webkit-user-select: none;
        -khtml-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
    }

    .working-gif{
        position: fixed;
        width:200px;
        margin:auto;
        left: 0;
        right: 0;
        bottom: 2rem;
        text-align: center;
        font-size: 16px;
        color: gray;
    }
    .chatlist {
        overflow-y: scroll;
        overflow-x: hidden;
        padding: 10px;
    }
    .appen-new{
        position: absolute;
        right: 0.5rem;
        border-radius: 4px;
        border: solid #1989fa 1px;
        padding: 2px;
        display: flex;
        align-items: center;
        color: #1989fa;
    }
    
    .chatlist-bottom {
        bottom: 48px;
    }
    
    .chatlist-bottom-collapse {
        bottom: 198px;
    }
    
    .chatlist ul {
        min-height: 300px;
    }
    
    .chatlist ul .chat-mine {
        text-align: right;
        padding-left: 0;
        padding-right: 60px;
    }
    .chatlist ul .chat-counter{
        text-align: left;
    }
    
    .chatlist ul li {
        position: relative;
        /*font-size: 0;*/
        margin-bottom: 10px;
        padding-left: 60px;
        min-height: 68px;
    }
    
    .chat-mine .chat-user {
        left: auto;
        right: 3px;
    }
    
    .chat-user {
        position: absolute;
        left: 3px;
    }
    
    .chat-text,
    .chat-user {
        display: inline-block;
        vertical-align: top;
        /*font-size: 14px;*/
    }
    
    .chat-user img {
        width: 40px;
        height: 40px;
        border-radius: 100%;
    }
    
    .time {
        width: 100%;
    }
    
    cite {
        left: auto;
        right: 60px;
        text-align: right;
    }
    
    cite {
        font-style: normal;
        line-height: 24px;
        font-size: 12px;
        white-space: nowrap;
        color: #999;
        text-align: left;
    }
    
    cite i {
        font-style: normal;
        padding-left: 5px;
        padding-right: 5px;
        font-size: 12px;
    }
    
    .chat-mine .chat-text {
        margin-left: 0;
        text-align: left;
        background-color: #33DF83;
        color: #fff;
    }
    
    .chat-text {
        position: relative;
        line-height: 22px;
        /*margin-top: 25px;*/
        padding: 10px 15px;
        background-color: #2196f3;
        border-radius: 3px;
        color: #fff;
        word-break: break-all;
        max-width: 462px\9;
    }
    
    .chat-text,
    .chat-user {
        display: inline-block;
        vertical-align: top;
        font-size: 14px;
    }
    
    .chat-text img {
        max-width: 100%;
        vertical-align: middle;
    }
    
    .chat-user {
        position: absolute;
        left: 3px;
    }
    
    .chat-text:after {
        content: '';
        position: absolute;
        left: -10px;
        top: 15px;
        width: 0;
        height: 0;
        border-style: solid dashed dashed;
        border-color: #2196f3 transparent transparent;
        overflow: hidden;
        border-width: 10px;
    }
    
    .chat-mine .chat-text:after {
        left: auto;
        right: -10px;
        border-top-color: #33DF83;
    }
    
    .foot {
        width: 100%;
        min-height: 48px;
        position: fixed;
        bottom: 0px;
        left: 0px;
        background-color: #F8F8F8;
    }
    
    .foot .con {
        position: absolute;
        left: 66px;
        right: 40px;
    }
    
    .foot .btn-plus {
        width: 28px;
        padding: 9px 3px;
        position: absolute;
        left: 0px;
        border-left: 1px solid #d9d9d9;
    }
    
    .foot .btn-plus i {
        font-size: 2em;
        color: #ccc;
    }
    
    .foot .btn-face {
        width: 28px;
        padding: 9px 3px 9px 0px;
        position: absolute;
        left: 35px;
        /*border-right: 1px solid #d9d9d9;*/
    }
    
    .foot .btn-face i {
        font-size: 2em;
        color: #d9d9d9;
    }
    
    .foot .selbox {
        height: 150px;
        margin-top: 48px;
        border-top: 1px solid #d9d9d9;
    }
    
    .show {
        display: block;
    }
    
    .hide {
        display: none;
    }
    
    .face-box {
        /* position: absolute; */
        /* top: 48px; */
        /* left: 0px; */
        /* right: 0px; */
        /* bottom: 0px; */
        padding: 15px 15px 0px 15px;
        overflow: hidden;
        width: 290px;
        margin: 0px auto;
        height: 135px;
    }
    
    .face-box li {
        width: 30px;
        float: left;
        padding: 6px 10px 0px 8px;
    }
    
    .btn {
        display: inline-block;
        vertical-align: top;
        font-size: 14px;
        line-height: 32px;
        margin-left: 5px;
        padding: 0 6px;
        background-color: #33DF83;
        color: #fff;
        border-radius: 3px;
    }
    
    .btn-send {
        position: absolute;
        right: 0px;
        top: 8px;
    }

.fl-buttomright-button{
  position: fixed;
  bottom: 24px;
  right: 16px;
  display: flex;
  flex-direction: column;
  border-radius: 50%;
  height: 54px;
  width: 54px;
  background-color: #2196f3;
  box-shadow:0 0 6px gray ;
  font-size: 14px;
  justify-content: center;
  align-items: center;
  color: white;
  padding: 12px;
}

</style>