/**
 * 门诊病人列表弹框
 */

import React from 'react';
import {
    Card, Table, Input, Form, Select, Row, Col, Checkbox, Modal,
    DatePicker, Button, Switch, Icon, Divider, message, Pagination, Tooltip,
} from 'antd';
import { Util, dayFormat } from 'tools/index';
import { $http } from 'containers/config/https';
import ReadCard from 'components/readcard/ReadCard';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import CommonPagination from 'components/pagination/index';
import RangeDatePicker from 'components/rangePicker/index';
import { PAGE_NUM_MORE_STATUS } from 'tools/statusConstants';
import { callNumberSocket } from 'tools/callNumber.js';
import ShowVideoCallModal from './ShowVideoCallModal';
import moment from 'moment';
import store from 'store';
import '../style/index.less';

const { RangePicker } = DatePicker;
const Search = Input.Search;
const Option = Select.Option;

class OutPatientOageModal 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'));
        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
        }
    }
    componentWillReceiveProps(nextProp) {
        if (nextProp.isShowModal === true) {
        } else if (this.props.isShow === false) {
            this.cleanInput();
        }
    }

    componentDidMount() {
        this.loadData();
        this.initData();
        this.loadHeaderData();
        this.loadCardType();
        this.getBindInfo();
        // document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 'px';
    }

    componentWillUnmount() {
        callNumberSocket.colse();
    }

    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)
        })
    }

    initData() {
        let data = {
            params: [{
                compontName: "OutPatientPage",
                type: "C",
                reactCode: ['OutPatientPage']
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040073",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    var columns = res.result.C;
                    var dynColumns = []
                    for (var i = 0; i < columns.length; i++) {
                        dynColumns.push({
                            title: this.state.userData.language == 'EN' ? columns[i].enDescripts : columns[i].title,
                            dataIndex: columns[i].dataIndex,
                            width: parseInt(columns[i].width),
                            align: columns[i].align || 'center'
                        })
                    }
                    this.setState({
                        column: dynColumns,
                        localeProvider: this.state.userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
                    })
                    this.props.hanlderThis.setState({
                        reload: false,
                    })
                }
            }
        })

    }

    loadData(page, pageSize, e) {
        var date = new Date();
        var params = {
            params: [{
                patCardTypeID: this.state.patCardTypeID ? this.state.patCardTypeID : (this.state.cardStatus),
                patCardNo: this.state.patCardNo,
                flag: this.state.checked ? 'Y' : 'N',
                number: this.state.number,
                admDateFrom: this.state.admDateFrom ? this.state.admDateFrom : moment(date).format(dayFormat),
                admDateTo: this.state.admDateTo ? this.state.admDateTo : moment(date).format(dayFormat),
            }],
            pagination: [{
                pageSize: this.state.size == 'small' ? this.state.pageSize : PAGE_NUM_MORE_STATUS[0].code,
                currentPage: page
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050004",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.initData()
                    this.setState({
                        dataSource: res.result.data,
                        total: res.result.totalCount,
                        rowId: res.result.data && res.result.data.length > 0 ? res.result.data[0].patAdmID : '',
                        page: page,
                        search: e
                    })
                }
            }
        });
    }

    searchPatientMsg(e) {
        if (e.keyCode == '13') {
            this.loadData(1)
        }
    }

    loadHeaderData() {
        var params = {
            params: [{}]
        }
        $http.post('urlDeault', this, {
            code: "03050005",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        sumData: res.data
                    })
                }
            }
        });
    }

    //获取卡类型
    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,
                    })
                }
            }
        });
    }

    //叫号
    loadCallNum() {
        var params = {
            params: [{
                locID: this.state.userData.locID,
                userID: this.state.userData.userID,
                docID: this.state.userData.userID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050006",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    // message.success('叫号成功')
                    message.success(this.setMessage('OutPatientPageCalled', 'descripts'),this.state.userData && this.state.userData.messageTime);
                    this.setState({
                        callMsg: res.result
                    }, () => {
                        this.sendMessage()
                    })
                    this.loadData()
                }
            }
        });
    }

    getBindInfo() {
        let data = {
            params: [{
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                purCode: "",
            }]
        }
        $http.post('urlDeault', this, {
            code: "04150007",
            data: data,
            success: (res) => {
                if (res.errorCode == '0') {
                    if (res.result.serverIP != undefined) {
                        callNumberSocket.init(res.result.serverIP, res.result.serverPort);
                        this.setState({
                            bindInfo: res.result,
                        })
                    }
                }
            }
        })
    }
    /** 发送消息 */
    sendMessage = () => {
        if (Util.isEmpty(this.state.bindInfo)) {
            return;
        }
        let msg = {};
        let ip = this.state.bindInfo.ip;
        callNumberSocket.sendMsg(this.state.callMsg, ip)
    }
    //过号
    loadPassNum() {
        var params = {
            params: [{
                locID: this.state.userData.locID,
                userID: this.state.userData.userID,
                docID: this.state.userData.userID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050007",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    // message.success('过号成功')
                    message.success(this.setMessage('OutPatientPageOperation', 'descripts'),this.state.userData && this.state.userData.messageTime)
                    this.loadData()
                }
            }
        });
    }

    startChange(date) {
        this.setState({
            admDateFrom: date,
        })
    }

    endChange(date) {
        this.setState({
            admDateTo: date,
        })
    }

    //分页切换
    onChange(e) {
        this.setState({ page: e }, () => {
            this.loadData(e);
        });
    }

    //分页切换
    changePageSize(current, pageSize) {
        this.setState({ pageSize: pageSize, page: current }, () => {
            this.loadData(current, pageSize);
        });
    }

    //接诊
    loadGetPatient(record) {
        // sessionStorage.setItem('recordData', JSON.stringify(record))
        var params = {
            params: [{
                patAdmID: record.patAdmID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050010",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    // message.success('接诊成功')
                    this.loadData(1)
                    this.loadPatientMsg(record)
                }
            }
        });
    }


    loadPatientMsg(record) {
        var params = {
            params: [{
                patID: record.patID,
                admID: record.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,
                    }, () => {
                        var { loadPatientMsg } = this.props;
                        loadPatientMsg && loadPatientMsg(res.data, record)

                    }
                    )
                }
            }
        });
    }

    //点击行，渲染当前行样式
    onClickRow = (record) => {
        return {
            onDoubleClick: () => {
                this.setState({
                    patAdmID: record.patAdmID
                });
                this.loadGetPatient(record)
            },
            onClick: () => {
                var patientData = {}
                patientData = {
                    admID: record.admID,
                    patID: record.patID
                }
                sessionStorage.setItem('patientData', JSON.stringify(patientData))
                this.setState({
                    rowId: record.patAdmID,
                    record: record
                }, () => {
                    var { loadTitleData } = this.props;
                    loadTitleData && loadTitleData()
                })
            },
            onKeyDown: () => {
                this.setState({
                    patAdmID: record.patAdmID
                });
                this.loadGetPatient(record)
            }
        };
    }

    //提交
    onSubmit() {
        // let { onSubmit } = this.props;

        // onSubmit && onSubmit(admID, ids);
        this.loadGetPatient(this.state.record)
    }

    //点击行，渲染当前行样式
    setRowClassName = (record) => {
        return record.patAdmID === this.state.rowId ? 'clickRowStyle' : '';
    }

    commonCheckbox(name, e) {
        this.setState({
            [name]: e
        }, () => {
            this.loadData(1, '', 'search')
        })
    }

    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, readStatus: 'read' }, () => {
                this.loadData()
            })
        })
    }
    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)).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
                })
            }
        }
    }

    loadVideoCall() {
        this.setState({
            isShowVideoCallModal: true
        })
    }

    hideModal(name) {
        this.setState({
            [name]: false
        })
    }

    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'>
            <div>
                {/**读卡 */}
                <ReadCard ref={ref => this.readCard = ref}></ReadCard>
                <ColumnAuthoritysModel
                    clientWidth='800px'
                    compontName="OutPatientPage"
                    configType="C"
                    onRef={this.onColumnRef}
                    reloadData={this.initData}
                />

                {/**视频通话 */}
                {/* <ShowVideoCallModal isShow={this.state.isShowVideoCallModal}
                    onHide={this.hideModal.bind(this, 'isShowVideoCallModal')}>
                </ShowVideoCallModal> */}
                <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}>
                            {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>

                        <Col span={6}>
                            <RangeDatePicker label={this.setMessage('OutPatientPagetime', 'descripts')} format='YYYY-MM-DD' width={300}
                                locale={this.state.userData.language}
                                startDate={moment(date).format(dayFormat)} endDate={moment(date).format(dayFormat)}
                                startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)} />
                        </Col>

                        <Button className='register-saveButton' type='primary' onClick={this.loadData.bind(this, 1, '', 'search')}>
                            {this.setMessage('OutPatientPagesearch', 'descripts')}</Button>
                    </Row>
                </Card>
                <div style={{ marginTop: 10 }}>
                    <Table columns={this.state.column} style={{ background: 'white', height: store.getState().tableHeight.y + 60 + 'px' }}
                        dataSource={this.state.dataSource}
                        loadData={this.loadData.bind(this)}
                        onRow={this.onClickRow} bordered
                        rowClassName={this.setRowClassName}
                        title={() => {
                            return (<div style={{ display: 'flex', marginTop: 5 }}><div className='patient-select-title' style={{ width: '140vh' }}>
                                <div>{this.setMessage('OutPatientPagetotal', 'descripts')}<span style={{ color: '#666666', fontWeight: 'bold' }}>{this.state.sumData ? this.state.sumData.totalCount : 0}</span></div>
                                <div>{this.setMessage('OutPatientPageAdmitted', 'descripts')}<span style={{ color: '#FAAD14', fontWeight: 'bold' }}>{this.state.sumData ? this.state.sumData.finishCount : 0}</span></div>
                                <div>{this.setMessage('OutPatientPageHaveNo', 'descripts')}<span style={{ color: '#13C2C2', fontWeight: 'bold' }}>{this.state.sumData ? this.state.sumData.overCount : 0}</span></div>
                                <div>{this.setMessage('OutPatientPagetreated', 'descripts')}<span style={{ color: '#FA8C16', fontWeight: 'bold' }}>{this.state.sumData ? this.state.sumData.waitCount : 0}</span></div>
                                <div>
                                    {/* <span>{this.setMessage('OutPatientPageNoAdmitted', 'descripts')}</span> */}
                                    <Switch style={{ marginLeft: 5 }} onChange={this.commonCheckbox.bind(this, 'checked')} />
                                    <span style={{ marginLeft: 5 }}>{this.state.checked ? this.setMessage('OutPatientPageAdmitted', 'descripts') :
                                        this.setMessage('OutPatientPageNoAdmitted', 'descripts')}</span>
                                </div>
                                {/* <div><Checkbox onChange={this.commonCheckbox.bind(this, 'checked')} /> {this.setMessage('OutPatientPagepatients', 'descripts')}</div> */}
                            </div>
                                <div /**style={{ marginLeft: '50%' }}*/>
                                    <Button style={{ background: '#1999db', color: 'white' }} className='patient-saveButton'
                                        onClick={this.loadCallNum.bind(this)}>{this.setMessage('OutPatientPageCall', 'descripts')}</Button>
                                    <Button style={{ background: '#FA8C16', color: 'white' }} className='patient-saveButton'
                                        onClick={this.loadData.bind(this, 1, '')}>{this.setMessage('OutPatientPageReCall', 'descripts')}</Button>
                                    <Button style={{ background: '#13C2C2', color: 'white' }} className='patient-saveButton'
                                        onClick={this.loadPassNum.bind(this)}>{this.setMessage('OutPatientPagePassNo', 'descripts')}</Button>
                                    {/* <Button style={{ background: '#13C2C2', color: 'white' }} className='patient-saveButton'
                                        onClick={this.loadVideoCall.bind(this)}>视频通话</Button> */}
                                </div>
                            </div>)
                        }}
                        rowKey={(data) => {
                            return data.patAdmID
                        }}
                        // scroll={{ y: store.getState().tableHeight.y + 'px' }}
                        scroll={{ y: store.getState().tableHeight.y - 40 + 'px' }}
                        onHeaderRow={column => {
                            return {
                                onDoubleClick: () => {
                                    this.columnRef.onOpenModel();
                                },
                            };
                        }}

                        pagination={false}>
                    </Table>
                    <CommonPagination size={this.state.size} current={this.state.page} total={this.state.total}
                        search={this.state.search}
                        onShowSizeChange={this.changePageSize.bind(this)} complete={true} dataSource={this.state.dataSource}
                        onChange={this.onChange.bind(this)} />
                </div>
            </div>
            {/* </Modal> */}
        </div>
    }
}

export default Form.create()(OutPatientOageModal);
