<template>
  <div class="chatBox" :class="{'active': drawer}" :style="{'bottom':offsetBottom+'px'}">
    <div class="menuTrainListBtn" @click="clickBtn">
      <!-- <i class="el-icon-more" /> -->
      <p style="margin: 0;">会</p>
      <p style="margin: 0;">话</p>
    </div>
    <div class="chat-box-main">
      <div class="chat-box-header">
        <div class="chat-box-header-title">
          <el-input v-if="isShow" v-model="queryMember" size="small" placeholder="请输入搜索人员">
            <el-button slot="append" icon="el-icon-search" />
          </el-input>
        </div>
        <div class="chat-setting" @click="handleSetting()">
          <i class="el-icon-s-tools" />
        </div>
      </div>
      <div v-if="isShow" class="chat-box-content">
        <el-tree
          ref="tree"
          :data="treeData"
          :props="defaultProps"
          node-key="id"
          default-expand-all
          :filter-node-method="filterNode"
          show-checkbox
          style="margin: 10px;overflow-y: auto;height: 100%;margin-right: 0;"
          @check-change="handleCheckChange"
        >
          <span :id="data.id" slot-scope="{ node, data }">
            <span style="font-size: 14px">{{ data.label }}</span>
          </span>
        </el-tree>
      </div>
      <div v-else class="chat-box-content">
        <div class="chatcontent">
          <chat-content ref="chatContent" :chat-content-list="chatContentList" />
          <div v-if="recordSending" class="chat_record_tip">
            <div id="record_progress_bar" :style="'width:'+100/60*seconds+'%'" />
            <div class="record_icon" />
            <div class="record_tip_text">正在录音...</div>
            <div class="record_tip_confirm" @click="stopRecording()">确定</div>
            <div class="record_tip_cancle" @click="cancleRecording()">取消</div>
          </div>
        </div>
        <chat-member-list ref="chatMemberList" :current-member-list="currentMemberList" />
      </div>
      <div class="chat-box-footer">
        <div v-if="isShow">
          <div class="userString">{{ userString }}</div>
          <el-button :loading="loading" size="mini" type="primary" class="chat-box-create-coversite" @click="doCreate">创建会话</el-button>
          <div v-if="scriptTip" class="scriptTip">{{ scriptTip }}</div>
        </div>
        <div v-else>
          <div class="chat-box-footer-tool" />
          <el-button v-if="isQuitShow" size="mini" type="danger" class="chat-box-footer-quit" :loading="loading" @click="quitConversition()">结束会话</el-button>
          <el-button v-if="isStartRecord" class="chat-box-footer-send" size="mini" type="primary" :disabled="recordSending" @click="startRecording()">发送语音</el-button>
          <div v-if="scriptTip" class="scriptTip">{{ scriptTip }}</div>
        </div>
      </div>
    </div>
    <chat-setting ref="chatSetting" :form="form" @setSetting="setSetting" />
    <chat-tooltip ref="chatToolTip" :group="group" :conversition-id="conversitionId" :invite-user-name="inviteUserName" />
  </div>
