/**
 *
 * 门诊医生站
 */
import React from 'react';
import { Card, Spin, Button, Steps, Icon, Divider, message, Modal, Tooltip } from 'antd';
import { Util } from 'tools/index';
import { $http } from 'containers/config/https';
import PatientsClinicalTabPane from './component/PatientsClinicalTabPane.jsx';
import CMOrderSave from './component/CMOrderSave.jsx';
import EntryApplicationForm from './component/EntryApplicationForm.jsx';
import OutPatientOageModal from './component/OutPatientOageModal.jsx';
import VideoConsultationPage from './component/VideoConsultationPage.jsx';
import ShowCommonVoiceChatPage from './component/ShowCommonVoiceChatPage.jsx';
import ShowCloseModal from './component/ShowCloseModal.jsx';
import asyncComponent from '../../routers/AsyncComponent.js';
import PatientCourseInfo from 'pages/nurse/Patient/PatientCourseInfo.jsx';
import MedicalRecord from 'pages/nurse/MedicalRecord/MedicalRecord.jsx';
import ShowCommonNavigationPage from './component/ShowCommonNavigationPage.jsx';
import DoctorAdviceStepPage from 'pages/workstation/component/DoctorAdviceStepPage'; // 医嘱录入
import CaseInformationPageExampleCaseOut from 'pages/workstation/component/CaseInformationPageExampleCaseOut'; // 病历录入
import CaseInformationPageExampleCase from 'pages/workstation/component/CaseInformationPageExampleCase'; // 住院病历
import store from 'store';
import TRTC from 'trtc-js-sdk';
import TIM from 'tim-js-sdk';
import COS from 'cos-js-sdk-v5';
import LibGenerateTestUserSig from '../../../public/lib-generate-test-usersig.min.js';
import $ from './component/js/jquery-3.2.1.min.js';
import './style/index.less';
import ShowExamineModal from "./component/ShowExamineModal.jsx";
import PatientBlacklist from 'pages/hospital/component/PatientBlacklist';

const icon_name_blocklist = require('pages/workstation/image/img/icon_name_blocklist.png');
const imagePlus = require('./image/Plus.png');
const imagePhone = require('./image/phone.png');
const imagePicture = require('./image/picture.png');
const imageInvite = require('./image/invite.png');
const videoCall = require('./image/videoCall.png');
const disVideo = require('./image/disable-video.png');
const hangUp = require('./image/hangUp.png');
const endVisit = require('./image/endVisit.png');
const disEndVisit = require('./image/disEndVisit.png');
const disHangUp = require('./image/disHangUp.png');
const maleImg = require('../../assets/images/avatar_male.png')
const femaleImg = require('../../assets/images/avatar_female.png')
const icon_name = require('./image/img/icon_name.png');
const icon_gender = require('./image/img/icon_gender.png');
const icon_expense = require('./image/img/icon_expense.png');
const icon_icon = require('./image/img/icon_icon.png');
const confirm = Modal.confirm;
const { Step } = Steps;
const SDKAPPID = 1400381368;
let isCamOn = true;
let isMicOn = true;
let isScreenOn = false;
let isJoined = true;
let rtc = null;
let share = null;
let shareUserId = '';
let cameraId = '';
let micId = '';
var time;
var sec = 0;
var second, minute, hour;
second = minute = hour = 0;
var timeout;
var setTime;

/**
 * 签名过期时间，建议不要设置的过短
 * <p>
 * 时间单位：秒
 * 默认时间：7 x 24 x 60 x 60 = 604800 = 7 天
 */
const EXPIRETIME = 604800;

/**
 * 计算签名用的加密密钥
 */
const SECRETKEY = '22f87766bb2a4a80ef0fadd32426e18317d01cdf62493ec913f5da4f43b7cafe';

var get = {
    byId: function (id) {
        return typeof id === "string" ? document.getElementById(id) : id
    },
    byClass: function (sClass, oParent) {
        var aClass = [];
        var reClass = new RegExp("(^| )" + sClass + "( |$)");
        var aElem = this.byTagName("*", oParent);
        for (var i = 0; i < aElem.length; i++) reClass.test(aElem[i].className) && aClass.push(aElem[i]);
        return aClass
    },
    byTagName: function (elem, obj) {
        return (obj || document).getElementsByTagName(elem)
    }
};
var dragMinWidth = 0;
var dragMinHeight = 0;
var dragHeight = 0;

class OutpatientStationTabs extends React.Component {
    constructor(props) {
        super(props)
        let recordData = JSON.parse(sessionStorage.getItem('recordData'));
        let patientData = JSON.parse(sessionStorage.getItem('patientData'));
        let userData = JSON.parse(sessionStorage.getItem('userData'));
        let EMRIP = window.location && (window.location.host.indexOf('localhost') !== -1 || window.location.host.indexOf('127.0.0.1') !== -1) ? 'https://172.16.1.6/EMR' : (window.location.protocol + '//' + window.location.host + '/EMR');
        this.state = {
            dataSource: [],
            total: 0,
            page: 1,
            pageSize: 10,
            recordData: recordData,
            patientData: patientData,
            userData: userData,
            isOpen: true,
            second: 0,
            minute: 0,
            hour: 0,
            iH: 700,
            loading: false,
            saveStatus: false,
            admID: '',
            EMRIP,
        }
        if (window.innerWidth > 1500) {
            dragMinWidth = 520;
            dragMinHeight = 700;
            dragHeight = 700;
        } else {
            dragMinWidth = 400;
            dragMinHeight = 550;
            dragHeight = 550;
        }
    }

    static getDerivedStateFromProps(nextProps, prevState) {
        if (nextProps.admID !== prevState.admID) {
            return {
                admID: nextProps.admID
            }
        }
        return null
    }

    componentDidUpdate(nextProps, prevState) {
        if (prevState.admID !== this.state.admID) { // 弹窗赋值会报错，所以表单在打开弹窗的时候单独调
            this.onRefDoctor && this.onRefDoctor.loadPatientMsg && this.onRefDoctor.loadPatientMsg(this.state.admID);
        }
        setTimeout(() => {//延时加载，防止医嘱录入刷新数据
            if (!Util.isEmpty(this.state.showVideoID) && document.getElementById('video_' + this.state.showVideoID)) {
                document.getElementById('video_' + this.state.showVideoID).controls = true
            }
        }, 500)
    }

    componentDidMount() {
        this.loadTencentCloud(); // 获取腾讯云配置
        this.loadPatientMsg(); // 获取接诊病人信息
        this.loadMedicineDepartment(); // 中医科权限
        this.loadStepComponent()
        if (this.props.onRef) {
            this.props.onRef(this);
        }
        this.loadCommonModal()
        this.isJoined_ = false;
        this.isPublished_ = false;
        this.isAudioMuted = false;
        this.isVideoMuted = false;
        this.localStream_ = null;
        this.remoteStreams_ = [];
        this.members_ = new Map();
        this.loadUploadAddress(); // 获取上传地址
        setTimeout(() => {
            this.importJquery();
            this.importService();
        }, 1000)
        // 重新进医生站需清空默认数据
        store.dispatch({
            type: 'outPatientDefaultValue',
            value: {}
        });
    }

    componentWillUnmount() {
        var roomID = JSON.parse(sessionStorage.getItem('roomID'))
        var userData = JSON.parse(sessionStorage.getItem('userData'))
        var activeKey = JSON.parse(sessionStorage.getItem('activeKey'))
        var showVideoModal = JSON.parse(sessionStorage.getItem('showVideoCallModal'))
        var showCalled = JSON.parse(sessionStorage.getItem('showCalled'))
        if (!Util.isEmpty(roomID)) {
            this.handleLeaveRoom('clear')
        }
        if (!Util.isEmpty(showVideoModal) && Util.isEmpty(showCalled) && (activeKey == '2' || Util.isEmpty(activeKey))) {
            this.loadCloseVideoMsg('clear')
        }
        clearTimeout(setTime);
        clearTimeout(timeout);
        sessionStorage.removeItem('outEMRDefaultTemplate'); // 清除门诊病历缓存的模板信息
        this.setState = (state, callback) => { return; }
    }

    // 病历资源文件预加载 - jq文件
    importJquery = () => {
        let jqDOM = document.getElementById('emr-jquery');
        if (!jqDOM) {
            let script = document.createElement('script');
            script.async = true;
            script.type = 'text/javascript';
            script.id = 'emr-jquery';
            script.src = `${this.state.EMRIP}/jquery/jquery-1.7.2.min.js`;
            document.head.appendChild(script);
        }
    }

    // 病历资源文件预加载 - 病历主文件
    importService = () => {
        let serviceDOM = document.getElementById('emr-service');
        if (!serviceDOM) {
            let script = document.createElement('script');
            script.async = true;
            script.id = 'emr-service';
            script.type = 'text/javascript';
            script.src = `${this.state.EMRIP}/DemoDocumentImageService.aspx?js=1`;
            document.head.appendChild(script);
        }
    }

    getQueryString(name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = this.props.location ? this.props.location.search.substr(1).match(reg) : null;
        if (r != null) {
            return decodeURIComponent(r[2]);
        }
        return null;
    }

