<template>
    <div class="chat-room common-container">
        <!-- 顶部 -->
        <div class="chat-room-head">
            <div class="head-title">
                <span>监控中心</span>
            </div>
            <div class="head-btn parent">
                <el-button
                    type="danger"
                    class="vertical-center exitBtn"
                    size="medium"
                    @click="goBack()"
                >退出</el-button>
                <!--<el-switch
                    class="vertical-center head-switch"
                    v-model="busy"
                    active-color="#13ce66"
                    inactive-color="#ccc"
                    active-text="示忙"
                ></el-switch>-->
            </div>
        </div>
        <!-- 主体内容部分 -->
        <div class="chat-room-body">
            <!-- 聊天框 -->
            <div class="body-centre">
                <div class="centre-top">
                    <div class="centre-top-title">{{name}}-<span v-if="dataTable == 1">问诊</span><span v-else>出诊</span></div>
                    <el-scrollbar style="background-color:#fff; height: 400px;" ref="scrollbar">
                        <div class="centre-top-content clearfix">
                            <div>
                                <button type="button" class="btn-history" v-if="isShowHistory" id="btnhistory" @click="showHistoryDesc($event)">查看历史记录</button>
                            </div>
                            <div
                                class="chat-records"
                                v-for="(item,index) in chatList"
                                :key="index"
                                :class="item.fromUser === customerServiceId ? 'reverse' : 'row' "
                            >
                                <div class="chat-records-icon">
                                    <el-image
                                        :src="item.avatarUrl | pathPipe"
                                        style="width:35px;height:35px"
                                        fit="cover"
                                    ></el-image>
                                </div>
                                <div class="chat-records-content" v-if="(item.msg.substr(item.msg.lastIndexOf('.')+1)!='jpg') && (item.msg.substr(item.msg.lastIndexOf('.')+1)!='png')">{{item.msg}}</div>                                
                                <div class="chat-records-content" v-else>
                                    <span @click="imgOpen(item.msg)" style="cursor:pointer;">
                                        <el-image :src="item.msg | pathPipe" style="width:100px;height:100px;">
                                        </el-image>
                                    </span>
                                </div>
                            </div>
                        </div>
                    </el-scrollbar>
                </div>
                <div class="centre-bottom">
                    <div class="bottom-top">
                   <!-- <i class="el-icon-setting"></i>
                        <i class="el-icon-warning-outline"></i>
                        <i class="el-icon-remove-outline"></i>
                        <i class="el-icon-circle-check"></i> -->
                    </div>
                    <div class="bottom-text clearfix">
                        <el-input
                            type="textarea"
                            resize="none"
                            placeholder="请输入内容..."
                            v-model="content"
                        ></el-input>
                        <el-button
                            type="success"
                            class="fr send"
                            size="medium"
                            @click="sendMessage()"
                        >发送</el-button>
                    </div>
                </div>
            </div>
            <!-- 右边聊天成员击专家成员-->
            <div class="body-rignt">
                <div class="member">
                    <div class="member-head">聊天成员（{{this.memberList.length || 0}}人）</div>
                    <div class="member-box">
                        <el-scrollbar>
                            <div
                                class="membei-list"
                                v-for="(item,index) in memberList"
                                :key="index"
                            >
                                <!-- <div class="circle" :class="item.flag === true?'active':'inactive'"></div> -->
                                <div class="membei-icon">
                                    <el-image
                                        :src="item.avatarUrl | pathPipe"
                                        style="width:43px;height:43px"
                                        fit="cover"
                                    ></el-image>
                                </div>
                                <div class="member-people">
                                    <div class="people-name">{{item.name}}</div>
                                    <div class="people-time">{{item.createTime | formatTimePipe}}</div>
                                </div>
                            </div>
                        </el-scrollbar>
                    </div>
                </div>
                <div class="expert-list-bigbox">
                    <div class="expert-title">专家列表</div>
                    <el-scrollbar class="expert-scrollbar">
                        <div class="expert-list">
                            <el-scrollbar>
                                <div
                                    class="membei-list pointer"
                                    v-for="(item,index) in expertList"
                                    :key="index"
                                >
                                    <div class="left-side">
                                        <div style="margin-top:20px;">
                                            <i
                                                class="el-icon-success"
                                                :class="item.userId === checkId?'check-active':'check-inactive'"
                                                @click="selectExpert(item)"
                                            ></i>
                                        </div>
                                        <div class="membei-icon">
                                            <el-image
                                                :src="item.avatarUrl | pathPipe"
                                                style="width:43px;height:43px"
                                                fit="cover"
                                            ></el-image>
                                        </div>
                                        <div class="member-people">
                                            <div class="people-name txt-ovehid">
                                                <span>{{item.name}}</span>
                                                <span class="expert-label">
                                                    <span v-if="item.platformInvitedFlag !== 0">普通专家</span>
                                                    <span v-if="item.platformInvitedFlag === 0">特邀专家</span>
                                                </span>
                                                <span class="expert-level">
                                                    <span v-if="item.expertLevel === 1">一级</span>
                                                    <span v-if="item.expertLevel === 2">二级</span>
                                                    <span v-if="item.expertLevel === 3">三级</span>
                                                    <span v-if="item.expertLevel === 4">四级</span>
                                                    <span v-if="item.expertLevel === 5">五级</span>
                                                </span>
                                            </div>
                                            <div
                                                class="people-time"
                                            >{{item.createTime | formatTimePipe}}</div>
                                            <div class="people-phone">{{item.mobile}}</div>
                                        </div>
                                    </div>
                                    <div class="member-people-btn">
                                        <el-button
                                            type="primary"
                                            class
                                            size="mini"
                                            disabled
                                            @click="callExpert(item)"
                                        >呼叫</el-button>
                                    </div>
                                </div>
                            </el-scrollbar>
                        </div>
                    </el-scrollbar>
                    <div class="Invite-experts clearfix">
                        <el-button
                            type="success"
                            class="fr Invite-experts-btn"
                            size="medium"
                            @click="inviteExpert()"
                        >邀请专家</el-button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import { webSocketUrl } from '../../../../../config';