</template>
<script>
import ChatSetting from './chatSetting';
import ChatMemberList from './chatMemberList';
import ChatContent from './chatContent';
import RecordRTC from 'recordrtc';
import ChatTooltip from './chatTooltip';
// getAllConversition
import {sendSimulationConversition, startConversition, overSimulationConversition} from '@/api/chat';
export default {
    name:'ChatBoxDraft',
    components:{
        ChatSetting,
        ChatMemberList,
        ChatContent,
        ChatTooltip
    },
    props:{
        isShow:{
            type:Boolean,
            required:true
        },
        treeData:{
            type:Array,
            required:true
        },
        group: {
            type: String,
            required: true
        },
        conversitionId:{
            type: String,
            required: true
        },
        currentMemberList:{
            type:Array,
            required: true
        },
        chatContentList:{
            type:Array,
            required: true
        },
        scriptTip:{
            type:String,
            required:true
        },
        isStartRecord:{
            type:Boolean,
            required:true
        },
        isQuitShow:{
            type:Boolean,
            required:true
        },
        inviteUserName:{
            type:String,
            required:true
        },
        offsetBottom:{
            type:Number,
            required:true
        }
    },
    data() {
        return {
            drawer: false,
            bottom:15,
            queryMember:'',
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            form:{
                language:'zh',
                sex:'1'
            },
            recordSending:false,
            recorders: null,
            seconds:0,
            inter:null,
            microphone:null,
            loading:false,
            userString:'',
            memberIdList:[],
            currentMemberListData:[]
        };
    },
    watch:{
        queryMember(val) {
            if (this.$refs.tree) {
                this.$refs.tree.filter(val);
            }
        }
    },
    methods:{
        clickBtn() {
            if (this.drawer) {
                this.drawer = false;
            } else {
                this.drawer = true;
            }
        },
        handleSetting() {
            this.$refs.chatSetting.doShow();
        },
        filterNode(value, data) {
            return data.label.indexOf(value) !== -1;
        },
        handleCheckChange() {
            const memberList = this.$refs.tree.getCheckedNodes();
            this.userString = '';
            this.memberIdList = [];
            if (memberList && memberList.length) {
                memberList.forEach(member => {
                    if (member && !(member.children) && (member.userId == '' || member.userId)) {
                        this.userString += member.memberName + ',';
                        this.memberIdList.push(member.id);
                    }
                });
            }
        },
        setSetting(data) {
            this.form = data;
        },
        // 语音录制开始
        startRecording() {
            this.$emit('setScriptTip', '');
            const that = this;
            if (!this.recordSending && !this.recorders && !this.microphone) {
                this.$refs.chatSetting.doClose();
                const StereoAudioRecorder = RecordRTC.StereoAudioRecorder;
                navigator.getUserMedia(
                    { audio: true } // 只启用音频
                    , function (stream) {
                        that.microphone = stream;
                        that.recorders = new RecordRTC(that.microphone, {
                            type: 'audio',
                            recorderType: StereoAudioRecorder,
                            numberOfAudioChannels: 1,
                            bitsPerSecond:256000,
                            desiredSampRate: 16000
                        });
                        that.recorders.startRecording();
                        that.recordSending = true;
                        that.inter = setInterval(() => {
                            if (that.seconds < 60) {
                                that.seconds++;
                            } else {
                                clearInterval(that.inter);
                            }
                        }, 1000);
                    }, function (error) {
                        switch (error.code || error.name) {
                        case 'PERMISSION_DENIED':
                        case 'PermissionDeniedError':
                            that.$message({
                                showClose: true,
                                message: '用户拒绝提供信息',
                                type: 'error'
                            });
                            break;
                        case 'NOT_SUPPORTED_ERROR':
                        case 'NotSupportedError':
                            that.$message({
                                showClose: true,
                                message: '浏览器不支持硬件设备',
                                type: 'error'
                            });
                            break;
                        case 'MANDATORY_UNSATISFIED_ERROR':
                        case 'MandatoryUnsatisfiedError':
                            that.$message({
                                showClose: true,
                                message: '无法发现指定的硬件设备',
                                type: 'error'
                            });
                            break;
                        default:
                            that.$message({
                                showClose: true,
                                message: '无法打开麦克风',
                                type: 'error'
                            });
                            break;
                        }
                    }
                );
            }
        },
        // 停止录制
        stopRecording() {
            const that = this;
            this.recorders.stopRecording(function(blobURL) {
                const data = URL.createObjectURL(that.recorders.getBlob());
                console.log('--------', data);
                clearInterval(that.inter);
                that.seconds = 0;
                const blob = that.recorders.getBlob();
                const fd = new FormData();
                fd.append('file', blob);
                sendSimulationConversition(that.group, that.conversitionId, fd)
                    .then((data) => {
                    })
                    .catch(error => {
                        console.log(error);
                    });
                if (that.microphone) {
                    that.microphone.stop();
                    that.microphone = null;
                    that.recordSending = false;
                    that.recorders = null;
                }
            });
        },
        cancleRecording() {
            if (this.microphone) {
                clearInterval(this.inter);
                this.seconds = 0;
                this.microphone.stop();
                this.microphone = null;
                this.recordSending = false;
                this.recorders = null;
            }
        },
        doCreate() {
            if (this.memberIdList.length > 0) {
                this.loading = true;
                startConversition(this.group, this.memberIdList).then(resp => {
                    if (resp.data) {
                        this.loading = false;
                        this.memberIdList = [];
                        this.userString = '';
                    }
                }).catch(error=>{
                    this.$message.error(error.code == '3005' ? '创建会话失败:仿真会话成员忙线中！' : '创建会话失败！');
                    this.loading = false;
                    this.dialogVisible = false;
                });
            } else {
                this.userString = '群聊列表为空, 请选择人员';
            }
        },
        quitConversition() {
            this.loading = true;
            overSimulationConversition(this.group, this.conversitionId).then(resp => {
                this.$emit('resetCoversition');
                this.loading = false;
            }).catch(() => {
                this.$message.error('退出会话失败！');
                this.loading = false;
            });
        },
        inviteMember() {
            this.$refs.chatToolTip.doShow();
        }
    }
};
</script>
<style lang="scss" scoped>
.chatBox {
	position: absolute;
    left: 0;
	top: calc((100% - 400px) / 2);
    height: 400px;
	width: 503px;
	transform: translateX(-503px);
	transition: all 0.4s;
	z-index: 9;
	&.active{
		transform: translateX(0px);
	}
}
.menuTrainListBtn {
    background: #fff;
    text-align: center;
    border-radius: 0px 6px 6px 0px;
    position: absolute;
    top: 45%;
    z-index: 2;
	transform: translateX(502px);
    cursor: pointer;
	z-index: 9;
	display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    justify-content: center;
	padding: 7px 4px;
	.el-icon-more{
		font-size: 20px;
		margin-top: 9px;
		transform-origin: 50% 50%;
		transform: rotate(90deg);
		margin-left:0px;
	}
}

