/**
 * 门诊医生工作站
 * 视频问诊
 */

import React from 'react';
import { Card, Input, Form, Select, Row, Col, Button, Tabs, message, Tooltip, } from 'antd';
import { Util, dayFormat } from 'tools/index';
import { $http } from 'containers/config/https';
import ReadCard from 'components/readcard/ReadCard';
import OutPatientOfVideoTabPane from './OutPatientOfVideoTabPane';
import VideoConsultationTabPane from './VideoConsultationTabPane';
import GraphicConsultationTabPane from './GraphicConsultationTabPane';
import ShowFaceRecognitionModal from './ShowFaceRecognitionModal';
import { PAGE_NUM_MORE_STATUS } from 'tools/statusConstants';
import moment from 'moment';
import store from 'store';
import '../style/index.less';

var mediaStreamTrack;
const Search = Input.Search;
const Option = Select.Option;
const TabPane = Tabs.TabPane;

class VideoConsultationPage extends React.Component {

    constructor(props) {
        super(props);
        var date = new Date();
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        var titleData = JSON.parse(sessionStorage.getItem('titleData'));
        var recordData = JSON.parse(sessionStorage.getItem('patientData'));
        var activeKey = JSON.parse(sessionStorage.getItem('activeKey'));
        if (!recordData) {
            recordData = JSON.parse(sessionStorage.getItem('recordData'));
        }
        var newDate = date.setMonth(date.getMonth() - 1);
        this.state = {
            dataSource: [],
            total: 0,
            page: 1,
            pageSize: 10,
            size: 'small',
            curPageDetail: PAGE_NUM_MORE_STATUS[0].code,
            recordData: recordData,
            userData: userData,
            activeKey: activeKey || '2' //默认线上问诊
        }
        this.patientNoRef = React.createRef();
        this.focurBtn = React.createRef();
    }

    componentWillReceiveProps(nextProp) {
        if (nextProp.isShowModal === true) {
        } else if (this.props.isShow === false) {
            this.cleanInput();
        }
    }

    componentDidMount() {
        this.props.onRef(this)
        this.initData();
        this.loadCardType()
        this.loadRoleMessage(); // 获取权限
        this.loadPatientNoFocus()
    }

    componentWillUnmount() {
        if (mediaStreamTrack) {
            mediaStreamTrack.getTracks()[0].stop(); //关闭摄像头
        }
    }

    loadPatientNoFocus() {
        this.patientNoRef.current.focus()
    }