import { queryLiftCasesList, queryChatHistoryList, invitationExpert, queryMsgHistoryList } from '@/apps/mobile/api/monitoring-center/index';
import { queryAllExpert } from '@/apps/mobile/api/expert/index';
import { isArray, chatUnique, chatUnique2 } from '@/apps//mobile/utils/util';
export default {
    data() {
        return {
            id: null, // 诊单id
            sessionId: null, // 房间id
            customerServiceId: null, // 平台客服id
            expertId: null, // 专家id
            statuz: null, // 诊单状态
            busy: false,
            masterList: [],
            memberList: [],
            expertList: [],
            chatList: [],
            content: '',
            page: {
                pageNum: 1,
                pageSize: 500,
                sort: {
                    order: 'desc',
                    orderBy: 'create_time',
                },
            },
            chatPage: {
                pageNum: 1,
                pageSize: 500,
            },
            checkId: -1,
            name: null,
            dataTable: null,
            $ws: null,
            timer: '',
            isShowHistory: true
        };
    },
    created() {
        this.id = this.$route.query.id;
        this.name = this.$route.query.name;
        this.sessionId = this.$route.query.sessionId;
        this.customerServiceId = this.$route.query.customerServiceId;
        this.dataTable = this.$route.query.dataTable;
        // this.queryChatHistoryData();
        this.queryExpertData();
        if (!this.id) {
            this.queryLiftCaseData();
            console.log('NoId...');
        }
    },
    mounted() {
        this.initWebSocket();
    },
    beforeDestroy() {
      clearInterval(this.timer);
    },
    methods: {
        imgOpen(item) {
            window.open(item);
        },
        // 诊单---------------------------------------------------------
        queryLiftCaseData() {
            let obj = {
                ...this.page,
                type: 'BACKQUERY',
                sessionId: this.sessionId,
                // customerServiceId: this.customerServiceId,
            };
            queryLiftCasesList(obj)
                .then(res => {
                    if (res.data && res.data.records && res.data.records.length > 0) {
                        this.id = res.data.records[0].id;
                    }
                })
                .catch();
        },
        // 聊天开始-------------------------------------------------------
        initWebSocket() {
            if (window.WebSocket) {
                this.$ws = new WebSocket(webSocketUrl);
                this.$ws.onopen = this.wsOpen;
                this.$ws.onclose = this.wsClose;
                this.$ws.onmessage = this.wsMessage;
                this.$ws.onerror = this.wsError;
            } else {
                this.$message.warning('浏览器暂不支持WebSocket服务');
            }
        },
        wsOpen(e) {
            console.log('WebSocket连接成功...........');
            this.initSeeionLogin();
            this.initLogin();
            this.timer = setInterval(this.initLoopLogin, 10000);
        },
        wsClose: function(e) {
            console.log('WebSocket连接关闭...........');
            clearInterval(this.timer);
        },
        wsError: function(e) {
            console.log('WebSocket连接出现错误............');
        },
        wsMessage: function(e) {
            let msgData = JSON.parse(e.data);
            console.log('...消息...', msgData);
            if (msgData && msgData.cmd === 'INITROOM') {
                let msgs = JSON.parse(msgData.msg);
                if (msgs && msgs.length > 0) {
                    this.chatList = msgs;
                }
            } else if (msgData && msgData.cmd === 'CHAT') {
                this.content = '';
                this.chatList.push(msgData);
                if (this.chatList && this.chatList.length > 0) {
                    this.keepChattingTop();
                }
            } else {
            }
        },
        initLogin() {
            let obj = {};
            // obj.cmd = 'LOGINALL';
            obj.cmd = 'INITROOM';
            obj.type = 1;
            obj.avatarUrl = JSON.parse(sessionStorage.getItem('avatarUrl'));
            obj.time = new Date().getTime();
            obj.fromUser = this.customerServiceId;
            obj.userId = this.customerServiceId;
            obj.name = '管理员';
            obj.sessionid = this.sessionId;
            obj.msg = '管理员进入该房间了！';
            this.$ws.send(JSON.stringify(obj));
        },
        initSeeionLogin() {
            let obj = {};
            obj.cmd = 'LOGINALL';
            obj.type = 1;
            obj.avatarUrl = JSON.parse(sessionStorage.getItem('avatarUrl'));
            obj.time = new Date().getTime();
            obj.fromUser = this.customerServiceId;
            obj.userId = this.customerServiceId;
            obj.name = '管理员';
            obj.sessionid = this.sessionId;
            obj.msg = '管理员进入该房间了！';
            this.$ws.send(JSON.stringify(obj));
        },
        initLoopLogin() {
            let obj = {};
            obj.cmd = 'LOOP';
            obj.userId = this.customerServiceId;
            this.$ws.send(JSON.stringify(obj));
        },
        sendMessage() {
            if (!window.WebSocket) {
                return;
            }
            if (this.content.replace(/\s/gi, '') == '') {
                return;
            }
            let obj = {};
            obj.cmd = 'CHAT';
            obj.type = 1;
            obj.avatarUrl = JSON.parse(sessionStorage.getItem('avatarUrl'));
            obj.time = new Date().getTime();
            obj.fromUser = this.customerServiceId;
            obj.userId = this.customerServiceId;
            obj.name = '管理员';
            obj.sessionid = this.sessionId;
            obj.msg = this.content;
            this.$ws.send(JSON.stringify(obj));
        },
        // 聊天结束-------------------------------------------------------
        // queryChatHistoryData() {
        //     let obj = {
        //         ...this.chatPage,
        //         sessionid: this.sessionId,
        //     };
        //     queryChatHistoryList(obj)
        //         .then(res => {
        //             // console.log('聊天历史记录', res);
        //             if (res.data && res.data.records && res.data.records.length > 0) {
        //                 this.chatList = res.data.records;
        //                 let chatData = [...res.data.records];
        //                 this.chatList = chatData.reverse();
        //                 if (this.chatList && this.chatList.length > 0) {
        //                     this.keepChattingTop();
        //                 }
        //             }
        //         })
        //         .catch();
        // },
        // 专家 -------------------------------------------------
        queryExpertData() {
            let obj = {
                sort: {
                    order: 'desc',
                    orderBy: 'platform_invited_flag',
                }
            };
            queryAllExpert(obj)
                .then(res => {
                    console.log('专家列表', res);
                    this.expertList = res.data;
                })
                .catch();
        },
        selectExpert(data) {
            console.log(data);
            this.checkId = data.userId;
            this.expertId = data.userId;
            this.statuz = data.statuz;
        },
        inviteExpert() {
            if (!this.expertId) {
                this.$message({
                    type: 'warning',
                    message: '请先选择一个专家',
                });
                return false;
            }
            //问诊
            if(this.statuz == 1 || this.statuz == 8){
                let obj = {
                    id: this.id,
                    chargerId: this.expertId,
                };
                invitationExpert(obj)
                    .then(res => {
                        if(res.statusCode==="1"){
                            this.$message.success('已邀请此专家,请耐心等候！');
                            this.queryLiftCaseData();
                            this.checkId = -1;
                            this.expertId = null;
                        }
                        else{
                            this.$message.error(res.message);
                        }
                    })
                    .catch();
            }
            //出诊
            else if(this.statuz == 0 || this.statuz == 8){
                let obj = {
                    id: this.id,
                    chargerId: this.expertId,
                };
                invitationExpert(obj)
                    .then(res => {
                        if(res.statusCode==="1"){
                            this.$message.success('已邀请此专家,请耐心等候！');
                            this.queryLiftCaseData();
                            this.checkId = -1;
                            this.expertId = null;
                        }
                        else{
                            this.$message.error(data.message);
                        }
                    })
                    .catch();
            }
            else{
                this.$message.warning('该专家已接单,请选择其他专家！');
            }
        },
        callExpert(data) {
            // console.log(data);
        },
        goBack() {
            this.$router.go(-1);
        },
        // 聊天消息置顶
        keepChattingTop() {
            this.$nextTick(() => {
                let scrollRef = this.$refs['scrollbar'].$refs['wrap'];
                if (scrollRef && scrollRef.scrollHeight) {
                    scrollRef.scrollTop = scrollRef.scrollHeight;
                }
            });
        },
        showHistoryDesc(e){
            let el = e.currentTarget;
            console.warn(el);
            let obj = {
                ...this.chatPage,
                sessionid: this.sessionId,
            };
            queryMsgHistoryList(obj)
                .then(res => {
                    console.log('聊天历史记录', res);
                    if (res.data && res.data.length > 0) {
                        this.chatList = this.chatList.concat(res.data);
                    }
                })
                .catch();

            this.isShowHistory = false;
        }
    },
    destroyed() {
        this.$ws.onclose();
    },
};
</script>
<style lang="stylus" scoped>
.chat-room {
    width: 100%;
    margin: 0 auto;
}