.chat-box-header{
    width: 100%;
    height: 40px;
    border-bottom: 1px #dedede solid;
}
.chat-box-header-title{
  font-size: 15px;
  margin-left: 15px;
  display: inline-block;
  margin-top: 4px;
  width: 70%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.chat-box-content{
    width: 100%;
    height: 300px;
    border-bottom: 1px #dedede solid;
    position: relative;
}

.chat-box-footer-quit{
    font-size: 12px;
    padding: 5px 15px;
    color: #fff;
    float: left;
    margin-left: 10px;
    margin-bottom: 10px;
    cursor: pointer;
}
.chatcontent{
    height: 100%;
    width: 362px;
    display: inline-block;
    cursor: auto;
    position: relative;
}

.chat-box-footer{
    display: inline-block;
    width: 100%;
    position: relative;
}

.chat-setting{
    float: right;
    line-height: 40px;
    margin-right: 10px;
    cursor: pointer;
    font-size: 16px;
}
.chat-box-footer-tool{
    width: 100%;
    height: 30px;
}
.chat-box-footer-send{
    font-size: 12px;
    text-align: center;
    float: right;
    margin-right: 10px;
    margin-bottom: 10px;
    cursor: pointer;
    padding: 5px 15px;
}
.chat-box-create-coversite{
    font-size: 12px;
    float: right;
    margin-right: 10px;
    margin-top: 18px;
    cursor: pointer;
    padding: 5px 15px;
}
.minimality {
    float: right;
    line-height: 40px;
    margin-right: 10px;
    cursor: pointer;
    font-size:16px;
}
.chat-box-main{
    position: absolute;
    width: 100%;
    left: 0;
    height: 100%;
    top: 0;
    border-right: 1px #dedede solid;
    z-index: 4;
    background: #fff;
    border-radius: 5px;
    left: 0;
    font-size:0;
}

.chat-box-footer-send.disbled{
    cursor: no-drop;
}

.scriptTip{
    position: absolute;
    width: 260px;
    padding: 10px;
    background: rgb(250, 246, 3);
    right: 7px;
    bottom:45px;
    border-radius: 5px;
    font-size: 14px;
    color: #000000;
    z-index: 2;
}
.scriptTip::after{
    content: '';
    position: absolute;
    width: 0;
    height: 0;
    border-left: 10px solid transparent;
    border-right: 10px solid transparent;
    border-top: 8px solid #faf603;
    right: 16px;
    bottom: -7px;
}

.userString{
    height: 50px;
    width: 409px;
    position: absolute;
    left: 0;
    top: 0;
    padding: 4px 5px;
    overflow-x: auto;
    font-size: 13px;
    line-height: 135%;
    resize: none;
}

#record_progress_bar{
    height: 100%;
    position: absolute;
    background: #bbe5f5;
}
.chat_record_tip{
    height: 28px;
    display: inline-block;
    background: #dfe6ee;
    width: 100%;
    font-size: 13px;
    border-top: 1px #d8dce5 solid;
    position: absolute;
    bottom: 0;
    right: 0;
}
.record_icon{
    display: inline-block;
    width: 8px;
    height: 8px;
    background: #25d825;
    border-radius: 10px;
    left: 7px;
    margin-right: 0px;
    box-shadow: -1px 0px 3px #6d6d6d;
    border: 1px #28d228 solid;
    position: absolute;
    top: 10px;
}
.record_tip_text{
    display: inline-block;
    font-size: 12px;
    margin-left: 3px;
    // padding: 8px 0px 6px 0px;
    position: absolute;
    top: 8px;
    left:20px
}
.record_tip_confirm{
    position: absolute;
    right: 63px;
    padding: 3px 0px 2px 0px;
    border: 1px #a2a5aa solid;
    border-radius: 5px;
    width: 45px;
    text-align: center;
    font-size: 12px;
    top: 4px;
    background: #eeeeee;
    cursor: pointer;
}
.record_tip_cancle{
    position: absolute;
    right: 10px;
    padding: 3px 0px 2px 0px;
    border: 1px #a2a5aa solid;
    border-radius: 5px;
    width: 45px;
    text-align: center;
    font-size: 12px;
    top: 4px;
    background: #eeeeee;
    cursor: pointer;
}

</style>