    initData() {
        let data = {
            params: [{
                type: "C",
                reactCode: ['OutPatientPage']
            }]
        }
        $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
                    })
                }
            }
        })
    }

    loadRoleMessage() {
        let data = {
            params: [{
                hospID: this.state.userData.hospID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03100115",
            data: data,
            success: (res) => {
                if (+res.errorCode == '0') {
                    this.setState({
                        roleMessage: res.result
                    })
                }
            }
        })
    }

    closeModal(name) {
        let { onHide } = this.props;
        onHide && onHide('isShowOutPatientModal');
        this.cleanInput();
    }

    //清空输入框
    cleanInput() {
        var date = new Date()
        var newDate = date.setMonth(date.getMonth() - 1);
        var dateTime = new Date()
        this.setState({
            ids: [],
            admID: '',
            leftData: [],
            rightData: [],
            admDateFrom: moment(newDate).format(dayFormat),
            admDateTo: moment(dateTime).format(dayFormat)
        })
    }

    searchPatientMsg(e) {
        if (e.keyCode == '13') {
            if (this.state.activeKey == '1') {
                this.outPatRef.loadData(1)
            } else if (this.state.activeKey == '2') {
                this.videoRef.loadData(1)
            } else if (this.state.activeKey == '3') {
                this.graphicRef.loadData(1)
            }
        }
    }

    loadData(page, code, data, status) {
        if (this.state.activeKey == '1') {
            this.outPatRef.loadData(page, '', '', status)
        } else if (this.state.activeKey == '2') {
            this.videoRef.loadData(page, '', '', status)
        } else if (this.state.activeKey == '3') {
            this.graphicRef.loadData(page, '', '', status)
        }
    }

    //获取卡类型
    loadCardType() {
        var params = {
            params: [{
                cardTypeFlag: '1',//卡类型
            }]
        }
        $http.post('urlDeault', this, {
            code: "03030005",
            data: params,
            success: function (res) {
                var cardStatus = '', replaceZero = '', cardLength = '', readMode = ''
                if (res.errorCode == '0') {
                    if (res.cardType && res.cardType.length > 0) {
                        var cardType = res.cardType;
                        for (var i = 0; i < cardType.length; i++) {
                            if (cardType[i].defaultFlag == 'Y') {
                                cardStatus = cardType[i].id,
                                    replaceZero = cardType[i].replenishZero
                                cardLength = cardType[i].cardLength
                                readMode = cardType[i].readMode
                            }
                        }
                    }
                    this.setState({
                        cardTypeData: res.cardType,
                        cardStatus: cardStatus,
                        readMode: readMode,
                        cardLength: cardLength,
                        replaceZero: replaceZero,
                    })
                }
            }
        });
    }

    //门诊医生工作站的读卡事件
    handleReadCard() {
        var cardType = this.state.patCardTypeID ? this.state.patCardTypeID : (this.state.cardStatus);
        this.readCard.ReadCard(cardType, "R", (json) => {
            this.setState({ readPatID: json && json.patInfo ? json.patInfo.patID : '', patCardNo: json.cardNo, number: json && json.patInfo ? json.patInfo.patNo : '', readStatus: 'read' }, () => {
                this.loadData(1)
            })
        }, this.state.equipManagerObj?.readCardCode)
    }

    onColumnRef = (ref) => {
        this.columnRef = ref;
    }

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

    loadKeyDown(e) {
        if (e.keyCode == '13') {
            this.setState({//自动补0，渲染到组件中
                patCardNo: this.state.replaceZero == 'Y' ? (Array(parseInt(this.state.cardLength || 0)).join(0) + this.state.patCardNo).slice(-parseInt(this.state.cardLength)) : this.state.patCardNo
            }, () => {
                this.loadData(1)
            })
        }
    }

    //切换卡类型
    changeCardType(name, e) {
        var { cardTypeData } = this.state;
        for (var i = 0; i < cardTypeData.length; i++) {
            if (e == cardTypeData[i].id) {
                this.setState({
                    cardLength: cardTypeData[i].cardLength,
                    replaceZero: cardTypeData[i].replenishZero,
                    cardTypeId: cardTypeData[i].id,
                    readMode: cardTypeData[i].readMode,
                    [name]: e,
                    inputStatus: true,
                    equipManagerObj: cardTypeData[i].equipManagerObj
                })
            }
        }
    }

    changeAdviceKey(e) {
        this.setState({
            activeKey: e
        }, () => {
            sessionStorage.setItem('activeKey', JSON.stringify(this.state.activeKey))
            var { handleEndReceive } = this.props;
            handleEndReceive && handleEndReceive(this.state.activeKey)
        })
    }

    outPatientRef = ref => {
        this.outPatRef = ref
    }

    VideoConRef = ref => {
        this.videoRef = ref
    }

    graphicConRef = ref => {
        this.graphicRef = ref
    }

    loadTitleData(status) {
        var { loadTitleData } = this.props;
        loadTitleData && loadTitleData(status)
    }

    loadPatientMsg(data, record) {
        var { loadPatientMsg } = this.props;
        loadPatientMsg && loadPatientMsg(data, record)
    }

    //视频问诊穿给最外层父级
    showVideoCallModal(rowId, roomID, patID, statusNote) {
        var { showVideoCallModal } = this.props;
        showVideoCallModal && showVideoCallModal(rowId, roomID, patID, statusNote)
    }

    //图文咨询
    showVoiceChatModal(statusNote, admID, patID) {
        var { showVoiceChatModal } = this.props;
        showVoiceChatModal && showVoiceChatModal(statusNote, admID, patID)
    }

    loadChildData() {
        if (this.state.activeKey == '2') {
            this.videoRef.loadData(1)
        } else if (this.state.activeKey == '3') {
            this.graphicRef.loadData(1)
        }
    }

    handleDisableBtn(flag) {
        this.videoRef.handleDisableBtn(flag)
    }

    showChatHistoryMsg(rowId, roomID, patID, statusNote) {
        var { showChatHistoryMsg } = this.props;
        showChatHistoryMsg && showChatHistoryMsg(rowId, roomID, patID, statusNote)
    }

    handlerefuseMsg(id) {
        var { handlerefuseMsg } = this.props;
        handlerefuseMsg && handlerefuseMsg(id)
    }

    hideModal(name) {
        this.setState({
            [name]: false,
            hideFocus: true
        })
        let video = document.querySelector("#video");
        if (mediaStreamTrack) {
            mediaStreamTrack.getTracks()[0].stop(); //关闭摄像头
        }
    }

    loadCallBackMsg(data) {
        this.setState({
            number: data
        }, () => {
            this.loadData(1, '', '', 'face')
        })
    }

    onRef = ref => {
        this.onFace = ref
    }

    handleFocusInput() {
        try {
            var that = this;
            // 获取用户媒体,包含视频和音频
            if (!this.state.hideFocus && this.state.activeKey == '1') {
                navigator.mediaDevices.getUserMedia({ video: true })
                    .then(stream => {
                        this.focurBtn.current.buttonNode.focus()
                        that.setState({ isShowFaceRecognitionModal: true })
                        mediaStreamTrack = stream; // 将捕获的视频流传递给video  放弃window.URL.createObjectURL(stream)的使用
                        // video.play(); //  播放视频

                    }).catch(error => {
                        message.error('当前系统未检测到您的摄像头，请检查设备是否正常开启！')
                    });
            }
        } catch (error) {
            message.error("当前浏览器没有摄像头权限，请先授权。")
        }
    }

    clearData(data) {
        this.setState({
            number: data
        })
    }

    render() {
        var date = new Date();
        //卡类型
        let cardTypeOption = []
        this.state.cardTypeData && this.state.cardTypeData.map((item, index) => {
            cardTypeOption.push(<Option key={index} value={item.id}>
                <Tooltip title={this.state.userData.language == 'EN' ? item.enDescripts : item.descripts}>
                    {this.state.userData.language == 'EN' ? item.enDescripts : item.descripts}</Tooltip></Option>)
        })

        return <div style={{ background: '#F5F7FE' }} className='outpatient-body'>
            {/**人脸识别 */}
            <ShowFaceRecognitionModal isShow={this.state.isShowFaceRecognitionModal}
                businessCode='002' onRef={this.onRef}
                onSubmit={this.loadCallBackMsg.bind(this)}
                onHide={this.hideModal.bind(this, 'isShowFaceRecognitionModal')}>
            </ShowFaceRecognitionModal>

            <div>
                {/**读卡 */}
                <ReadCard ref={ref => this.readCard = ref}></ReadCard>
                <Card>
                    <Row gutter={15}>
                        <Col span={6}>
                            <Select style={{ width: '100px' }} placeholder='请选择卡类型'
                                allowClear
                                showSearch
                                value={this.state.patCardTypeID ? this.state.patCardTypeID : (this.state.cardStatus)}
                                getPopupContainer={triggerNode => triggerNode.parentNode}
                                onChange={this.changeCardType.bind(this, 'patCardTypeID')}>
                                {cardTypeOption}
                            </Select>
                            <Search
                                placeholder={this.setMessage('OutPatientPagecardType', 'message')} style={{ width: '250px', marginLeft: 10 }}
                                onChange={Util.commonInputChange.bind(this, 'patCardNo')}
                                value={this.state.patCardNo}
                                enterButton={this.setMessage('OutPatientPageCardReading', 'descripts')}
                                readOnly={this.state.readMode == 'R' ? true : false}
                                onPressEnter={(e) => console.dir(e)}
                                onKeyDown={this.loadKeyDown.bind(this)}
                                onSearch={this.handleReadCard.bind(this)}
                            />
                        </Col>

                        <Col span={6}>
                            <Input.Group>
                                <Input className='express-input-disable' style={{ width: '30%', textAlign: 'center' }} value={this.setMessage('OutPatientPagePatInfo', 'descripts')} disabled />
                                <Input onChange={Util.commonInputChange.bind(this, 'number')}
                                    onFocus={this.props.faceFocus ? this.handleFocusInput.bind(this) : ''} value={this.state.number}
                                    onKeyDown={this.searchPatientMsg.bind(this)} ref={this.patientNoRef}
                                    placeholder={this.setMessage('OutPatientPagePatInfo', 'message')} style={{ width: '69.9%' }} />
                            </Input.Group>
                            {/* {this.setMessage('OutPatientPagePatInfo', 'descripts')}<Input onChange={Util.commonInputChange.bind(this, 'number')}
                                onKeyDown={this.searchPatientMsg.bind(this)}
                                placeholder={this.setMessage('OutPatientPagePatInfo', 'message')} style={{ width: '25vh' }} /> */}
                        </Col>

                        <Button className='register-saveButton' type='primary' ref={this.focurBtn} onClick={this.loadData.bind(this, 1, '', '', '')}>
                            {this.setMessage('OutPatientPagesearch', 'descripts')}</Button>
                    </Row>
                </Card>
                <div style={{ marginTop: 10, background: 'white', height: store.getState().tableHeight.y + 105 + 'px' }}>
                    <Tabs activeKey={this.state.activeKey} onChange={this.changeAdviceKey.bind(this)}>
                        {!Util.isEmpty(this.state.roleMessage) && this.state.roleMessage.op == 'Y' ? <TabPane tab='门诊' key='1'>
                            <OutPatientOfVideoTabPane onRef={this.outPatientRef}
                                patCardTypeID={this.state.patCardTypeID ? this.state.patCardTypeID : (this.state.cardStatus)}
                                patCardNo={this.state.patCardNo}
                                number={this.state.number}
                                clearData={this.clearData.bind(this)}
                                loadTitleData={this.loadTitleData.bind(this)}
                                loadPatientMsg={this.loadPatientMsg.bind(this)}
                            />
                        </TabPane> : null}
                        {!Util.isEmpty(this.state.roleMessage) && this.state.roleMessage.video == 'Y' ? <TabPane tab='线上门诊' key='2'>
                            <VideoConsultationTabPane onRef={this.VideoConRef}
                                patCardTypeID={this.state.patCardTypeID ? this.state.patCardTypeID : (this.state.cardStatus)}
                                showVideoCallModal={this.showVideoCallModal.bind(this)}
                                showChatHistoryMsg={this.showChatHistoryMsg.bind(this)}
                                patCardNo={this.state.patCardNo}
                                number={this.state.number}
                                handlerefuseMsg={this.handlerefuseMsg.bind(this)}
                                loadTitleData={this.loadTitleData.bind(this)}
                                loadPatientMsg={this.loadPatientMsg.bind(this)}
                            />
                        </TabPane> : null}
                        {!Util.isEmpty(this.state.roleMessage) && this.state.roleMessage.image == 'Y' ? <TabPane tab='图文咨询' key='3'>
                            <GraphicConsultationTabPane onRef={this.graphicConRef}
                                patCardTypeID={this.state.patCardTypeID ? this.state.patCardTypeID : (this.state.cardStatus)}
                                showVoiceChatModal={this.showVoiceChatModal.bind(this)}
                                patCardNo={this.state.patCardNo}
                                number={this.state.number}
                                handlerefuseMsg={this.handlerefuseMsg.bind(this)}
                                loadTitleData={this.loadTitleData.bind(this)}
                                loadPatientMsg={this.loadPatientMsg.bind(this)}
                            />
                        </TabPane> : null}
                        {!Util.isEmpty(this.state.roleMessage) && this.state.roleMessage.convenience == 'Y' ? <TabPane tab='便民门诊' key='4'>
                            <OutPatientOfVideoTabPane onRef={this.outPatientRef}
                                patCardTypeID={this.state.patCardTypeID ? this.state.patCardTypeID : (this.state.cardStatus)}
                                patCardNo={this.state.patCardNo}
                                number={this.state.number}
                                convenience='convenience'
                                loadTitleData={this.loadTitleData.bind(this)}
                                loadPatientMsg={this.loadPatientMsg.bind(this)}
                            />
                        </TabPane> : null}
                    </Tabs>
                </div>
            </div>
        </div>
    }
}

export default Form.create()(VideoConsultationPage);