.chat-room-head {
    display: flex;
    height: 64px;

    .head-title {
        background-color: rgba(0, 40, 77, 1);

        span {
            display: block;
            width: 256px;
            height: 64px;
            line-height: 64px;
            text-align: center;
            font-weight: 700;
            font-style: normal;
            font-size: 20px;
            color: rgba(255, 255, 255, 0.847058823529412);
        }
    }

    .head-btn {
        width: calc(100% - 256px);

        .exitBtn {
            left: 80px;
            font-size: 16px;
        }

        .head-switch {
            right: 20px;
        }
    }
}

.chat-room-body {
    display: flex;
    justify-content: space-around;
    padding: 20px 10px;
    background-color: rgba(240, 242, 245, 1);

    .body-centre {
        width: 700px;

        .centre-top {
            .centre-top-title {
                height: 20px;
                line-height: 20px;
                font-size: 16px;
                color: #000000;
                text-indent: 10px;
                background-color: #f5f5f5;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12);
            }

            .centre-top-content {
                width: 100%;
                background-color: #fff;

                .left-side {
                    width: 350px;
                    border: 1px solid green;
                    padding-left: 8px;
                }

                .left-item {
                    width: 100%;
                    display: flex;
                    margin-bottom: 10px;
                }

                .left-chat-content {
                    max-width: 160px;
                    padding: 8px;
                    margin-top: 4px;
                    border-radius: 5px;
                    background-color: #f5f5f5;
                    height: auto;
                }

                .right-side {
                    display: flex;
                    width: 350px;
                    border: 1px solid yellow;
                    padding-right: 8px;
                }

                .right-item {
                    width: 100%;
                    display: flex;
                    margin-bottom: 10px;
                    flex-direction: row-reverse;
                }

                .right-chat-content {
                    max-width: 160px;
                    padding: 8px;
                    margin-top: 4px;
                    border-radius: 5px;
                    background-color: #f5f5f5;
                    height: auto;
                }

                .chat-records {
                    display: flex;
                    min-height: 76px;
                    padding: 20px;

                    .chat-records-icon {
                        margin: 0 5px;
                        width: 35px;
                        height: 35px;

                        .el-image {
                            border-radius: 50%;
                        }
                    }

                    .chat-records-content {
                        max-width: 160px;
                        padding: 8px;
                        margin-top: 3px;
                        border-radius: 5px;
                        background-color: #f5f5f5;
                    }
                }

                .row {
                    flex-direction: row;
                }

                .reverse {
                    flex-direction: row-reverse;
                }
            }
        }

        .centre-bottom {
            .bottom-top {
                height: 30px;
                padding-left: 10px;

                i {
                    margin-right: 5px;
                    height: 30px;
                    line-height: 30px;
                }

                i:before {
                    font-size: 16px;
                }
            }

            .bottom-text {
                background-color: #fff;
                padding-bottom: 20px;

                .send {
                    margin-right: 10px;
                }
            }
        }
    }

    .body-rignt {
        width: 350px;
        background-color: #fff;

        .member {
            padding: 0 20px;

            .member-head {
                height: 40px;
                line-height: 40px;
                font-size: 16px;
                font-weight: 700;
            }

            .member-box {
                height: 180px;
            }

            .membei-list {
                display: flex;
                position: relative;
                padding: 2px 0;
                border-bottom: 1px solid #f2f2f2;
                margin-bottom: 10px;

                .membei-icon {
                    padding: 5px;

                    .el-image {
                        border-radius: 50%;
                    }
                }

                .member-people {
                    div {
                        height: 25px;
                        line-height: 25px;
                        font-size: 14px;
                    }

                    .people-name {
                        color: rgba(24, 210, 94, 1);
                        font-size: 16px;
                    }

                    .people-time {
                        color: #7f7f7f;
                    }

                    .people-phone {
                        color: rgba(24, 210, 94, 1);
                    }
                }

                .member-people-btn {
                    position: absolute;
                    top: 10px;
                    right: 10px;
                }

                .circle {
                    width: 8px;
                    height: 8px;
                    border-radius: 50%;
                    background-color: red;
                }

                .active {
                    background-color: #67C23A;
                }

                .inactive {
                    background-color: #ccc;
                }
            }
        }

        .expert-list-bigbox {
            .expert-title {
                text-indent: 20px;
                font-size: 16px;
                font-weight: 700;
                height: 40px;
                line-height: 40px;
                background-color: #f0f2f5;
            }

            .expert-scrollbar {
                height: 100%;
            }

            .expert-list {
                padding: 20px;
                height: 370px;
            }

            .el-icon-success {
                font-size: 18px;
            }

            .check-active {
                color: #85ce61;
            }

            .check-inactive {
                color: #ccc;
            }

            .membei-list {
                display: flex;
                position: relative;
                padding: 2px 0;
                border-bottom: 1px solid #f2f2f2;
                margin-bottom: 10px;

                .left-side {
                    display: flex;
                }

                .membei-icon {
                    padding: 5px;

                    .el-image {
                        border-radius: 50%;
                    }
                }

                .member-people {
                    div {
                        height: 25px;
                        line-height: 25px;
                        font-size: 14px;
                    }

                    .people-name {
                        color: rgba(24, 210, 94, 1);
                        font-size: 16px;
                    }

                    .people-time {
                        color: #7f7f7f;
                    }

                    .people-phone {
                        color: rgba(24, 210, 94, 1);
                    }

                    .expert-label {
                        margin-left: 4px;
                        font-size: 10px;
                        color: #E6A23C;
                    }

                    .expert-level {
                        margin-left: 4px;
                        font-size: 8px;
                        color: #409EFF;
                    }
                }

                .member-people-btn {
                    position: absolute;
                    top: 10px;
                    right: 10px;
                }
            }

            .Invite-experts {
                .Invite-experts-btn {
                    margin-right: 10px;
                }
            }
        }
    }
}

::v-deep .el-switch__label {
    width: 30px;
}

::v-deep .el-button {
    border: none;
}

.el-scrollbar {
    height: 100%;
}

::v-deep .el-scrollbar__wrap {
    overflow-x: hidden;
    background-color: #fff;
}

::v-deep .el-textarea__inner {
    height: 130px;
}

.btn-history {
	border:0;
	outline:none;
	background-color: transparent;
    cursor: pointer;
    color: #5383E7;
    margin-top: 5px;
    margin-left: 300px;
    font-size: 12px;
}
</style>