    loadTencentCloud() {
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "03100143",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        tencentMsg: res.result,
                        imSecretKey: !Util.isEmpty(res.result) ? res.result.imSecret : '',
                        imAppID: !Util.isEmpty(res.result) ? Number(res.result.imAppID) : '',
                    })
                }
            }
        });
    }

    loadMedicineDepartment() {
        var params = {
            params: [{
                locID: this.state.userData.locID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "03010111",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        medicineFlag: res.result.flag,
                        medicineStatus: res.result.flag == 'Y' ? true : false
                    })
                }
            }
        });
    }

    loadUploadAddress() {
        var params = {
            params: [{
                locID: this.state.userData.locID,
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "03070115",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    let windowHost = window.location && window.location.origin ? window.location.origin : (window.location && window.location.protocol ? (window.location.protocol + '//' + window.location.hostname) : "");
                    let url = res.result || "";
                    this.setState({
                        addressUrl: url.indexOf("http") !== -1 ? url : windowHost + url,
                        downloadPath: res.downloadPath,
                    })
                }
            }
        });
    }

    loadNextPatientMsg() {
        var params = {
            params: [{
                locID: this.state.userData.locID,
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "03100074",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        nextPatientMsg: res.result,
                        // rowId: !Util.isEmpty(res.result) ? res.result.admID : ''
                    })
                }
            }
        });
    }

    drag(oDrag, handle) {
        var that = this;
        var activeKey = JSON.parse(sessionStorage.getItem('activeKey'))
        var disX = 0;
        var oMin = get.byClass("min", oDrag)[0];
        var oMax = get.byClass("max", oDrag)[0];
        var oRevert = get.byClass("revert", oDrag)[0];
        var oClose = get.byClass("close", oDrag)[0];
        handle = handle || oDrag;
        handle && handle.style ? handle.style.cursor = "move" : '';
        handle.onmousedown = function (event) {
            var event = event || window.event;
            disX = event.clientX - oDrag.offsetLeft;
            var disY = event.clientY - oDrag.offsetTop;
            document.onmousemove = function (event) {
                var event = event || window.event;
                var iL = event.clientX - disX;
                var iT = event.clientY - disY;
                var maxL = document.documentElement.clientWidth - oDrag.offsetWidth;
                var maxT = document.documentElement.clientHeight - oDrag.offsetHeight;
                iL <= 0 && (iL = 0);
                iT <= 0 && (iT = 0);
                iL >= maxL && (iL = maxL);
                iT >= maxT && (iT = maxT);
                oDrag.style.left = iL + "px";
                oDrag.style.top = iT + "px";
                return false
            };
            document.onmouseup = function () {
                document.onmousemove = null;
                document.onmouseup = null;
                this.releaseCapture && this.releaseCapture()
            };
            this.setCapture && this.setCapture();
            return false
        };
        oMax.onclick = function () {
            oDrag.style.top = oDrag.style.left = 0;
            oDrag.style.width = document.documentElement.clientWidth - 20 + "px";
            oDrag.style.height = document.documentElement.clientHeight - 70 + "px";
            document.getElementById('main-video').style.width = '30%'
            if (!Util.isEmpty(that.state.showVideoID) && document.getElementById(that.state.showVideoID)) {
                document.getElementById(that.state.showVideoID).style.width = '30%'
            }
            this.style.display = "none";
            oRevert.style.display = "block";
        };
        //还原按钮
        oRevert.onclick = function () {
            // oDrag.style.width = dragMinWidth + "px";
            // oDrag.style.height = dragMinHeight + "px";
            document.getElementById('main-video').style.width = '100%'
            if (!Util.isEmpty(that.state.showVideoID) && document.getElementById(that.state.showVideoID)) {
                document.getElementById(that.state.showVideoID).style.width = '100%'
            }
            if (window.innerWidth > 1500) {
                if (that.state.showPicture == true) {
                    oDrag.style.width = 1000 + "px";
                    oDrag.style.height = 740 + "px";
                    oDrag.style.left = (document.documentElement.clientWidth - oDrag.offsetWidth) / 2 + "px";
                    oDrag.style.top = (document.documentElement.clientHeight - oDrag.offsetHeight) / 2 + "px";
                } else {
                    oDrag.style.width = 520 + "px";
                    oDrag.style.height = 700 + "px";
                    oDrag.style.left = (document.documentElement.clientWidth - oDrag.offsetWidth) / 2 + "px";
                    oDrag.style.top = (document.documentElement.clientHeight - oDrag.offsetHeight) / 2 + "px";
                }
            } else {
                oDrag.style.width = 400 + "px";
                oDrag.style.height = 550 + "px";
                oDrag.style.left = (document.documentElement.clientWidth - oDrag.offsetWidth) / 2 + "px";
                oDrag.style.top = 0 + "px";
            }
            this.style.display = "none";
            oMax.style.display = "block";
        };
        //最小化按钮
        oMin.onclick = function () {
            oDrag.style.display = "none";
            var oA = document.createElement("a");
            // oA.className = "open";
            if (activeKey == '2' || Util.isEmpty(activeKey)) {
                oA.id = 'recert-open';
            } else {
                oA.id = 'recert-open-picture';
            }
            oA.href = "javascript:;";
            oA.title = "还原";
            document.body.appendChild(oA);
            oA.onclick = function () {
                oDrag.style.display = "block";
                document.body.removeChild(this);
                this.onclick = null;
            };
            // that.setState({
            //     showVideoCallModal:false
            // })
        };
        //关闭
        oClose.onclick = function () {
            // if (activeKey == '3') {
            //     if (that.state.statusCode == 'R' || that.state.statusCode == 'A') {
            //         that.setState({
            //             isShowCloseModal: true
            //         })
            //     } else {
            //         that.setState({
            //             showVoiceChatModal: false,
            //             sendStatus: false
            //         })
            //         oDrag.style.display = "none";
            //         that.signOut()
            //     }
            // } else if (that.state.showCalled == true && activeKey == '2' && that.state.statusCode !== 'F') {
            //     that.setState({
            //         isShowCloseModal: true
            //     })
            // } else {
            oDrag.style.display = "none";
            var oA = document.createElement("a");

            if ((that.state.showCalled == true || that.state.showVideoCallModal == true) && Util.isEmpty(that.state.sendMeg) && that.state.showCallBtn !== true) {
                that.handleSendVideoMsg('end')
            }
            // oA.className = "open";
            // oA.href = "javascript:;";
            // oA.title = "还原";
            document.body.appendChild(oA);
            oA.onclick = function () {
                oDrag.style.display = "block";
                document.body.removeChild(this);
                this.onclick = null;
            };
            that.setState({
                showVideoCallModal: false,
                showVoiceChatModal: false,
                continueStatus: false,
                second: 0,
                minute: 0,
                hour: 0,
                sec: 0,
                cameraId: '',
                micId: '',
                showCalled: false,
                showPicture: false,
                isKickedOut: false
            }, () => {
                second = 0, minute = 0, hour = 0, sec = 0
                //当为进行中状态或者点击了过号后，关闭通话后，不更改状态
                // if (that.state.statusCode !== 'A' && that.state.statusCode !== 'F' && that.state.callStatus !== true) {
                that.loadCloseVideoMsg()
                // }
                if (activeKey == '2' || Util.isEmpty(activeKey)) {
                    that.onLoadData.handleDisableBtn('show')
                }
                that.leave()
                clearTimeout(time)
                clearTimeout(setTime);
                if (that.state.showPicture) {
                    that.signOut()
                }
                var child = document.getElementById("audio_tip");
                if (child) {
                    child.parentNode.removeChild(child);
                }
            })
            // }

        };
        //阻止冒泡
        oMin.onmousedown = oMax.onmousedown = oClose.onmousedown = function (event) {
            this.onfocus = function () { this.blur() };
            (event || window.event).cancelBubble = true
        };
    }

    //未接通挂断
    loadCloseVideoMsg(type) {
        var patientData = JSON.parse(sessionStorage.getItem('patientData'));
        if (type = 'cannel') {
            this.setState({ disCannel: true })
        }
        var params = {
            params: [{
                admID: this.state.nextAdmID ? this.state.nextAdmID : (this.state.rowId ? this.state.rowId : (!Util.isEmpty(patientData) ? patientData.admID : '')),
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                locID: this.state.userData.locID,
                videoFlag: 'Y'
            }]
        }
        $http.post('urlDeault', this, {
            code: "03100080",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    if (type == 'clear') {
                        sessionStorage.removeItem('showVideoCallModal')
                        sessionStorage.removeItem('showCalled')
                    } else {
                        if (type == 'cannel') {
                            this.setState({ disCannel: false })
                        }
                        this.onLoadData.loadChildData()
                    }
                }
            }
        });
    }

    //结束就诊
    handleEndReceive(type) {
        var params = {
            params: [{
                admID: this.state.rowId,
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                locID: this.state.userData.locID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "03100061",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    if (type == 'next') {
                        this.loadVideoCall()
                    }
                    message.success('接诊完成', this.state.userData && this.state.userData.messageTime)
                    this.onLoadData.loadChildData()
                }
            }
        });
    }

    // 退出
    signOut = (type, code) => {
        let { userData } = this.state;
        const generator = new LibGenerateTestUserSig(this.state.imAppID, this.state.imSecretKey, EXPIRETIME);
        const userSig = generator.genTestUserSig('user' + (this.state.userData.userID));
        let promise = this.tim.logout();
        if (promise) {
            promise.then((imResponse) => {
                console.log("用户退出成功");
                if (type === "user") {
                    this.loginTencent(userSig, code);
                }
            }).catch(function (imError) {
                console.warn('logout error:', imError);
            });
        }
    }

    resize(oParent, handle, isLeft, isTop, lockX, lockY) {
        var that = this;
        handle.onmousedown = function (event) {
            var event = event || window.event;
            var disX = event.clientX - handle.offsetLeft;
            var disY = event.clientY - handle.offsetTop;
            var iParentTop = oParent.offsetTop;
            var iParentLeft = oParent.offsetLeft;
            var iParentWidth = oParent.offsetWidth;
            var iParentHeight = oParent.offsetHeight;
            document.onmousemove = function (event) {
                var event = event || window.event;
                var iL = event.clientX - disX;
                var iT = event.clientY - disY;
                var maxW = document.documentElement.clientWidth - oParent.offsetLeft - 2;
                var maxH = document.documentElement.clientHeight - oParent.offsetTop - 2; var iW = isLeft ? iParentWidth - iL : handle.offsetWidth + iL;
                var iH = isTop ? iParentHeight - iT : handle.offsetHeight + iT;
                isLeft && (oParent.style.left = iParentLeft + iL + "px");
                isTop && (oParent.style.top = iParentTop + iT + "px");
                iW < dragMinWidth && (iW = dragMinWidth);
                iW > maxW && (iW = maxW);
                lockX || (oParent.style.width = iW + "px");
                iH < dragMinHeight && (iH = dragMinHeight);
                iH > maxH && (iH = maxH);
                lockY || (oParent.style.height = iH + "px");
                dragHeight = iH
                setTimeout(() => {
                    that.setState({})
                }, 200)
                if ((isLeft && iW == dragMinWidth) || (isTop && iH == dragMinHeight)) document.onmousemove = null;
                return false;
            };
            document.onmouseup = function () {
                document.onmousemove = null;
                document.onmouseup = null;
            };
            return false;
        }
    };

    loadCommonModal() {
        let data = {
            params: [{
                compontName: "DoctorAdviceModal",
                type: "C",
                reactCode: ['DoctorAdviceModal']
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040073",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    this.setState({
                        localeProvider: this.state.userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
                    })
                }
            }
        })
    }

    loadPatientMsg(status) {
        let patientData = JSON.parse(sessionStorage.getItem('patientData'));
        var params = {
            params: [{
                patID: patientData ? patientData.patID : '',
                admID: patientData ? patientData.admID : '',
                locID: this.state.userData.locID,
                userID: this.state.userData.userID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050021",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    sessionStorage.setItem('titleData', JSON.stringify(res.data))
                    this.setState({
                        titleData: res.data,
                        statusNote: !Util.isEmpty(res.data) ? res.data.statusCode : '',
                        statusCode: !Util.isEmpty(res.data) ? res.data.statusCode : '',
                    })
                }
            }
        });
    }

    //结束
    loadEndPatinet() {
        var params = {
            params: [{
                patAdmID: this.props.paras ? this.props.paras.userInfo.id : this.getQueryString('id'),
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050008",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('操作成功', this.state.userData && this.state.userData.messageTime)
                    this.props.history.push('./03050001')
                    sessionStorage.removeItem('patientData')
                }
            }
        });
    }

    //获取动态step组件
    getDefaultChangeComponent = (componentSource) => {
        return componentSource && componentSource.code === '03050037' && this.state.userData?.hospCode === 'QYCRGMZB' ? '1' : '2';
    }

    loadStepComponent() {
        var params = {
            params: [{
                locID: this.state.userData.locID,
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050093",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    var data = res.result;
                    var code = ''
                    var current = '0'
                    if (!Util.isEmpty(data)) {
                        for (var i = 0; i < data.length; i++) {
                            if (!Util.isEmpty(data[i].defaultFlag) && data[i].defaultFlag == 'Y') {
                                code = data[i]
                                current = i//新增，用于对外组件调用，step默认问题
                                break;
                            }
                        }
                    }
                    this.setState({
                        dataSource: res.result,
                        componentSource: code,
                        current: current,
                        changeComponent: this.getDefaultChangeComponent(code)
                    })
                }
            }
        });
    }

    //取消接诊
    onCannelPatient() {
        var that = this;
        confirm({
            title: this.setMessage('DoctorAdviceModalConfirm', 'descripts'),
            content: '',
            okText: that.state.userData.language == 'EN' ? 'Ok' : '确认取消',
            cancelText: that.state.userData.language == 'EN' ? 'cancel' : '继续接诊',
            onOk() {
                that.channelPatientModal()
            },
            onCancel() {
                console.log('Cancel');
            },
        });
    }

    handleCannelStop() {
        var data = JSON.parse(sessionStorage.getItem('patientData'));
        this.setState({ saveStatus: true })
        var params = {
            params: [{
                admID: data ? data.admID : '',
                userID: this.state.userData.userID,
                locID: this.state.userData.locID,
                hospID: this.state.userData.hospID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "03100125",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    // message.success('取消成功')
                    this.setState({ saveStatus: false })
                    message.success(this.setMessage('DoctorAdviceModalCancelSuccess', 'descripts'), this.state.userData && this.state.userData.messageTime)
                    this.onRefDoctor.loadEndReceiveOfDisableBtn()
                    // this.props.history.push('./03050002')
                    // sessionStorage.removeItem('patientData')
                    this.onLoadData.loadChildData()
                } else {
                    this.setState({ saveStatus: false })
                }
            }
        });
    }

    channelPatientModal() {
        var data = JSON.parse(sessionStorage.getItem('patientData'));
        this.setState({ saveStatus: true })
        var params = {
            params: [{
                // patAdmID: this.props.paras ? this.props.paras.userInfo.id : data ? data.admID : '',
                admID: this.props.paras ? this.props.paras.userInfo.id : data ? data.admID : '',
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                locID: this.state.userData.locID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "03100080",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    // message.success('取消成功')
                    this.setState({ saveStatus: false })
                    message.success(this.setMessage('DoctorAdviceModalCancelSuccess', 'descripts'), this.state.userData && this.state.userData.messageTime)
                    // this.props.history.push('./03050002')
                    // sessionStorage.removeItem('patientData')
                    this.onLoadData.loadChildData()
                } else {
                    this.setState({ saveStatus: false })
                }
            }
        });
    }

    hashROuter(data) {
        var that = this;
        var { routeFlag, saveFlag } = this.state;
        if (routeFlag === true) {
            confirm({
                title: '提示',
                content: '当前页面数据未保存，是否需要保存？',
                okText: that.state.userData.language == 'EN' ? 'Ok' : '是',
                cancelText: that.state.userData.language == 'EN' ? 'cancel' : '否',
                onOk() {
                    if (saveFlag && saveFlag == '3') {
                        that.handleUnSaveData()
                        // that.onRefDoctor.checkPoisonMsg()
                    } else if (saveFlag && saveFlag == '2') {
                        that.onRefDoctor.saveDiagnosisMsg()
                    } else if (saveFlag && saveFlag == '4') {
                        that.onRefDoctor.saveRecord()
                    }
                    that.setState({
                        changeComponent: data,
                        medicineStatus: false,
                        routeFlag: []//组件切换后，销毁自组件数据
                    })
                },
                onCancel() {
                    that.setState({
                        changeComponent: data,
                        medicineStatus: false,
                        routeFlag: []//组件切换后，销毁自组件数据
                    })
                }
            })
        } else {
            that.setState({
                changeComponent: data,
                medicineStatus: false
            })
        }
    }

    //添加背景色
    addBackGrd() {
        this.setState({
            bgdStatus: true
        })
    }

    removeBgd() {
        this.setState({
            bgdStatus: false
        })
    }

    changeTabs(e) {
        this.setState({
            activeTab: e
        })
    }

    openWindowBySubTab(data) {
        if (this.props.openWindowBySubTab) {
            this.props.openWindowBySubTab({
                title: '医嘱录入',
                path: '/03050002',
                Paras: {
                    targetKey: '医嘱录入',
                    flag: 'compile',
                    userInfo: data
                },
                component: "pages/workstation/OutPatientStationTabs.jsx"
            });
        } else {
            this.props.history.push('./03050002?id=' + record.patAdmID)
        }
        this.loadOutPatientModal(data)
    }

    loadOutPatientModal(data) {
        var params = {
            params: [{
                patID: data.patID,
                admID: data.id,
                locID: this.state.userData.locID,
                userID: this.state.userData.userID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050021",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    sessionStorage.setItem('titleData', JSON.stringify(res.data))
                    this.setState({
                        titleData: res.data
                    })
                    this.child.change(1)
                }
            }
        });
    }

    // 调用公共组件的连接事件
    onRef = (ref) => {
        this.child = ref
    }

    change(e) {
        this.state.current = e
        // this.setState({
        //     current: e,
        //     // changeComponent: '2',
        //     // isShowOutPatientModal: true,
        //     // isShowTriageSystemModal: true
        // })
        var { change } = this.props;
    }

    onChangeStepComponent(data, e) {
        var that = this;
        var { routeFlag, saveFlag } = this.state;

        /**
         * @ByYQL: 需求 #955 门诊慢性病患者提示
         * Create 2022-09-29
         */
        let titleData = JSON.parse(sessionStorage.getItem('titleData'));
        if (+data.id === 3 && titleData?.insuOPChronicDiseaseRegFlag === 'Y') {
            Modal.warning({
                title: '注意：',
                content: '此患者为慢性病患者',
            });
        }

        /**
        * @ByShizi: 切换工作站页签时如果已修改病历则需要提示已修改是否保存
        * 需求 #番禺医院提出
        * Create 2022-08-01
        */
        let isModifyMedicalRecord = that.onRefDoctor && that.onRefDoctor.getModified ? that.onRefDoctor.getModified() : false; // 病历信息切换标识
        saveFlag = isModifyMedicalRecord ? "" : saveFlag;
        // console.log("isModifyMedicalRecord", data, isModifyMedicalRecord, that.onRefDoctor)
        let templateDesc = that.onRefDoctor && that.onRefDoctor.getTemplateDesc ? that.onRefDoctor.getTemplateDesc() : "";
        if (routeFlag === true || isModifyMedicalRecord) {
            confirm({
                title: isModifyMedicalRecord ? <div>当前病历 <span style={{ fontWeight: "900" }}>{templateDesc}</span> 已修改，是否需要保存？</div> : '提示',
                content: isModifyMedicalRecord ? "" : '当前页面数据还没保存，是否需要保存？',
                okText: that.state.userData.language == 'EN' ? 'Ok' : '是->保存',
                cancelText: that.state.userData.language == 'EN' ? 'cancel' : '否->无需保存',
                onOk() {
                    //当patinetData为空时，不让step点击
                    var disbledStatus = JSON.parse(sessionStorage.getItem('patientData'))
                    if (Util.isEmpty(disbledStatus)) {
                        return
                    }
                    if (saveFlag && saveFlag == '3') {
                        that.handleUnSaveData()
                        // that.onRefDoctor.checkPoisonMsg()
                    } else if (saveFlag && saveFlag == '2') {
                        that.onRefDoctor.saveDiagnosisMsg()
                    } else if (saveFlag && saveFlag == '4') {
                        that.onRefDoctor.saveRecord()
                    }
                    if (data.code == '03050040') {
                        setTimeout(() => {
                            that.loadDoctorActiveMsg(data)//提示就诊未开医嘱
                        }, 500)
                    } else if (isModifyMedicalRecord) { // 为住院病历信息时
                        that.onRefDoctor && that.onRefDoctor.handleSave && that.onRefDoctor.handleSave('', '', () => that.handleSwitch(data));
                    } else {
                        that.setState({
                            componentSource: data,
                            // current: index,
                            changeComponent: that.getDefaultChangeComponent(data),
                            // medicineStatus:false,
                            isShowOutPatientModal: true,
                            isShowTriageSystemModal: true,
                            routeFlag: false//组件切换后，销毁自组件数据
                        })
                    }
                },
                onCancel() {
                    if (data.code == '03050040') {
                        setTimeout(() => {
                            that.loadDoctorActiveMsg(data)//提示就诊未开医嘱
                        }, 500)
                    } else {
                        that.handleSwitch(data);
                    }
                }
            })
        } else {
            //当patinetData为空时，不让step点击
            var disbledStatus = JSON.parse(sessionStorage.getItem('patientData'))
            if (Util.isEmpty(disbledStatus) || (((!Util.isEmpty(this.state.titleData) && this.state.titleData.typeCode == 'IMAGE') ||
                this.state.showVoiceChatModal == true || this.state.statusNote == 'RR') && (data.code !== '03050040' && data.code !== '03050055'))) {
                return
            }
            if (data.code == '03050040') {
                that.loadDoctorActiveMsg(data)//提示就诊未开医嘱
            } else {
                that.setState({
                    componentSource: data,
                    // current: parseInt(e.target.innerText) - 1,
                    changeComponent: that.getDefaultChangeComponent(data),
                    // medicineStatus:false,
                    isShowOutPatientModal: true,
                    isShowTriageSystemModal: true
                })
            }
        }
    }

    // 切换跳转
    handleSwitch = (data) => {
        this.setState({
            componentSource: data,
            // current: index,
            changeComponent: this.getDefaultChangeComponent(data),
            // medicineStatus:false,
            isShowOutPatientModal: true,
            isShowTriageSystemModal: true,
            routeFlag: false//组件切换后，销毁自组件数据
        })
    }

    loadDoctorActiveMsg(data) {
        var patientData = JSON.parse(sessionStorage.getItem('patientData'));
        var { dataSource } = this.state;
        var that = this;
        var params = {
            params: [{
                admID: patientData.admID,
                locID: this.state.userData.locID,
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03100131",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        activeFlag: res.result.flag,
                        activeMsg: res.result.message
                    }, () => {
                        if (this.state.activeFlag == 'Y') {
                            confirm({
                                title: '提示',
                                content: that.state.activeMsg,
                                okText: that.state.userData.language == 'EN' ? 'Ok' : '是',
                                cancelText: that.state.userData.language == 'EN' ? 'cancel' : '否',
                                onOk() {
                                    that.setState({
                                        componentSource: data,
                                        // current: index,
                                        changeComponent: that.getDefaultChangeComponent(data),
                                        // medicineStatus:false,
                                        isShowOutPatientModal: true,
                                        isShowTriageSystemModal: true,
                                        routeFlag: false//组件切换后，销毁自组件数据
                                    })
                                },
                                onCancel() {
                                    that.setState({
                                        current: 0,
                                        componentSource: dataSource[0]
                                    })
                                }
                            })
                        } else {
                            that.setState({
                                componentSource: data,
                                // current: index,
                                changeComponent: that.getDefaultChangeComponent(data),
                                // medicineStatus:false,
                                isShowOutPatientModal: true,
                                isShowTriageSystemModal: true,
                                routeFlag: false//组件切换后，销毁自组件数据
                            })
                        }
                    })
                }
            }
        });
    }

    handleUnSaveData() {
        var temp = []
        var patientData = JSON.parse(sessionStorage.getItem('patientData'));
        var { componentData } = this.state;
        for (var i = 0; i < componentData.length; i++) {
            temp.push({
                ...componentData[i],
                skinTestWayList: undefined,
                admReasonList: undefined,
                doseUnitList: undefined,
                durationList: undefined,
                frequenceList: undefined,
                priorityExtList: undefined,
                priorityList: undefined,
                qtyUnitList: undefined,
                recLocList: undefined,
                specList: undefined,
                usageList: undefined,
                causeList: undefined,
                stageList: undefined,
                infuseSpeedList: undefined
            })
        }
        var params = {
            params: [{
                admID: patientData.admID,
                locID: this.state.userData.locID,
                userID: this.state.userData.userID,
                docID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                medType: 'WM',
                orders: temp
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050176",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                }
            }
        });
    }

    loadStepCompent() {
        //获取父组件的参数，渲染组件
        const { componentSource } = this.state;
        var titleData = JSON.parse(sessionStorage.getItem('titleData'))
        if (!Util.isEmpty(componentSource)) {
            const Component = asyncComponent(() => import('../../' + componentSource.component));
            return (this.state.changeComponent == '1' || (componentSource.code == '03050037' && this.state.medicineStatus == true) ?
                (<CMOrderSave hashROuter={this.hashROuter.bind(this)}
                    componentRouter={this.componentRouter.bind(this)}></CMOrderSave>) :
                (this.state.changeComponent == '3' ? <EntryApplicationForm hashROuter={this.hashROuter.bind(this)}
                    componentRouter={this.componentRouter.bind(this)} /> :
                    (componentSource.code == '03050035' ?
                        <OutPatientOageModal loadPatientMsg={this.loadTitleData.bind(this)}
                            loadTitleData={this.loadPatientMsg.bind(this)}
                            componentRouter={this.componentRouter.bind(this)}
                            loadPatientPage={this.loadPatientPage.bind(this)}
                            handleEndOperation={this.handleEndOperation.bind(this)} /> :
                        (componentSource.code == '03050055' ?
                            <VideoConsultationPage loadPatientMsg={this.loadTitleData.bind(this)}
                                onRef={this.onRefLoadData}
                                loadTitleData={this.loadPatientMsg.bind(this)}
                                componentRouter={this.componentRouter.bind(this)}
                                handlerefuseMsg={this.handlerefuseMsg.bind(this)}
                                loadPatientPage={this.loadPatientPage.bind(this)}
                                showChatHistoryMsg={this.showChatHistoryMsg.bind(this)}
                                showVideoCallModal={this.showVideoCallModal.bind(this)}
                                showVoiceChatModal={this.showVoiceChatModal.bind(this)}
                                handleEndReceive={this.handleChangeActiveKey.bind(this)}
                                handleEndOperation={this.handleEndOperation.bind(this)} /> :
                            (componentSource.code == '03050038' && (titleData && titleData.internetFlag == 'Y') ?
                                <MedicalRecord hashROuter={this.hashROuter.bind(this)} saveDiagnosisMsg={this.saveDiagnosisMsg.bind(this)}
                                    onHide={this.hideModal.bind(this)} loadPatientMsg={this.loadTitleData.bind(this)}
                                    loadTitleData={this.loadPatientMsg.bind(this)}
                                    onRef={this.onRefs}
                                    componentRouter={this.componentRouter.bind(this)}
                                    loadPatientPage={this.loadPatientPage.bind(this)}
                                    activeKey={this.state.activeKey}
                                    handleEndOperation={this.handleEndOperation.bind(this)}
                                    isShow={this.state.isShowTriageSystemModal} isShowModal={this.state.isShowOutPatientModal} /> : (
                                    componentSource.code === '03050037' ? ( // 医嘱录入
                                        <DoctorAdviceStepPage
                                            billingDoctor={this.props.billingDoctor || 'N'}
                                            hashROuter={this.hashROuter.bind(this)}
                                            saveDiagnosisMsg={this.saveDiagnosisMsg.bind(this)}
                                            onHide={this.hideModal.bind(this)}
                                            loadPatientMsg={this.loadTitleData.bind(this)}
                                            loadTitleData={this.loadPatientMsg.bind(this)}
                                            onRef={this.onRefs}
                                            componentRouter={this.componentRouter.bind(this)}
                                            loadPatientPage={this.loadPatientPage.bind(this)}
                                            activeKey={this.state.activeKey}
                                            handleEndOperation={this.handleEndOperation.bind(this)}
                                            isShow={this.state.isShowTriageSystemModal}
                                            isShowModal={this.state.isShowOutPatientModal}
                                        />
                                    ) : (componentSource.code === '03050020' ? ( // 新门诊病历信息
                                        <CaseInformationPageExampleCaseOut
                                            caseInformationPageTabs={this.props.patientFlag} // 是否展示右侧引用数据
                                            hashROuter={this.hashROuter.bind(this)}
                                            saveDiagnosisMsg={this.saveDiagnosisMsg.bind(this)}
                                            onHide={this.hideModal.bind(this)}
                                            loadPatientMsg={this.loadTitleData.bind(this)}
                                            loadTitleData={this.loadPatientMsg.bind(this)}
                                            onRef={this.onRefs}
                                            componentRouter={this.componentRouter.bind(this)}
                                            loadPatientPage={this.loadPatientPage.bind(this)}
                                            activeKey={this.state.activeKey}
                                            handleEndOperation={this.handleEndOperation.bind(this)}
                                            isShow={this.state.isShowTriageSystemModal}
                                            isShowModal={this.state.isShowOutPatientModal}
                                        />
                                    ) : (componentSource.code === '03060008' || componentSource.code === '04160022' ? ( // 住院病历信息
                                        <CaseInformationPageExampleCase
                                            caseInformationPageTabs={this.props.patientFlag} // 是否展示右侧引用数据
                                            hashROuter={this.hashROuter.bind(this)}
                                            saveDiagnosisMsg={this.saveDiagnosisMsg.bind(this)}
                                            onHide={this.hideModal.bind(this)}
                                            loadPatientMsg={this.loadTitleData.bind(this)}
                                            loadTitleData={this.loadPatientMsg.bind(this)}
                                            onRef={this.onRefs}
                                            componentRouter={this.componentRouter.bind(this)}
                                            loadPatientPage={this.loadPatientPage.bind(this)}
                                            activeKey={this.state.activeKey}
                                            handleEndOperation={this.handleEndOperation.bind(this)}
                                            isShow={this.state.isShowTriageSystemModal}
                                            isShowModal={this.state.isShowOutPatientModal}
                                        />
                                    ) : (
                                        <Component
                                            billingDoctor={this.props.billingDoctor || 'N'}
                                            hashROuter={this.hashROuter.bind(this)}
                                            saveDiagnosisMsg={this.saveDiagnosisMsg.bind(this)}
                                            onHide={this.hideModal.bind(this)} loadPatientMsg={this.loadTitleData.bind(this)}
                                            loadTitleData={this.loadPatientMsg.bind(this)}
                                            componentRouter={this.componentRouter.bind(this)}
                                            loadPatientPage={this.loadPatientPage.bind(this)}
                                            activeKey={this.state.activeKey}
                                            onRef={this.onRefs}
                                            upDataComponentSource={this.upDataComponentSource}
                                            componentSource={componentSource}
                                            handleEndOperation={this.handleEndOperation.bind(this)}
                                            isShow={this.state.isShowTriageSystemModal} isShowModal={this.state.isShowOutPatientModal} />
                                    )))))))))
        }
    }

    onRefs = (ref) => {
        this.onRefDoctor = ref
    }

    onRefLoadData = (ref) => {
        this.onLoadData = ref
    }

    //拒绝接诊，发送IM消息
    handlerefuseMsg(id) {
        const generator = new LibGenerateTestUserSig(this.state.imAppID, this.state.imSecretKey, EXPIRETIME);
        const userSig = generator.genTestUserSig('user' + (this.state.userData.userID));
        let options = {
            SDKAppID: this.state.imAppID
        }
        this.tim = TIM.create(options); // SDK 实例通常用 tim 表示
        // 设置 SDK 日志输出级别，详细分级请参见 setLogLevel 接口的说明
        this.tim.setLogLevel(0); // 普通级别，日志量较多，接入时建议使用
        // tim.setLogLevel(1); // release 级别，SDK 输出关键信息，生产环境时建议使用
        // 注册 COS SDK 插件
        this.tim.registerPlugin({ 'cos-js-sdk': COS });
        // this.handleSendText(res)
        this.setState({
            chatPatID: id
        }, () => {
            this.querysendMessage(userSig, 'refuse')
        })
    }

    querysendMessage = (userSig, type) => {
        let { userData } = this.state;
        let data = {
            params: [{
                imUserID: 'patient' + this.state.chatPatID,
            }]
        }
        $http.post("urlS", this, {
            code: "03090001",
            data: data,
            namespace: "HIS",
            success: function (res) {
                if (+res.errorCode === 0) {
                    if (res.result.exitFlag === "Y") {
                        console.log("用户已存在。")
                        this.loginTencent(userSig, type)
                    } else {
                        const generator = new LibGenerateTestUserSig(this.state.imAppID, this.state.imSecretKey, EXPIRETIME);
                        const userSigs = generator.genTestUserSig('patient' + (this.state.chatPatID));
                        // this.loginTencent(userSig, 'user')
                        this.loginPatient(userSigs, 'user', 'refuse')
                    }
                } else {
                    message.erroe(res.errorMessage, this.state.userData && this.state.userData.messageTime)
                }
            }
        })
    }

    //判断当前为门诊还是视频、或者图文
    handleChangeActiveKey(activeKey) {
        this.setState({
            activeKey: activeKey
        })
    }

    componentRouter(data, flag, componentData) {
        this.state.routeFlag = data//是否存在未保存数据
        this.state.saveFlag = flag//当前组件标识
        this.state.componentData = componentData//未保存的数据
    }

    hideModal(name) {
        this.setState({
            [name]: false,
            activeKey: '1'
        })
    }

    loadPatientPage(type) {
        var { dataSource } = this.state;
        this.setState({
            current: 0,
            isShowTriageSystemModal: false,
            componentSource: dataSource[0]
        }, () => {
            if (type == 'success' || type == 'finish') {
                this.setState({
                    titleData: {}
                })
                sessionStorage.removeItem('titleData')
                sessionStorage.removeItem('patientData')
            }
        })
    }

    loadTitleData(data, record) {
        // componentSource
        var { dataSource } = this.state;
        var code = ''
        var num = ''
        for (var i = 0; i < dataSource.length; i++) {
            if (!Util.isEmpty(dataSource[i].defaultFlag) && dataSource[i].defaultFlag == 'Y') {
                code = dataSource[i + 1]
                num = i
            }
        }
        this.setState({
            titleData: data,
            componentSource: code,
            current: num + 1
        }, () => {
            // this.props.history.push('./03050002?id=' + record.patAdmID)
        })
    }

    //点击结束就诊，返回列表
    handleEndOperation() {
        var activeKey = JSON.parse(sessionStorage.getItem('activeKey'));
        var { dataSource } = this.state;
        var code = ''
        var num = ''
        if (activeKey == '2' || activeKey == '3') {
            for (var i = 0; i < dataSource.length; i++) {
                if (!Util.isEmpty(dataSource[i].defaultFlag) && dataSource[i].defaultFlag == 'Y') {
                    code = dataSource[i]
                    num = i
                }
            }
            this.setState({
                componentSource: code,
                current: num
            })
        } else {
            for (var i = 0; i < dataSource.length; i++) {
                if (!Util.isEmpty(dataSource[i].defaultFlag) && dataSource[i].defaultFlag == 'Y') {
                    code = dataSource[i + 1]
                    num = i
                }
            }
            this.setState({
                componentSource: code,
                current: num + 1
            })
        }
    }

    saveDiagnosisMsg(id) {
        this.setState({
            current: id
        })
    }

    //国际化
    setMessage(name, message) {
        return this.state.localeProvider && this.state.localeProvider[name] ? this.state.localeProvider[name][message] : ''
    }

    showTimeout() {
        var admID = '', patID = '';
        var patientData = JSON.parse(sessionStorage.getItem('patientData'))
        if (!Util.isEmpty(patientData)) {
            admID = patientData.admID
            patID = patientData.patID
            this.childConsume.showModal(admID, patID);
        }
    }


    //自费按钮触发事件
    showExamineModal() {
        var admID = '';
        var patientData = JSON.parse(sessionStorage.getItem('patientData'))
        if (!Util.isEmpty(patientData)) {
            admID = patientData.admID
            this.childShowExamine.showModal(admID);
        }
    }

    /**
     * @ByYQL: 事前事中消息模态框
     * Create 2021-12-21
     */
    onShowExamineModalRef = (ref) => {
        this.childShowExamine = ref;
    };

    onConsumeRef = (ref) => {
        this.childConsume = ref;
    };

    initDragList() {
        var oDrag = document.getElementById("drag");
        var oTitle = get.byClass("title", oDrag)[0];
        var oL = get.byClass("resizeL", oDrag)[0];
        var oT = get.byClass("resizeT", oDrag)[0];
        var oR = get.byClass("resizeR", oDrag)[0];
        var oB = get.byClass("resizeB", oDrag)[0];
        var oLT = get.byClass("resizeLT", oDrag)[0];
        var oTR = get.byClass("resizeTR", oDrag)[0];
        var oBR = get.byClass("resizeBR", oDrag)[0];
        var oLB = get.byClass("resizeLB", oDrag)[0];
        this.drag(oDrag, oTitle);
        //四角
        this.resize(oDrag, oLT, true, true, false, false);
        this.resize(oDrag, oTR, false, true, false, false);
        this.resize(oDrag, oBR, false, false, false, false);
        this.resize(oDrag, oLB, true, false, false, false);
        //四边
        this.resize(oDrag, oL, true, false, false, true);
        this.resize(oDrag, oT, false, true, true, false);
        this.resize(oDrag, oR, false, false, false, true);
        this.resize(oDrag, oB, false, false, true, false);
        document.getElementById('drag').style.display = 'block'
        if (window.innerWidth > 1500) {
            oDrag.style.left = (document.documentElement.clientWidth - oDrag.offsetWidth - 400) / 2 + "px";
            oDrag.style.top = (document.documentElement.clientHeight - oDrag.offsetHeight - 150) / 2 + "px";
        } else {
            oDrag.style.left = (document.documentElement.clientWidth - oDrag.offsetWidth - 400) / 2 + "px";
            oDrag.style.top = 0 + "px";
        }
    }

    //视频问诊
    showVideoCallModal(rowId, roomID, chatPatID, statusNote) {
        this.setState({
            showVideoCallModal: true,
            rowId: rowId,
            patRowID: rowId,
            roomID: roomID,
            chatPatID: chatPatID,
            statusNote: statusNote,
            callStatus: false,
            loading: true,
            continueStatus: true
        }, () => {
            TRTC.Logger.setLogLevel(TRTC.Logger.LogLevel.DEBUG);
            TRTC.Logger.enableUploadLog();
            const generator = new LibGenerateTestUserSig(this.state.imAppID, this.state.imSecretKey, EXPIRETIME);
            const userSig = generator.genTestUserSig('user' + (this.state.userData.userID));
            //用于组件销毁时，更新视频问诊状态
            sessionStorage.setItem('showVideoCallModal', JSON.stringify('show'))
            sessionStorage.removeItem('showCalled')
            //视频弹框后，背面的视频呼叫按钮置灰
            this.onLoadData.handleDisableBtn('disable')
            this.onLoadData.loadChildData()
            this.initDragList()
            this.initData()
            this.setBtnClickFuc()
            this.loadLogin()
            setTimeout(() => {
                this.loadNextPatientMsg()//获取下一位患者信息
            }, 500)
            let options = {
                SDKAppID: this.state.imAppID
            }
            this.tim = TIM.create(options); // SDK 实例通常用 tim 表示
            // 设置 SDK 日志输出级别，详细分级请参见 setLogLevel 接口的说明
            this.tim.setLogLevel(0); // 普通级别，日志量较多，接入时建议使用
            // tim.setLogLevel(1); // release 级别，SDK 输出关键信息，生产环境时建议使用
            // 注册 COS SDK 插件
            this.tim.registerPlugin({ 'cos-js-sdk': COS });
            this.loginTencent(userSig, 'video')
            setTime = setInterval(() => { this.loginTencent(userSig, 'video') }, 10000)
            // this.queryWhetherTheUserExists(userSig)
            if (this.state.showCalled !== true) {
                time = setInterval(() => { this.showTimer() }, 1000);
            }
        })
    }

    showChatHistoryMsg(rowId, roomID, chatPatID, statusNote) {
        this.setState({
            showVideoCallModal: true,
            showCalled: true,
            rowId: rowId,
            patRowID: rowId,
            roomID: roomID,
            chatPatID: chatPatID,
            statusNote: statusNote,
            showCallBtn: true,
            continueStatus: true
        }, () => {
            this.initDragList()
        })
    }

    //图文咨询
    showVoiceChatModal(statusNote, rowId, patID) {
        this.setState({
            showVoiceChatModal: true,
            statusNote: statusNote,
            patRowID: rowId,
            rowId: rowId,
            chatPatID: patID,
        }, () => {
            this.initDragList()
            this.getChatData("isScroll", "", "");
            const generator = new LibGenerateTestUserSig(this.state.imAppID, this.state.imSecretKey, EXPIRETIME);
            const userSig = generator.genTestUserSig('user' + (this.state.userData.userID));
            let options = {
                SDKAppID: this.state.imAppID
            }
            this.tim = TIM.create(options); // SDK 实例通常用 tim 表示
            // 设置 SDK 日志输出级别，详细分级请参见 setLogLevel 接口的说明
            this.tim.setLogLevel(0); // 普通级别，日志量较多，接入时建议使用
            // tim.setLogLevel(1); // release 级别，SDK 输出关键信息，生产环境时建议使用

            // 注册 COS SDK 插件
            this.tim.registerPlugin({ 'cos-js-sdk': COS });
            this.queryWhetherTheUserExists(userSig)
        })
    }

    //  检查IM通信用户是否存在
    queryWhetherTheUserExists = (userSig) => {
        let { userData } = this.state;
        let data = {
            params: [{
                imUserID: 'patient' + this.state.chatPatID,
            }]
        }
        $http.post("urlS", this, {
            code: "03090001",
            data: data,
            namespace: "HIS",
            success: function (res) {
                if (+res.errorCode === 0) {
                    if (res.result.exitFlag === "Y") {
                        console.log("用户已存在。")
                        this.loginTencent(userSig, 'M')
                    } else {
                        const generator = new LibGenerateTestUserSig(this.state.imAppID, this.state.imSecretKey, EXPIRETIME);
                        const userSigs = generator.genTestUserSig('patient' + (this.state.chatPatID));
                        // this.loginTencent(userSig, 'user')
                        this.loginPatient(userSigs, 'user')
                    }
                } else {
                    message.erroe(res.errorMessage, this.state.userData && this.state.userData.messageTime)
                }
            }
        })
    }

    loginPatient(userSig, type, code) {
        let user = userSig;
        let promise = this.tim.login({ userID: 'patient' + (this.state.chatPatID) || "", userSig: user });
        promise.then((imResponse) => {
            console.log(imResponse)
            if (imResponse.data.errorCode == '0') {
                this.setState({ isKickedOut: true }, () => {
                    this.tim.on(TIM.EVENT.MESSAGE_RECEIVED, this.onMessageReceived);
                    this.tim.on(TIM.EVENT.KICKED_OUT, this.monitorKickedOut);
                })
                if (type === "user") {
                    this.saveCommunicationUser();
                    setTimeout(() => {
                        this.signOut("user", code); // 退出医生登录
                    }, 300)
                }
            }
        }).catch(function (imError) {
            console.warn('login error:', imError); // 登录失败的相关信息
        });
    }

    loginTencent(userSig, type) {
        console.dir('我发消息了哦')
        let user = userSig;
        let promise = this.tim.login({ userID: 'user' + (this.state.userData.userID) || "", userSig: user });
        promise.then((imResponse) => {
            console.log(imResponse)
            if (imResponse.data.errorCode == '0') {
                this.setState({ isKickedOut: true }, () => {
                    this.tim.on(TIM.EVENT.MESSAGE_RECEIVED, this.onMessageReceived);
                    this.tim.on(TIM.EVENT.KICKED_OUT, this.monitorKickedOut);
                    if (type == 'video' || 'refuse' || 'M') {
                        setTimeout(() => {
                            this.handleSendVideoMsg(type)
                        }, 500)
                    }
                })
                if (type === "user") {
                    this.saveCommunicationUser();
                    setTimeout(() => {
                        this.signOut("user"); // 退出医生登录
                    }, 300)
                }
            }
        }).catch(function (imError) {
            console.warn('login error:', imError); // 登录失败的相关信息
        });
    }

    //视频呼叫时，给患者发送一条消息
    handleSendVideoMsg(status) {
        let { userData, titleData } = this.state;
        var patientData = JSON.parse(sessionStorage.getItem('patientData'));
        try {
            let messageContent = {};
            messageContent.userID = userData.userID;
            messageContent.admID = !Util.isEmpty(patientData) ? patientData.admID : '';
            messageContent.patID = !Util.isEmpty(patientData) ? patientData.patID : '';
            messageContent.patName = !Util.isEmpty(titleData) ? titleData.patName : '';
            messageContent.userName = userData.userName;
            messageContent.type = (status == 'end' ? 'E' : (status == 'refuse' ? 'R' : (status == 'M' ? 'M' : 'V')));
            messageContent.text = '视频信息';
            let message = this.tim.createTextMessage({
                to: 'patient' + this.state.chatPatID,
                conversationType: TIM.TYPES.CONV_C2C,
                payload: {
                    text: JSON.stringify(messageContent)
                }
            });
            if (status == 'end') {
                this.setState({
                    sendMeg: undefined
                })
            }
            // this.tim.sendMessage(message);
            let promise = this.tim.sendMessage(message);
            if (promise) {
                promise.then((imResponse) => {
                    if (imResponse && imResponse.code === 0) {
                    }
                }).catch((imError) => {
                    // 发送失败 --- 调接口改变消息状态
                    message.error('发送失败：', imError);
                });
            }

        } catch (e) {
            message.error("发送失败: " + e.message)
        }
    }

    // 保存IM通信用户
    saveCommunicationUser = () => {
        let data = {
            params: [{
                userType: 'P',
                userID: this.state.chatPatID || '',
            }]
        }
        $http.post("urlS", this, {
            code: "03090002",
            data: data,
            namespace: "HIS",
            success: function (res) {
                if (+res.errorCode === 0) {
                } else {
                    // message.error(res.errorMessage)
                }
            }
        })
    }

    // 监听是否被踢下线
    monitorKickedOut = (event) => {
        let { isKickedOut } = this.state;
        this.setState({ isKickedOut: false });
        if (isKickedOut) {
            message.warn('您的账号在别处登录，请重新登录', this.state.userData && this.state.userData.messageTime)
            this.setState({ showCallBtn: true })
            this.leave()
            this.handleSendVideoMsg('end')
        }
    }

    // 监听接收消息
    onMessageReceived = event => {
        var that = this;
        // console.log("触发监听了", event)
        let { userData } = this.state;
        let from = event.data[0].from;
        if (('patient' + this.state.chatPatID) == from) {
            this.getChatData("isScroll", "", "");
        }
    }

    // 获取消息列表数据
    getChatData = (isScroll, isLoading, newMessage) => {
        let { doctorData, userData, lastMsgID } = this.state;
        if (isLoading !== "isLoading") {
            this.setState({ refreshing: true });
        }
        let data = {
            params: [{
                admID: this.state.patRowID,
                frUser: 'user' + userData.userID,
                toUser: 'patient' + this.state.chatPatID,
                lastMsgID
                // lastMsgID: chatData&&chatData.length > 0 ? chatData[0].megID : ""
            }]
        }
        $http.post("urlS", this, {
            code: "02090005",
            data: data,
            namespace: "HIS",
            success: function (res) {
                if (+res.errorCode === 0) {
                    let chatData = res.result && res.result.msgData instanceof Array ? res.result.msgData : [];
                    this.setState({ chatData, refreshing: false, moreMsgFlag: res.result.moreMsgFlag, newMessage: newMessage ? newMessage : "" }, () => {

                        // this.getSendHeight();
                        if (this.state.showPicture == true || this.state.showVoiceChatModal == true) {
                            this.onRefMsg && this.onRefMsg.scrollToBottom()
                        }
                        if (isScroll === "isScroll") {
                            // this.messageWrapperScrollBottom();
                        }
                    });
                } else {
                    this.setState({ chatData: [], refreshing: false, moreMsgFlag: "Y", newMessage: newMessage ? newMessage : "" })
                }
            }
        });
    }

    // 重新获取底部高度
    getSendHeight = () => {
        let sendDom = document.getElementById("message-send-box-wrapper");
        var sendHeight = sendDom.clientHeight || sendDom.offsetHeight;
        this.setState({ sendHeight: sendHeight + "px" })
    }

    // input-onChange
    messageValueOnChange(e) {
        this.setState({ messageValue: e }, () => {
            // this.getSendHeight();
        });
    }

    // 消息列表滚动条默认至最低端
    messageWrapperScrollBottom = () => {
        let messageScrollDom = document.querySelector(".am-pull-to-refresh");
        messageScrollDom.scrollTop = messageScrollDom.scrollHeight;
    }

    onRefMessage = ref => {
        this.onRefMsg = ref
    }

    // 图片上传至服务器
    imageUpload = (fileList, success, error) => {
        var that = this;
        let { userData } = this.state;
        let data = new FormData();
        data.append('file', fileList);
        if (fileList.type !== 'image/gif' && fileList.type !== 'image/jpeg' && fileList.type !== 'image/png' && fileList.type !== 'image/bmp') {
            message.error('图片上传格式不正确，请重新上传！', this.state.userData && this.state.userData.messageTime)
            return
        }
        const option = {
            method: 'post',
            mode: 'cors',
            headers: {},
            body: data
        };
        fetch(this.state.addressUrl, option)
            .then(function (response) {
                if (response.ok) {
                    return response.text();
                } else {
                    console.log('网络错误，请稍后再试')
                    return;
                }
            }).then(function (data) {
                let dataS = JSON.parse(data);
                that.setState({
                    filePath: dataS.filePath
                }, () => {
                    that.uploadImg()
                })
            }).catch(function (e) {
                console.log("发送失败： ", e);
                error && error(e);
            })
    }

    uploadImg() {
        let { messageValue, doctorData, userData } = this.state;
        // this.fileToBase64(this.state.filePath).then(res => {
        let data = {
            params: [{
                admID: this.state.patRowID,
                frUser: 'user' + userData.userID,
                toUser: 'patient' + this.state.chatPatID,
                consultText: "",
                picture: this.state.filePath,
            }]
        }
        $http.post("urlS", this, {
            code: "02090004",
            data: data,
            namespace: "HIS",
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        sendStatus: true
                    })
                    this.handleSendImage(res);
                    this.onRefMsg && this.onRefMsg.scrollToBottom()
                    this.onRefMsg && this.onRefMsg.clearInput()
                    this.handleReceive()
                } else {
                    message.error(res.errorMessage, this.state.userData && this.state.userData.messageTime)
                }
            }
        })
        // })
    }

    // 发送
    handleSend = (type, source) => {
        let { messageValue, doctorData, userData } = this.state;
        if (type === "img") {
            let imagePickerDom = document.getElementById("imagePicker");
            this.imageUpload(imagePickerDom.files[0])
        } else {
            let data = {
                params: [{
                    admID: this.state.patRowID,
                    frUser: 'user' + userData.userID,
                    toUser: 'patient' + this.state.chatPatID,
                    consultText: messageValue ? messageValue : source,
                    picture: "",
                }]
            }
            $http.post("urlS", this, {
                code: "02090004",
                data: data,
                namespace: "HIS",
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            messageValue: source,
                            sendStatus: true
                        }, () => {
                            this.handleReceive()
                            this.handleSendText(res)
                            this.onRefMsg && this.onRefMsg.scrollToBottom()
                            this.onRefMsg && this.onRefMsg.clearInput()
                        })
                    } else {
                        message.error(res.errorMessage, this.state.userData && this.state.userData.messageTime)
                    }
                }
            })
        }
    }

    // 发送图片
    handleSendImage = (res) => {
        let { messageValue, doctorData, userData, titleData, patientData } = this.state;
        try {

            let messageContent = {};
            messageContent.userID = userData.userID;
            messageContent.admID = !Util.isEmpty(patientData) ? patientData.admID : '';
            messageContent.patID = !Util.isEmpty(patientData) ? patientData.patID : '';
            messageContent.patName = !Util.isEmpty(titleData) ? titleData.patName : '';
            messageContent.userName = userData.userName;
            messageContent.type = 'M';
            messageContent.text = '';
            messageContent.image = 'Y';
            let message = this.tim.createTextMessage({
                to: 'patient' + this.state.chatPatID,
                conversationType: TIM.TYPES.CONV_C2C,
                payload: {
                    text: JSON.stringify(messageContent),
                }
            });
            // 2. 发送消息
            let promise = this.tim.sendMessage(message);
            if (promise) {
                promise.then((imResponse) => {
                    // 发送成功
                    if (imResponse && imResponse.code === 0) {
                        let chatData = JSON.parse(JSON.stringify(this.state.chatData));
                        // let imgPath = imResponse.data.message.payload.imageInfoArray[0].imageUrl;
                        // let imgPath = 'https://chis.e24health.com/images/consult/' + this.state.filePath;
                        let imgPath = this.state.downloadPath + this.state.filePath;
                        let obj = {
                            picture: imgPath,
                            direction: "right",
                            msgType: "1",
                        }
                        chatData.push(obj);
                        this.setState({ chatData }, () => {
                            // this.getChatData("isScroll", "", ""); // 获取消息
                            // this.messageWrapperScrollBottom();
                            // this.setState({})
                            this.onRefMsg && this.onRefMsg.scrollToBottom()
                        })
                        // this.getChatData("isScroll", "", ""); // 获取消息
                    }
                }).catch((imError) => {
                    // 发送失败
                    message.error('发送失败：', imError);
                    this.deleteChatData(res.result.msgID)
                });
            }
        } catch (e) {
            message.error("发送失败: " + e.message)
        }
    }

    // 删除图文咨询聊天记录
    deleteChatData = (msgID) => {
        let data = {
            params: [{
                msgID
            }]
        }
        $http.post("urlS", this, {
            code: "03070076",
            data: data,
            namespace: "HIS",
            success: function (res) {
                if (+res.errorCode === 0) {
                    console.log(res)
                }
            }
        });
    }

    // 发送文字
    handleSendText = (res) => {
        let { messageValue, doctorData, userData, titleData } = this.state;
        var patientData = JSON.parse(sessionStorage.getItem('patientData'));
        try {

            let messageContent = {};
            messageContent.userID = userData.userID;
            messageContent.admID = !Util.isEmpty(patientData) ? patientData.admID : '';
            messageContent.patID = !Util.isEmpty(patientData) ? patientData.patID : '';
            messageContent.patName = !Util.isEmpty(titleData) ? titleData.patName : '';
            messageContent.userName = userData.userName;
            messageContent.type = 'M';
            messageContent.text = messageValue;
            let message = this.tim.createTextMessage({
                to: 'patient' + this.state.chatPatID,
                conversationType: TIM.TYPES.CONV_C2C,
                payload: {
                    text: JSON.stringify(messageContent)
                }
            });
            // 2. 发送消息
            let promise = this.tim.sendMessage(message);
            if (promise) {
                promise.then((imResponse) => {
                    if (imResponse && imResponse.code === 0) {
                        let chatData = JSON.parse(JSON.stringify(this.state.chatData));
                        let text = imResponse.data.message.payload.text;
                        let obj = {
                            consultText: messageValue,
                            direction: "right",
                            msgType: "1",
                        }
                        chatData.push(obj)
                        this.setState({ messageValue: "", chatData }, () => {
                            // this.getChatData("isScroll", "", ""); // 获取消息
                            // this.messageWrapperScrollBottom();
                            this.onRefMsg && this.onRefMsg.scrollToBottom()
                            // this.setState({})
                        })
                    }
                }).catch((imError) => {
                    // 发送失败 --- 调接口改变消息状态
                    message.error('发送失败：', imError);
                    this.deleteChatData(res && res.result.msgID)
                });
            }
        } catch (error) {
            message.error(error.message);
        }
    }

    fileToBase64(file) {
        let reader = new FileReader();
        reader.readAsDataURL(file);
        return new Promise((resolve, reject) => {
            reader.onload = function (e) { //这里是一个异步，所以获取数据不好获取在实际项目中，就用new Promise解决
                if (e.target.result) {
                    resolve(e.target && e.target.result ? e.target.result : "")
                } else {
                    reject("")
                }
            }
        })
    }


    //计时器
    showTimer() {
        // second++;
        // if (second >= 60) {
        //     second = 0;
        //     minute = minute + 1;
        // }
        // if (minute >= 60) {
        //     minute = 0;
        //     hour = hour + 1;
        // }
        // document.getElementById('timer').innerHTML = ' 已呼叫：' + hour + '：' + minute + '：' + second

        sec++;
        var date = new Date(0, 0)
        date.setSeconds(sec);
        hour = date.getHours(), minute = date.getMinutes(), second = date.getSeconds();
        if (document.getElementById("timer")) {
            document.getElementById("timer").innerText = ' 已呼叫：' + this.two_char(hour) + ":" + this.two_char(minute) + ":" + this.two_char(second);
        }
    }

    two_char(n) {
        return n >= 10 ? n : "0" + n;
    }

    throttle(func, delay) {
        var timer = null;
        var startTime = Date.now();
        return function () {
            var curTime = Date.now();
            var remaining = delay - (curTime - startTime);
            var context = this;
            var args = arguments;
            clearTimeout(timer);
            if (remaining <= 0) {
                func.apply(context, args);
                startTime = Date.now();
            } else {
                timer = setTimeout(() => {
                    console.log('duplicate click');
                }, remaining);
            }
        };
    }


    muteAudio() {
        this.localStream_.muteAudio();
    }

    unmuteAudio() {
        this.localStream_.unmuteAudio();
    }

    muteVideo() {
        this.localStream_.muteVideo();
    }

    unmuteVideo() {
        this.localStream_.unmuteVideo();
    }

    setCameraId(thisDiv) {
        cameraId = $(thisDiv).attr('id');
        console.log('setCameraId: ' + cameraId);
    }

    setMicId(thisDiv) {
        micId = $(thisDiv).attr('id');
        console.log('setMicId: ' + micId);
    }

    handleVideo() {
        $('#video-btn').on('click', () => {
            if (isCamOn) {
                $('#video-btn').attr('src', './img/big-camera-off.png');
                $('#video-btn').attr('title', '打开摄像头');
                $('#member-me').find('.member-video-btn').attr('src', 'img/camera-off.png');
                isCamOn = false;
                this.muteVideo();
            } else {
                $('#video-btn').attr('src', './img/big-camera-on.png');
                $('#video-btn').attr('title', '关闭摄像头');
                $('#member-me').find('.member-video-btn').attr('src', 'img/camera-on.png');
                isCamOn = true;
                this.unmuteVideo();
            }
        });
    }

    handleMicPhone() {
        $('#mic-btn').on('click', () => {
            if (isMicOn) {
                $('#mic-btn').attr('src', './img/big-mic-off.png');
                $('#mic-btn').attr('title', '打开麦克风');
                $('#member-me').find('.member-audio-btn').attr('src', 'img/mic-off.png');
                isMicOn = false;
                this.muteAudio();
            } else {
                $('#mic-btn').attr('src', './img/big-mic-on.png');
                $('#mic-btn').attr('title', '关闭麦克风');
                $('#member-me').find('.member-audio-btn').attr('src', 'img/mic-on.png');
                isMicOn = true;
                this.unmuteAudio();
            }
        });
    }

    setBtnClickFuc() {
        //userid roomid规格
        //$('#userId').on('input', function(e) {
        //    e.preventDefault();
        //    console.log('userId input ' + e.target.value);
        //    let val = $('#userId').val().slice(5);
        //    $('#userId').val('user_'+val.replace(/[^\d]/g,''));
        //});
        $('#roomId').on('input', function (e) {
            e.preventDefault();
            console.log('roomId input ' + e.target.value);
            let val = $('#roomId').val();
            $('#roomId').val(val.replace(/[^\d]/g, ''));
        });
        //login
        //open or close camera
        $('#video-btn').on('click', () => {
            if (isCamOn) {
                $('#video-btn').attr('src', './img/big-camera-off.png');
                $('#video-btn').attr('title', '打开摄像头');
                $('#member-me').find('.member-video-btn').attr('src', 'img/camera-off.png');
                isCamOn = false;
                this.muteVideo();
            } else {
                $('#video-btn').attr('src', './img/big-camera-on.png');
                $('#video-btn').attr('title', '关闭摄像头');
                $('#member-me').find('.member-video-btn').attr('src', 'img/camera-on.png');
                isCamOn = true;
                this.unmuteVideo();
            }
        });
        //open or close microphone
        $('#mic-btn').on('click', () => {
            if (isMicOn) {
                $('#mic-btn').attr('src', './img/big-mic-off.png');
                $('#mic-btn').attr('title', '打开麦克风');
                $('#member-me').find('.member-audio-btn').attr('src', 'img/mic-off.png');
                isMicOn = false;
                this.muteAudio();
            } else {
                $('#mic-btn').attr('src', './img/big-mic-on.png');
                $('#mic-btn').attr('title', '关闭麦克风');
                $('#member-me').find('.member-audio-btn').attr('src', 'img/mic-on.png');
                isMicOn = true;
                this.unmuteAudio();
            }
        });
        //switch main video
        $('#main-video').on('click', () => {
            // let mainVideo = $('.video-box').first();
            // if ($('#main-video').is(mainVideo)) {
            //     return;
            // }
            // //释放main-video grid-area
            // mainVideo.css('grid-area', 'auto/auto/auto/auto');
            // this.exchangeView($('#main-video'), mainVideo);
            //将video-grid中第一个div设为main-video
            $('.video-box').first().css('grid-area', '1/1/3/4');
            //chromeM71以下会自动暂停，手动唤醒
            if (this.getBroswer().broswer == 'Chrome' && this.getBroswer().version < '72') {
                rtc.resumeStreams();
            }
        });

        //chrome60以下不支持popover，防止error
        if (this.getBroswer().broswer == 'Chrome' && this.getBroswer().version < '60')
            return;
        //开启popover
        // $(function () {
        //     $('[data-toggle="popover"]').popover()
        // })
        // $('#camera').popover({
        //     html: true,
        //     content: () => {
        //         return $('#camera-option').html();
        //     }
        // });
        // $('#microphone').popover({
        //     html: true,
        //     content: () => {
        //         return $('#mic-option').html();
        //     }
        // });

        $('#camera').on('click', () => {
            $('#microphone').popover('hide');
            $('.popover-body').find('div').attr('onclick', 'setCameraId(this)');
        });

        $('#microphone').on('click', () => {
            $('#camera').popover('hide');
            $('.popover-body').find('div').attr('onclick', 'setMicId(this)');
        });

        //点击body关闭popover
        // $('body').click(() => {
        //     $('#camera').popover('hide');
        //     $('#microphone').popover('hide');
        // });

        //popover事件
        $('#camera').on('show.bs.popover', () => {
            $('#camera').attr('src', './img/camera-on.png');
        });
        $('#camera').on('hide.bs.popover', () => {
            $('#camera').attr('src', './img/camera.png');
        });

        $('#microphone').on('show.bs.popover', () => {
            $('#microphone').attr('src', './img/mic-on.png');
        });
        $('#microphone').on('hide.bs.popover', () => {
            $('#microphone').attr('src', './img/mic.png');
        });
    }

    exchangeView(a, b) {
        var $div1 = $(a);
        var $div3 = $(b);
        var $temobj1 = $("<div></div>");
        var $temobj2 = $("<div></div>");
        $temobj1.insertBefore($div1);
        $temobj2.insertBefore($div3);
        $div1.insertAfter($temobj2);
        $div3.insertAfter($temobj1);
        $temobj1.remove();
        $temobj2.remove();
    }

    getBroswer() {
        var sys = {};
        var ua = navigator.userAgent.toLowerCase();
        var s;
        (s = ua.match(/edge\/([\d.]+)/)) ? sys.edge = s[1] :
            (s = ua.match(/rv:([\d.]+)\) like gecko/)) ? sys.ie = s[1] :
                (s = ua.match(/msie ([\d.]+)/)) ? sys.ie = s[1] :
                    (s = ua.match(/firefox\/([\d.]+)/)) ? sys.firefox = s[1] :
                        (s = ua.match(/chrome\/([\d.]+)/)) ? sys.chrome = s[1] :
                            (s = ua.match(/opera.([\d.]+)/)) ? sys.opera = s[1] :
                                (s = ua.match(/version\/([\d.]+).*safari/)) ? sys.safari = s[1] : 0;

        if (sys.edge) return { broswer: "Edge", version: sys.edge };
        if (sys.ie) return { broswer: "IE", version: sys.ie };
        if (sys.firefox) return { broswer: "Firefox", version: sys.firefox };
        if (sys.chrome) return { broswer: "Chrome", version: sys.chrome };
        if (sys.opera) return { broswer: "Opera", version: sys.opera };
        if (sys.safari) return { broswer: "Safari", version: sys.safari };

        return { broswer: "", version: "0" };
    }

    loadLogin() {
        var roomId = this.state.roomID;
        this.client_
            .join({ roomId })
            .catch(error => {
                console.log('进房失败 ' + error);
            })
            .then(() => {
                // console.log('进房成功');
                // this.localStream()
                this.join();
                this.updateRoomStatus()
            });
    }

    //医生进入房间，初始化状态
    updateRoomStatus() {
        var params = {
            params: [{
                roomID: this.state.roomID,
                userType: 'U',
                userID: this.state.userData.userID,
                loginType: 'I'
            }]
        }
        $http.post('urlDeault', this, {
            code: "02090002",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                }
            }
        });
    }

    initData() {
        const generator = new LibGenerateTestUserSig(this.state.imAppID, this.state.imSecretKey, EXPIRETIME);
        const userSig = generator.genTestUserSig('user' + this.state.userData.userID);
        this.client_ = TRTC.createClient({
            mode: 'rtc',
            sdkAppId: this.state.imAppID,
            userId: 'user' + this.state.userData.userID,
            userSig: userSig
        });
        this.handleEvents();
    }

    getCameraId() {
        console.log('selected cameraId: ' + cameraId);
        return cameraId;
    }

    getMicrophoneId() {
        console.log('selected microphoneId: ' + micId);
        return micId;
    }


    async join() {
        const generator = new LibGenerateTestUserSig(this.state.imAppID, this.state.imSecretKey, EXPIRETIME);
        const userSig = generator.genTestUserSig('user' + (this.state.userData.userID));
        if (this.isJoined_) {
            console.warn('duplicate RtcClient.join() observed');
            return;
        }
        try {
            console.log('join room success');
            TRTC.getDevices()
                .then(devices => {
                    devices.forEach(item => {
                        console.log('device: ' + item.kind + ' ' + item.label + ' ' + item.deviceId);
                    });
                })
                .catch(error => console.error('getDevices error observed ' + error));

            // populate camera options
            TRTC.getCameras().then(devices => {
                devices.forEach(device => {
                    if (!cameraId) {
                        cameraId = device.deviceId;
                    }
                });
            });

            // populate microphone options
            TRTC.getMicrophones().then(devices => {
                devices.forEach(device => {
                    if (!micId) {
                        micId = device.deviceId;
                    }
                });
            });
            this.isJoined_ = true;
            this.localStream_ = TRTC.createStream({
                userId: 'user' + this.state.userData.userID, audio: true, video: true, mirror: false,
                // cameraId: this.getCameraId(), microphoneId: this.getMicrophoneId(),
            });
            this.localStream_
                .initialize()
                .catch(error => {
                    console.log('初始化本地流失败 ' + error);

                    if (Util.isEmpty(cameraId)) {
                        message.error('当前系统未检测到您的摄像头，请检查设备是否正常开启！', this.state.userData && this.state.userData.messageTime)
                        this.setState({
                            loading: false
                        }, () => {
                            // this.leave()
                        })
                        // return
                    }
                    if (Util.isEmpty(micId)) {
                        message.error('当前系统未检测到您的麦克风，请检查设备是否正常开启！', this.state.userData && this.state.userData.messageTime)
                        this.setState({
                            loading: false
                        }, () => {
                            // this.leave()
                        })
                        // return
                    }
                })
                .then((res) => {
                    console.log('初始化本地流成功');
                    // setTime = setInterval(() => { this.loginTencent(userSig, 'video') }, 10000)
                    // this.loadLocalStaem(this.localStream_)
                    var x = document.createElement("AUDIO");
                    x.id = 'audio_tip'
                    x.setAttribute("src", "https://chis.e24health.com/images/Voice/startvideo.mp3");
                    // x.setAttribute("controls", "controls");
                    x.setAttribute("autoplay", "autoplay");
                    x.setAttribute("loop", "loop");
                    x.setAttribute("display", "none");
                    document.body.appendChild(x);
                });
            try {
                await this.localStream_.initialize();
                console.log('initialize local stream success');

                this.localStream_.on('player-state-changed', event => {
                    console.log(`local stream ${event.type} player is ${event.state}`);
                });
                //设置1080p视频
                this.localStream_.setVideoProfile({ width: 1920, height: 1080, frameRate: 15, bitrate: 2000 /* kpbs */ });
                // publish the local stream
                await this.publish();

                this.localStream_.play('main-video');
                $('#main-video-btns').show();
                $('#mask_main').appendTo($('#player_' + this.localStream_.getId()));
                // });
                this.setState({
                    loading: false
                })

            } catch (e) {
                console.error('failed to initialize local stream - ' + e);
            }
        } catch (e) {
            console.error('join room failed! ' + e);
        }
        //更新成员状态
        let states = this.client_.getRemoteMutedState();
        for (let state of states) {
            if (state.audioMuted) {
                $('#' + state.userId)
                    .find('.member-audio-btn')
                    .attr('src', './img/mic-off.png');
            }
            if (state.videoMuted) {
                $('#' + state.userId)
                    .find('.member-video-btn')
                    .attr('src', './img/camera-off.png');
                $('#mask_' + this.members_.get(state.userId).getId()).show();
            }
        }
    }

    async leave() {
        clearTimeout(setTime);
        clearTimeout(timeout);
        if (!this.isJoined_) {
            console.warn('leave() - please join() firstly');
            return;
        }
        // ensure the local stream is unpublished before leaving.
        // await this.unpublish();

        // leave the room
        await this.client_.leave();

        this.localStream_.stop();
        this.localStream_.close();
        this.localStream_ = null;
        this.isPublished_ = false;
        this.isAudioMuted = false;
        this.isVideoMuted = false;
        this.isJoined_ = false;
        this.remoteStreams_ = [];
        this.members_ = new Map();
        isCamOn = true;
        isMicOn = true;
        isScreenOn = false;
        isJoined = true;
        rtc = null;
        share = null;
        shareUserId = '';
        cameraId = '';
        micId = '';
        this.resetView();
        this.handleLeaveRoom()
    }

    handleLeaveRoom(status) {
        var roomID = JSON.parse(sessionStorage.getItem('roomID'))
        var params = {
            params: [{
                roomID: status == 'clear' ? roomID : (this.state.roomID),
                userType: 'U',
                userID: this.state.userData.userID,
                loginType: 'O'
            }]
        }
        $http.post('urlDeault', this, {
            code: "02090002",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                }
            }
        });
    }

    resetView() {
        isCamOn = true;
        isMicOn = true;
        isScreenOn = false;
        isJoined = true;
        $('#main-video-btns').hide();
        $('#video-btn').attr('src', './img/big-camera-on.png');
        $('#mic-btn').attr('src', './img/big-mic-on.png');
        $('#screen-btn').attr('src', './img/screen-off.png');
        $('#member-me').find('.member-video-btn').attr('src', 'img/camera-on.png');
        $('#member-me').find('.member-audio-btn').attr('src', 'img/mic-on.png');
        $('.mask').hide();
        //清空member-list
        if ($('#member-list')) {
            $('#member-list')
                .find('.member')
                .each((index, element) => {
                    if ($(element).parent().attr('id') != 'member-me') {
                        $(element).parent().remove();
                    }
                });
        }
    }

    async publish() {
        if (!this.isJoined_) {
            console.warn('publish() - please join() firstly');
            return;
        }
        if (this.isPublished_) {
            console.warn('duplicate RtcClient.publish() observed');
            return;
        }
        try {
            // await this.client_.publish(this.localStream_);
            await this.client_
                .publish(this.localStream_)
                .catch(error => {
                    console.log('本地流发布失败 ' + error);
                })
                .then(() => {
                    console.log('本地流发布成功');
                    // this.initLocalSteam(localStream)
                });
        } catch (e) {
            console.error('failed to publish local stream ' + e);
            this.isPublished_ = false;
        }

        this.isPublished_ = true;
    }

    async unpublish() {
        if (!this.isJoined_) {
            console.warn('unpublish() - please join() firstly');
            return;
        }
        if (!this.isPublished_) {
            console.warn('RtcClient.unpublish() called but not published yet');
            return;
        }

        await this.client_.unpublish(this.localStream_);
        this.isPublished_ = false;
    }

    muteLocalAudio() {
        this.localStream_.muteAudio();
    }

    unmuteLocalAudio() {
        this.localStream_.unmuteAudio();
    }

    muteLocalVideo() {
        this.localStream_.muteVideo();
    }

    unmuteLocalVideo() {
        this.localStream_.unmuteVideo();
    }

    resumeStreams() {
        this.localStream_.resume();
        for (let stream of this.remoteStreams_) {
            stream.resume();
        }
    }

    addMemberView(id) {
        let memberElm = $('#member-me').clone();
        memberElm.attr('id', id);
        memberElm.find('div.member-id').html(id);
        memberElm.css('display', 'flex');
        memberElm.appendTo($('#member-list'));
    }

    removeView(id) {
        if ($('#' + id)[0]) {
            $('#' + id).remove();
            //将video-grid中第一个div设为main-video
            $('.video-box').first().css('grid-area', '1/1/3/4');
        }
    }

    addVideoView(id, isLocal = false) {
        let div = $('<div/>', {
            id: id,
            class: 'video-box',
            style: 'justify-content: center'
        });
        div.appendTo('#video-grid');
        //设置监听
        div.click(() => {
            // let mainVideo = $('.video-box').first();
            // if (div.is(mainVideo)) {
            //     return;
            // }
            // //释放main-video grid-area
            // mainVideo.css('grid-area', 'auto/auto/auto/auto');
            // this.exchangeView(div, mainVideo);
            //将video-grid中第一个div设为main-video
            $('.video-box').first().css('grid-area', '1/1/3/4');
            //chromeM71以下会自动暂停，手动唤醒
            if (this.getBroswer().broswer == 'Chrome' && this.getBroswer().version < '72') {
                rtc.resumeStreams();
            }
        });
    }

    isHidden() {
        var hidden, visibilityChange;
        if (typeof document.hidden !== "undefined") {
            hidden = "hidden";
            visibilityChange = "visibilitychange";
        } else if (typeof document.msHidden !== "undefined") {
            hidden = "msHidden";
            visibilityChange = "msvisibilitychange";
        } else if (typeof document.webkitHidden !== "undefined") {
            hidden = "webkitHidden";
            visibilityChange = "webkitvisibilitychange";
        }
        return document[hidden];
    }

    handleEvents() {
        this.client_.on('error', err => {
            console.error(err);
            alert(err);
            location.reload();
        });
        this.client_.on('client-banned', err => {
            console.error('client has been banned for ' + err);
            if (!this.isHidden()) {
                alert('您的账号在已别处登录！');
                location.reload();
            } else {
                document.addEventListener(
                    'visibilitychange',
                    () => {
                        if (!this.isHidden()) {
                            alert('您的账号在已别处登录！');
                            location.reload();
                        }
                    },
                    false
                );
            }
        });
        // fired when a remote peer is joining the room
        this.client_.on('peer-join', evt => {
            const userId = evt.userId;
            console.log('peer-join ' + userId);
            if (userId !== shareUserId) {
                this.addMemberView(userId);
            }
        });
        // fired when a remote peer is leaving the room
        this.client_.on('peer-leave', evt => {
            message.error('对方已挂断视频！', this.state.userData && this.state.userData.messageTime)
            this.setState({
                sendMeg: false//呼叫，对方未接通通过该状态，给患者端发送一条tim消息
            })
            const userId = evt.userId;
            this.removeView(userId);
            clearTimeout(setTime);
            clearTimeout(timeout);
            console.log('peer-leave ' + userId);
        });
        // fired when a remote stream is added
        this.client_.on('stream-added', evt => {
            const remoteStream = evt.stream;
            const id = remoteStream.getId();
            const userId = remoteStream.getUserId();
            this.members_.set(userId, remoteStream);
            console.log(`remote stream added: [${userId}] ID: ${id} type: ${remoteStream.getType()}`);
            if (remoteStream.getUserId() === shareUserId) {
                // don't need screen shared by us
                this.client_.unsubscribe(remoteStream);
            } else {
                console.log('subscribe to this remote stream');
                this.client_.subscribe(remoteStream);
            }
            if (!Util.isEmpty(id)) {
                this.setState({
                    showCalled: true,
                    showCallBtn: false,
                    sendMeg: true//呼叫，对方未接通通过该状态，给患者端发送一条tim消息
                }, () => {
                    this.handleReceive()//叫号成功后接诊
                    //用于组件销毁时，更新视频问诊状态
                    sessionStorage.setItem('showCalled', JSON.stringify('show'))
                    clearTimeout(time)
                    clearTimeout(setTime);
                    document.getElementById('video-grid').style.display = 'block'
                    var child = document.getElementById("audio_tip");
                    if (child) {
                        child.parentNode.removeChild(child);
                    }
                })
            } else {
                this.setState({
                    sendMeg: true
                })
            }
        });
        // fired when a remote stream has been subscribed
        this.client_.on('stream-subscribed', evt => {
            const uid = evt.userId;
            const remoteStream = evt.stream;
            const id = remoteStream.getId();
            this.remoteStreams_.push(remoteStream);
            remoteStream.on('player-state-changed', event => {
                console.log(`${event.type} player is ${event.state}`);
                if (event.type == 'video' && event.state == 'STOPPED') {
                    $('#mask_' + remoteStream.getId()).show();
                    $('#' + remoteStream.getUserId())
                        .find('.member-video-btn')
                        .attr('src', 'img/camera-off.png');
                }
                if (event.type == 'video' && event.state == 'PLAYING') {
                    $('#mask_' + remoteStream.getId()).hide();
                    $('#' + remoteStream.getUserId())
                        .find('.member-video-btn')
                        .attr('src', 'img/camera-on.png');
                }
            });
            this.addVideoView(id);
            // objectFit 为播放的填充模式，详细参考：https://trtc-1252463788.file.myqcloud.com/web/docs/Stream.html#play
            remoteStream.play(id, { objectFit: 'cover' });
            //添加“摄像头未打开”遮罩
            let mask = $('#mask_main').clone();
            mask.attr('id', 'mask_' + id);
            mask.appendTo($('#player_' + id));
            mask.hide();
            if (!remoteStream.hasVideo()) {
                mask.show();
                $('#' + remoteStream.getUserId())
                    .find('.member-video-btn')
                    .attr('src', 'img/camera-off.png');
            }
            console.log('stream-subscribed ID: ', id);
            this.setState({ showVideoID: id })
        });
        // fired when the remote stream is removed, e.g. the remote user called Client.unpublish()
        this.client_.on('stream-removed', evt => {
            const remoteStream = evt.stream;
            const id = remoteStream.getId();
            remoteStream.stop();
            this.remoteStreams_ = this.remoteStreams_.filter(stream => {
                return stream.getId() !== id;
            });
            this.removeView(id);
            console.log(`stream-removed ID: ${id}  type: ${remoteStream.getType()}`);
        });

        this.client_.on('stream-updated', evt => {
            const remoteStream = evt.stream;
            let uid = this.getUidByStreamId(remoteStream.getId());
            if (!remoteStream.hasVideo()) {
                $('#' + uid)
                    .find('.member-video-btn')
                    .attr('src', 'img/camera-off.png');
            }
            console.log(
                'type: ' +
                remoteStream.getType() +
                ' stream-updated hasAudio: ' +
                remoteStream.hasAudio() +
                ' hasVideo: ' +
                remoteStream.hasVideo() +
                ' uid: ' +
                uid
            );
        });

        this.client_.on('mute-audio', evt => {
            console.log(evt.userId + ' mute audio');
            $('#' + evt.userId)
                .find('.member-audio-btn')
                .attr('src', 'img/mic-off.png');
        });
        this.client_.on('unmute-audio', evt => {
            console.log(evt.userId + ' unmute audio');
            $('#' + evt.userId)
                .find('.member-audio-btn')
                .attr('src', 'img/mic-on.png');
        });
        this.client_.on('mute-video', evt => {
            console.log(evt.userId + ' mute video');
            $('#' + evt.userId)
                .find('.member-video-btn')
                .attr('src', 'img/camera-off.png');
            let streamId = this.members_.get(evt.userId).getId();
            if (streamId) {
                $('#mask_' + streamId).show();
            }
        });
        this.client_.on('unmute-video', evt => {
            console.log(evt.userId + ' unmute video');
            $('#' + evt.userId)
                .find('.member-video-btn')
                .attr('src', 'img/camera-on.png');
            const stream = this.members_.get(evt.userId);
            if (stream) {
                let streamId = stream.getId();
                if (streamId) {
                    $('#mask_' + streamId).hide();
                }
            }
        });
    }

    showStreamState(stream) {
        console.log('has audio: ' + stream.hasAudio() + ' has video: ' + stream.hasVideo());
    }

    getUidByStreamId(streamId) {
        for (let [uid, stream] of this.members_) {
            if (stream.getId() == streamId) {
                return uid;
            }
        }
    }

    //打开、关闭图文
    showPictuerAndTeat() {
        if (this.state.showPicture == true) {
            this.setState({
                showPicture: false,
            }, () => {
                if (window.innerWidth > 1500) {
                    document.getElementById('drag').style.height = '740px'
                    document.getElementById('drag').style.width = '480px'
                } else {
                    document.getElementById('drag').style.height = '550px'
                    document.getElementById('drag').style.width = '400px'
                }
                this.signOut()
            })
        } else {
            this.setState({
                showPicture: true
            }, () => {
                if (window.innerWidth > 1500) {
                    document.getElementById('drag').style.height = '740px'
                    document.getElementById('drag').style.width = '1000px'
                } else {
                    document.getElementById('drag').style.height = '550px'
                    document.getElementById('drag').style.width = '800px'
                }
                this.getChatData("isScroll", "", "");
                const generator = new LibGenerateTestUserSig(this.state.imAppID, this.state.imSecretKey, EXPIRETIME);
                const userSig = generator.genTestUserSig('user' + (this.state.userData.userID));
                let options = {
                    SDKAppID: this.state.imAppID
                }
                this.tim = TIM.create(options); // SDK 实例通常用 tim 表示
                // 设置 SDK 日志输出级别，详细分级请参见 setLogLevel 接口的说明
                this.tim.setLogLevel(0); // 普通级别，日志量较多，接入时建议使用
                // tim.setLogLevel(1); // release 级别，SDK 输出关键信息，生产环境时建议使用

                // 注册 COS SDK 插件
                this.tim.registerPlugin({ 'cos-js-sdk': COS });
                this.queryWhetherTheUserExists(userSig)
                // this.loginTencent(userSig, 'user')
            })
        }
    }

    //过号
    handlePassNum(status) {
        var patientData = JSON.parse(sessionStorage.getItem('patientData'));
        this.setState({ disPassNum: true })
        var params = {
            params: [{
                admID: this.state.nextAdmID ? this.state.nextAdmID : (!Util.isEmpty(patientData) ? patientData.admID : ''),
                userID: this.state.userData.userID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03100059",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        callStatus: true,
                        disPassNum: false
                    })
                    message.success('过号成功！', this.state.userData && this.state.userData.messageTime)
                    if (status == 'next') {
                        this.loadVideoCall('next')
                        setTimeout(() => {
                            this.onLoadData.loadChildData()
                        }, 300)
                        this.onLoadData.handleDisableBtn('show')
                    } else {
                        this.setState({
                            showVideoCallModal: false,
                            showVoiceChatModal: false,
                            continueStatus: false,
                            second: 0,
                            minute: 0,
                            hour: 0,
                            sec: 0,
                            showCalled: false,
                            showPicture: false,
                            isKickedOut: false,
                            cameraId: '',
                            micId: '',
                        }, () => {
                            second = 0, minute = 0, hour = 0, sec = 0
                            this.leave()
                            this.onLoadData.loadChildData()
                            this.onLoadData.handleDisableBtn('show')
                            clearTimeout(time)
                            if (this.state.showPicture) {
                                this.signOut()
                            }
                            var child = document.getElementById("audio_tip");
                            if (child) {
                                child.parentNode.removeChild(child);
                            }
                        })
                    }
                }
            }
        });
    }

    //视频呼叫
    loadVideoCall(type) {
        var params = {
            params: [{
                admID: !Util.isEmpty(this.state.nextPatientMsg) ? this.state.nextPatientMsg.admID : '',
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                locID: this.state.userData.locID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "03100058",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        nextAdmID: !Util.isEmpty(this.state.nextPatientMsg) ? this.state.nextPatientMsg.admID : ''
                    })
                    // this.handleReceive()//叫号成功后接诊
                    // message.success('叫号成功')
                    if (type == 'next') {
                        setTimeout(() => {
                            this.loadNextPatientMsg()
                        }, 300)
                    }
                }
            }
        });
    }

    //接诊
    handleReceive() {
        var params = {
            params: [{
                admID: this.state.rowId,
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                locID: this.state.userData.locID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "03100060",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                }
            }
        });
    }

    //结束本次视频问诊
    handleEndOfReceive() {
        var that = this;
        confirm({
            title: '结束问诊',
            content: '您确定要结束本次问诊吗？',
            okText: '是',
            cancelText: '否',
            onOk() {
                document.getElementById('drag').style.display = 'none'
                that.setState({
                    showCalled: false
                }, () => {
                    that.handleEndReceive()
                    that.onLoadData.handleDisableBtn('show')
                    that.leave()
                })
            },
            onCancel() {

            },
        });
    }

    //挂断电话
    handleHangUpVideo() {
        var that = this;
        confirm({
            title: '挂断视频',
            content: '您确定要挂断视频吗？',
            okText: '是',
            cancelText: '否',
            onOk() {
                if (that.state.showCalled == true && Util.isEmpty(that.state.sendMeg)) {
                    that.handleSendVideoMsg('end')
                }
                that.setState({
                    showCallBtn: true,//为true,可以直接呼叫电话
                    cameraId: '',
                    micId: '',
                    sendMeg: undefined
                }, () => {
                    clearTimeout(setTime);
                    clearTimeout(timeout);
                    that.leave()
                    var child = document.getElementById("audio_tip");
                    if (child) {
                        child.parentNode.removeChild(child);
                    }
                    // that.onLoadData.handleDisableBtn('show')
                })
            },
            onCancel() {

            },
        });
    }

    //双击事件，防止双击后把用户踢出房间
    onDoubleVideoCode() {
        clearTimeout(timeout);
        console.dir('双击事件')
    }

    //视频呼叫
    handleVideoCode() {
        clearTimeout(timeout)
        timeout = setTimeout(() => {
            if (this.state.continueStatus == true) {
                TRTC.Logger.setLogLevel(TRTC.Logger.LogLevel.DEBUG);
                TRTC.Logger.enableUploadLog();
                //视频弹框后，背面的视频呼叫按钮置灰
                this.onLoadData.handleDisableBtn('disable')
                // this.initDragList()
                this.initData()
                this.setBtnClickFuc()
                this.loadLogin()
                setTimeout(() => {
                    this.loadNextPatientMsg()//获取下一位患者信息
                }, 500)
                const generator = new LibGenerateTestUserSig(this.state.imAppID, this.state.imSecretKey, EXPIRETIME);
                const userSig = generator.genTestUserSig('user' + (this.state.userData.userID));
                //用于组件销毁时，更新视频问诊状态
                //视频弹框后，背面的视频呼叫按钮置灰
                this.onLoadData.loadChildData()
                let options = {
                    SDKAppID: this.state.imAppID
                }
                this.tim = TIM.create(options); // SDK 实例通常用 tim 表示
                // 设置 SDK 日志输出级别，详细分级请参见 setLogLevel 接口的说明
                this.tim.setLogLevel(0); // 普通级别，日志量较多，接入时建议使用
                // tim.setLogLevel(1); // release 级别，SDK 输出关键信息，生产环境时建议使用
                // 注册 COS SDK 插件
                this.tim.registerPlugin({ 'cos-js-sdk': COS });
                this.loginTencent(userSig, 'video')
                setTime = setInterval(() => { this.loginTencent(userSig, 'video') }, 10000)
                this.setState({
                    showCalled: true,
                    showCallBtn: false
                })
            } else {
                TRTC.Logger.setLogLevel(TRTC.Logger.LogLevel.DEBUG);
                TRTC.Logger.enableUploadLog();
                //视频弹框后，背面的视频呼叫按钮置灰
                this.onLoadData.handleDisableBtn('disable')
                // this.initDragList()
                this.initData()
                this.setBtnClickFuc()
                this.loadLogin()
                setTimeout(() => {
                    this.loadNextPatientMsg()//获取下一位患者信息
                }, 500)
                const generator = new LibGenerateTestUserSig(this.state.imAppID, this.state.imSecretKey, EXPIRETIME);
                const userSig = generator.genTestUserSig('user' + (this.state.userData.userID));
                //用于组件销毁时，更新视频问诊状态
                //视频弹框后，背面的视频呼叫按钮置灰
                this.onLoadData.loadChildData()
                let options = {
                    SDKAppID: this.state.imAppID
                }
                this.tim = TIM.create(options); // SDK 实例通常用 tim 表示
                // 设置 SDK 日志输出级别，详细分级请参见 setLogLevel 接口的说明
                this.tim.setLogLevel(0); // 普通级别，日志量较多，接入时建议使用
                // tim.setLogLevel(1); // release 级别，SDK 输出关键信息，生产环境时建议使用
                // 注册 COS SDK 插件
                this.tim.registerPlugin({ 'cos-js-sdk': COS });
                this.loginTencent(userSig, 'video')
                setTime = setInterval(() => { this.loginTencent(userSig, 'video') }, 10000)
                this.setState({
                    showCalled: true,
                    showCallBtn: false
                })
            }
        }, 300)
    }

    handleCannel(type) {
        document.getElementById('drag').style.display = 'none'
        this.onLoadData.handleDisableBtn('show')
        // if (this.state.statusCode !== 'A') {
        this.loadCloseVideoMsg(type)
        // }
        this.leave()
        clearTimeout(time)
        var child = document.getElementById("audio_tip");
        if (child) {
            child.parentNode.removeChild(child);
        }
    }

    //暂时中断图文咨询
    handleCloseChatModal() {
        this.setState({
            showVoiceChatModal: false,
            sendStatus: false
        })
        document.getElementById('drag').style.display = 'none'
        this.signOut()
        this.hideModal('isShowCloseModal')
    }

    //结束图文对话
    handleCloseChatReceiveModal() {
        this.setState({
            showVoiceChatModal: false,
            sendStatus: false
        })
        document.getElementById('drag').style.display = 'none'
        this.handleEndReceive()
        this.signOut()
        this.hideModal('isShowCloseModal')
    }

    //暂时关闭视频对话
    handleCloseVideoModal() {
        if (this.state.showCalled == true && Util.isEmpty(this.state.sendMeg)) {
            this.handleSendVideoMsg('end')
        }
        document.getElementById('drag').style.display = 'none'
        this.hideModal('isShowCloseModal')
        this.onLoadData.handleDisableBtn('show')
        this.onLoadData.loadChildData()
        this.setState({
            showVideoCallModal: false,
            showVoiceChatModal: false,
            continueStatus: false,
            second: 0,
            minute: 0,
            hour: 0,
            sec: 0,
            showCalled: false,
            showPicture: false,
            isKickedOut: false,
            cameraId: '',
            micId: '',
            sendMeg: undefined//清除该状态
        }, () => {
            second = 0, minute = 0, hour = 0, sec = 0
            this.leave()
            clearTimeout(time)
            if (this.state.showPicture) {
                this.signOut()
            }
        })
    }

    //结束视频就诊
    handleCloseVideoReceiveModal() {
        document.getElementById('drag').style.display = 'none'
        this.hideModal('isShowCloseModal')
        this.onLoadData.handleDisableBtn('show')
        this.setState({
            showVideoCallModal: false,
            showVoiceChatModal: false,
            continueStatus: false,
            second: 0,
            minute: 0,
            hour: 0,
            sec: 0,
            showCalled: false,
            showPicture: false,
            isKickedOut: false,
            cameraId: '',
            micId: '',
        }, () => {
            second = 0, minute = 0, hour = 0, sec = 0
            this.leave()
            this.handleEndReceive()
            clearTimeout(time)
            if (this.state.showPicture) {
                this.signOut()
            }
        })
    }

    //过号呼叫下一位
    handleEndOfReceiveCallNext(roomId) {
        this.hideModal('isShowCloseModal')
        this.setState({
            second: 0,
            minute: 0,
            hour: 0,
            sec: 0,
            showCalled: false,
            showPicture: false,
            isKickedOut: false,
            roomID: roomId
        }, () => {
            second = 0, minute = 0, hour = 0, sec = 0
            // clearTimeout(time)
            this.handleEndReceive('next')
            if (Util.isEmpty(roomId)) {
                message.error('房间号不能为空', this.state.userData && this.state.userData.messageTime)
                return
            } else {
                this.loadLogin()
            }
            if (this.state.showPicture) {
                this.signOut()
            }
        })
    }

    onMouseOver() {
        // this.setState({})
    }

    // 切换tabs
    upDataComponentSource = (data) => {
        console.log(data)
        this.setState({
            componentSource: data,
            changeComponent: this.getDefaultChangeComponent(data),
            isShowOutPatientModal: true,
            isShowTriageSystemModal: true
        })
    }

    // 添加至黑名单
    addToBlacklist = () => {
        const { titleData } = this.state;
        if (!Util.isEmpty(titleData)) {
            this.blacklistRef && this.blacklistRef.modifyVisible(true, { ...titleData });
        }
    }

    render() {
        const { patientFlag, cannelStopFlag } = this.props;
        var disbledStatus = JSON.parse(sessionStorage.getItem('patientData'))
        var activeKey = JSON.parse(sessionStorage.getItem('activeKey'));
        var { dataSource, titleData } = this.state;
        var componentOption = []
        dataSource && dataSource.map((item, index) => {
            componentOption.push(
                <Step key={index} style={{ cursor: 'pointer' }} title={<Tooltip title={this.state.userData.language == 'EN' ? item.ENDesc : item.title}>
                    {this.state.userData.language == 'EN' ? item.ENDesc : item.title}</Tooltip>}
                    disabled={Util.isEmpty(disbledStatus) ? true :
                        (((!Util.isEmpty(this.state.titleData) && this.state.titleData.typeCode == 'IMAGE' ||
                            this.state.statusNote == 'RR' || this.state.showVoiceChatModal == true) && (item.code !== '03050040' && item.code !== '03050055')) ? true : false)}
                    onClick={this.onChangeStepComponent.bind(this, item)} />)
        })

        const style = {
            float: 'right',
            width: '79.9%',
            height: this.state.showPicture == true ? (dragHeight - 130) : (dragHeight - 130),
            overflow: 'auto'
        }

        let windowHost = window.location && window.location.origin ? window.location.origin : (window.location && window.location.protocol ? (window.location.protocol + '//' + window.location.hostname) : "");
        let patientUrl = !Util.isEmpty(this.state.titleData) ? this.state.titleData.patImage : ''
        var patientImg = patientUrl ? (patientUrl.indexOf("http") !== -1 ? patientUrl : windowHost + patientUrl) : '';

        return <div className='outpatient-station-body' style={{ height: '100%', width: '100%', overflowX: 'hidden' }}>
            <Spin spinning={this.state.saveStatus} tip='加载中...'>
                <PatientCourseInfo
                    onRef={this.onConsumeRef}
                />
                {/**视频关闭窗口 */}
                <ShowCloseModal isShow={this.state.isShowCloseModal}
                    activeKey={this.state.activeKey}
                    handleCloseChatModal={this.handleCloseChatModal.bind(this)}
                    handleCloseVideoModal={this.handleCloseVideoModal.bind(this)}
                    handleCloseVideoReceiveModal={this.handleCloseVideoReceiveModal.bind(this)}
                    handleEndOfReceiveCallNext={this.handleEndOfReceiveCallNext.bind(this)}
                    handleCloseChatReceiveModal={this.handleCloseChatReceiveModal.bind(this)}
                    onHide={this.hideModal.bind(this, 'isShowCloseModal')}>
                </ShowCloseModal>
                <div className='out-patient-style'>
                    <div style={{ float: 'left', width: '10.7%', display: patientFlag === 'N' ? 'none' : 'block' }}>
                        <Card>
                            <div>
                                <div style={{ textAlign: 'center' }}>
                                    {
                                        !Util.isEmpty(patientUrl) ? <img className='splice-patient-img' src={patientImg} /> : <div className={this.state.titleData && this.state.titleData.patSexCode == '1' ?
                                            'splice-boys' : (this.state.titleData && this.state.titleData.patSexCode == '2' ? 'splice-girls' : 'splice-girls')}></div>
                                    }
                                </div>
                                <div style={{ fontSize: '14px' }}>
                                    <div style={{ padding: '0 0 0 30px' }}>
                                        <div style={{ color: '#333333', fontWeight: 'bold', cursor: 'pointer' }}>
                                            <Tooltip placement="topLeft" title={!Util.isEmpty(titleData) ? (titleData?.blackListobj?.blackFlag === 'Y' ? '修改黑名单信息' : '添加至黑名单') : '请先选择患者'}>
                                                <img src={titleData?.blackListobj?.blackFlag === 'Y' ? icon_name_blocklist : icon_name} style={{ marginRight: 20, marginBottom: 3 }} onClick={this.addToBlacklist} />
                                            </Tooltip>
                                            <Tooltip placement="topLeft" title="患者历程">
                                                <span onClick={this.showTimeout.bind(this)}>{this.state.titleData ? this.state.titleData.patName || '--' : '--'}</span>
                                            </Tooltip>
                                        </div>

                                        <div style={{ marginTop: 10 }}><img src={icon_gender} style={{ marginRight: 20, marginBottom: 3 }} />
                                            {this.state.titleData ? this.state.titleData.patSexDesc || '--' : '--'}</div>

                                        <div style={{ marginTop: 10 }}><img src={icon_expense} style={{ marginRight: 20, marginBottom: 3 }} />
                                            {this.state.titleData ? this.state.titleData.patAge || '--' : '--'}</div>

                                        <div style={{ marginTop: 10 }}><img src={icon_icon} style={{ marginRight: 20, marginBottom: 3 }} />
                                            {this.state.titleData ? this.state.titleData.patMobile || '--' : '--'}</div>

                                        <div style={{ marginTop: 10 }}><Icon className='statusdesc-splice' style={{ marginRight: 20 }} />
                                            {this.state.titleData ? this.state.titleData.patSocialStatusDesc || '--' : '--'}</div>

                                        <div style={{ marginTop: 10 }} onDoubleClick={this.showExamineModal.bind(this)}><Icon className='typeDesc-splice' style={{ marginRight: 20 }} />
                                            {this.state.titleData ? this.state.titleData.patTypeDesc || '--' : '--'}</div>

                                        <div style={{ color: '#007AFF', marginTop: 10, marginBottom: 10 }}><Icon className='account-splice' style={{ marginRight: 20 }} />
                                            {this.state.titleData ? this.state.titleData.accountBalance || '--' : 0}</div>
                                    </div>
                                </div>
                            </div>
                        </Card>

                        <Card className="scroll-bar-style" style={{ marginTop: 5, height: store.getState().tableHeight.y - 165, overflow: 'auto' }}>
                            <ShowCommonNavigationPage patientData={JSON.parse(sessionStorage.getItem('patientData'))}></ShowCommonNavigationPage>
                        </Card>
                    </div>

                    <Card style={{ float: 'right', width: patientFlag === 'N' ? '100%' : '89%' }}>
                        <div style={{ display: 'flex' }}>
                            <div className='doctor-step-cls' style={{ marginTop: 10, marginLeft: '5%', marginRight: '5%', width: cannelStopFlag === 'N' ? '100%' : '94%' }}>
                                <Steps onChange={this.change.bind(this)} type="navigation"
                                    current={this.state.current} size='small'>
                                    {componentOption}
                                </Steps>
                            </div>
                            <div style={{ width: '5.3%', borderLeft: '1px solid #EEEEEE', textAlign: 'center', display: cannelStopFlag === 'N' ? 'none' : 'block' }}>
                                {this.state.statusCode !== 'A' ? <div
                                ><div style={{ color: '#666666' }}>{this.setMessage('DoctorAdviceModalCannelApp', 'descripts')}</div><Divider />
                                    <div style={{ cursor: 'pointer', color: 'red', marginBottom: 5 }} onClick={this.handleCannelStop.bind(this)}>取消结束</div>
                                </div>
                                    : <div><div style={{ cursor: 'pointer', color: '#1890FF' }}
                                        onClick={this.onCannelPatient.bind(this)}>{this.setMessage('DoctorAdviceModalCannelApp', 'descripts')}</div><Divider />
                                        <div style={{ cursor: 'pointer', color: 'red', marginBottom: 5 }} onClick={this.handleCannelStop.bind(this)}>取消结束</div>
                                    </div>}
                            </div>

                        </div>
                        <PatientsClinicalTabPane current={this.state.current} hashROuter={this.hashROuter.bind(this)}
                            ref={this.onRef} componentSource={this.state.componentSource}
                            openWindowBySubTab={this.openWindowBySubTab.bind(this)}
                            patientData={JSON.parse(sessionStorage.getItem('patientData'))}
                            loadStepCompent={this.loadStepCompent()}
                            changeComponent={this.state.changeComponent}>
                        </PatientsClinicalTabPane>
                    </Card>
                </div>
                {(this.state.showVoiceChatModal == true || this.state.showVideoCallModal == true) ?
                    <div id="drag"
                        style={this.state.showVoiceChatModal == true ? { width: '900px', height: '700px' } : null}>
                        <Spin spinning={this.state.loading} tip='正在加载视频设备'>
                            <div className="title">
                                <h2>{this.state.showVoiceChatModal == true ? '图文咨询' : (this.state.showVideoCallModal == true ? '视频问诊' : '')}</h2>
                                <div>
                                    <a className="min" href="javascript:;" title="最小化"></a>
                                    <a className="max" href="javascript:;" title="最大化"></a>
                                    <a className="revert" href="javascript:;" title="还原"></a>
                                    <a className="close" href="javascript:;" title="关闭"></a>
                                </div>
                            </div>
                            <div className="resizeL"></div>
                            <div className="resizeT"></div>
                            <div className="resizeR"></div>
                            <div className="resizeB"></div>
                            <div className="resizeLT"></div>
                            <div className="resizeTR"></div>
                            <div className="resizeBR"></div>
                            <div className="resizeLB"></div>
                            {this.state.showVideoCallModal == true ? <div className="content" style={{ display: 'flex', background: '#F1F1F1', height: (dragHeight - 60) }}>
                                <div style={{ width: this.state.showPicture == true ? '45%' : '100%' }}>
                                    {this.state.showCalled == true ? <Card bodyStyle={{ padding: '5px' }}>接诊成功<br />当前2人在视频问诊室</Card> : null}
                                    <div style={{ marginTop: 5 }}>
                                        {this.state.showCalled == true ?
                                            <Card style={{ float: 'left', width: '20%', height: this.state.showPicture == true ? (dragHeight - 130) : (dragHeight - 130), textAlign: 'center' }} bodyStyle={{ padding: '5px' }}>
                                                <div style={{ cursor: 'pointer' }} onClick={this.showPictuerAndTeat.bind(this)}>
                                                    <img src={imagePicture} style={{ marginTop: 10 }} />
                                                    <div style={{ marginTop: 10 }}>{this.state.showPicture == true ? '关闭图文' : '打开图文'}</div>
                                                </div>
                                                {/* <div style={{ cursor: 'pointer' }}>
                                        <img src={imageInvite} style={{ marginTop: 10 }} />
                                        <div style={{ marginTop: 10 }}>邀请医生</div>
                                    </div> */}
                                                {this.state.showCallBtn == true && this.state.statusCode !== 'F' ? <div style={{ cursor: 'pointer' }} onClick={this.handleVideoCode.bind(this)}
                                                    onDoubleClick={this.onDoubleVideoCode.bind(this)}>
                                                    <img src={videoCall} style={{ marginTop: 10 }} />
                                                    <div style={{ marginTop: 10 }}>视频呼叫</div>
                                                </div> : <div>
                                                    <img src={disVideo} style={{ marginTop: 10 }} />
                                                    <div style={{ marginTop: 10 }}>视频呼叫</div>
                                                </div>}
                                                {this.state.statusCode !== 'F' ? <div style={{ cursor: 'pointer' }} onClick={this.handleHangUpVideo.bind(this)}>
                                                    <img src={hangUp} style={{ marginTop: 10 }} />
                                                    <div style={{ marginTop: 10 }}>挂断视频</div>
                                                </div> : <div>
                                                    <img src={disHangUp} style={{ marginTop: 10 }} />
                                                    <div style={{ marginTop: 10 }}>挂断视频</div>
                                                </div>}

                                                {/* {this.state.statusCode !== 'F' ? <div style={{ cursor: 'pointer' }} onClick={this.handleEndOfReceive.bind(this)}>
                                                <img src={endVisit} style={{ marginTop: 10 }} />
                                                <div style={{ marginTop: 10 }}>结束接诊</div>
                                            </div> : <div >
                                                    <img src={disEndVisit} style={{ marginTop: 10 }} />
                                                    <div style={{ marginTop: 10 }}>结束接诊</div>
                                                </div>} */}
                                            </Card> : null}
                                        <Card style={this.state.showCalled == true ? style : null} bodyStyle={{ padding: '5px' }}
                                            onMouseOver={this.onMouseOver.bind(this)}>
                                            <div className='video-component-modal' style={{ height: dragHeight / 2.6, width: '100%' }}>
                                                <div id="video-grid" style={{ height: '100%', flex: '1' }}>
                                                    <div id="main-video" className="video-box col-div">
                                                        <div id="mask_main" className="mask col-div">
                                                            {/**摄像头未开启”遮罩 */}
                                                            <div></div>
                                                        </div>
                                                    </div>

                                                    {/* {this.state.showCalled == true ? null :
                                            <div style={{ height: '20vh', width: '20vh', border: '1px dashed #999999', textAlign: 'center' }}>
                                                <img src={imagePlus} style={{ marginTop: 50, cursor: 'pointer' }} /><br />
                                                <div style={{ marginTop: 20 }}>邀请医生</div>
                                            </div>} */}
                                                </div>

                                                {this.state.showCalled == true ? null : <div>
                                                    <div style={{ textAlign: 'center', marginTop: 20, fontSize: '16px' }} id='timer'></div>

                                                    <div style={{ textAlign: 'center', marginTop: 20 }}>
                                                        <img src={imagePhone} />
                                                    </div>

                                                    <div style={{ textAlign: 'center', marginTop: 20, fontSize: '16px', color: '#999999' }}>
                                                        正在呼叫患者</div>

                                                    <div style={{ textAlign: 'center', marginTop: 20 }}>
                                                        <Button type='danger' onClick={this.handleCannel.bind(this, 'cannel')}
                                                            disabled={this.state.disCannel}>取消呼叫</Button>
                                                        <Button type='primary' style={{ marginLeft: 10 }} disabled={this.state.statusCode == 'A' || this.state.disPassNum}
                                                            onClick={this.handlePassNum.bind(this)}>过号</Button>
                                                        <Button style={{ marginLeft: 10 }} onClick={this.handlePassNum.bind(this, 'next')}
                                                            disabled={Util.isEmpty(this.state.nextPatientMsg) || this.state.statusCode == 'A' || this.state.disPassNum}>过号呼叫下一位</Button>
                                                    </div>

                                                    <div style={{ textAlign: 'center', marginTop: 20, borderTop: '1px solid #e8e8e8', fontSize: '16px' }}>
                                                        <div style={{ padding: '20px 0' }}>
                                                            <span style={{ color: '#999999' }}>下一位患者：</span>
                                                            <span>{!Util.isEmpty(this.state.nextPatientMsg) ? this.state.nextPatientMsg.patName : '--'}</span><Divider type='vertical' />
                                                            <span>{!Util.isEmpty(this.state.nextPatientMsg) ? this.state.nextPatientMsg.patSexDesc : '--'}</span><Divider type='vertical' />
                                                            <span>{!Util.isEmpty(this.state.nextPatientMsg) ? this.state.nextPatientMsg.patAge : '--'}</span><Divider type='vertical' />
                                                            <span>{!Util.isEmpty(this.state.nextPatientMsg) ? this.state.nextPatientMsg.patNo : '--'}</span>
                                                        </div>
                                                    </div>
                                                </div>}
                                            </div>
                                        </Card>
                                    </div>
                                </div>

                                {this.state.showCalled == true && this.state.showPicture == true ?
                                    <div style={{ width: this.state.showPicture == true ? '54.9%' : '100%' }}>
                                        <ShowCommonVoiceChatPage handleSend={this.handleSend.bind(this)}
                                            chatData={this.state.chatData}
                                            sendStatus={this.state.sendStatus}
                                            statusNote={this.state.statusNote}
                                            onRef={this.onRefMessage}
                                            messageValueOnChange={this.messageValueOnChange.bind(this)} />
                                    </div> : null}
                            </div> : (this.state.showVoiceChatModal == true ?
                                <div className="content" style={{ height: (dragHeight - 60) }} id="message-send-box-wrapper">
                                    <ShowCommonVoiceChatPage handleSend={this.handleSend.bind(this)}
                                        chatData={this.state.chatData}
                                        sendStatus={this.state.sendStatus}
                                        statusNote={this.state.statusNote}
                                        onRef={this.onRefMessage}
                                        messageValueOnChange={this.messageValueOnChange.bind(this)} /></div> : null)}
                        </Spin></div> : null}
            </Spin>

            {/*事前事中消息模板*/}
            <ShowExamineModal onRef={this.onShowExamineModalRef} />

            {/* 添加至黑名单 */}
            <PatientBlacklist handleQuery={this.loadPatientMsg.bind(this)} onRef={ref => this.blacklistRef = ref} />
        </div>
    }

}
export default OutpatientStationTabs;
