/**
 *
 * 门诊病人列表
 */
import React from 'react';
import {
    Card, Table, Input, Form, Select, Row, Col, Checkbox,
    DatePicker, Button, Popconfirm, Icon, Divider, message, Pagination,
} 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 moment from 'moment';
import store from 'store';
import './style/index.less';

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

class OutPatientPage extends React.Component {
    constructor(props) {
        super(props)
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        var date = new Date()
        this.state = {
            dataSource: [],
            total: 0,
            page: 1,
            pageSize: 10,
            size: 'small',
            curPageDetail: PAGE_NUM_MORE_STATUS[0].code,
            admDateFrom: moment(date).format(dayFormat),
            admDateTo: moment(date).format(dayFormat),
            userData: userData
        }
    }

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

    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++) {
                        if (columns[i].dataIndex == 'queStatusDesc') {
                            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',
                                onCell: (text, data) => {
                                    return {
                                        style: {
                                            background: text.color ? text.color : '',
                                            color: text.color ? 'white' : ''
                                        }
                                    }
                                },
                                render: (text, data) => {
                                    return <span>{data.queStatusDesc}</span>
                                }
                            })
                        } else {
                            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();
        this.setState({ loading: true })
        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,
                admDateTo: this.state.admDateTo,
            }],
            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.loadHeaderData()
                    this.initData()
                    this.setState({
                        dataSource: res.result.data,
                        total: res.result.totalCount,
                        page: 1,
                        search: e,
                        loading: false
                    })
                }
            }
        });
    }

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

    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 = ''
                var 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,
                                    readMode = cardType[i].readMode
                            }
                        }
                    }
                    this.setState({
                        cardTypeData: res.cardType,
                        cardStatus: cardStatus,
                        readMode: readMode
                    })
                }
            }
        });
    }

    //叫号
    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') {
                    this.loadData()
                    this.setState({
                        callMsg: res.result
                    }, () => {
                        this.sendMessage()
                    })
                }
            }
        });
    }

    //过号
    loadPassNum() {
        var params = {
            params: [{
                patAdmID: this.state.rowId,
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050007",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('过号成功',this.state.userData && this.state.userData.messageTime)
                    this.loadData()
                }
            }
        });
    }

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

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

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

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

    //接诊
    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.state.userData && this.state.userData.messageTime)
                    var data = {
                        id: record.admID
                    }
                    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)
                    }
                }
            }
        });
    }

    //点击行，渲染当前行样式
    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,
                })
            }
        };
    }

    onCell(record) {
        console.dir(record)
    }

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

    commonCheckbox(name, e) {
        this.setState({
            [name]: e.target.checked
        }, () => {
            this.loadData()
        })
    }

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

    getBindInfo() {
        let data = {
            params: [{
                dataID: "8",
                hospID: this.state.userData.hospID,
                purCode: "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)) {
            message.warn("未关联电子屏，不能呼叫!",this.state.userData && this.state.userData.messageTime);
            return;
        }
        let msg = {};
        let ip = this.state.bindInfo.ip;
        callNumberSocket.sendMsg(this.state.callMsg, ip)
    }

    handleSelectChange(name, e) {
        var { cardTypeData } = this.state;
        for (var i = 0; i < cardTypeData.length; i++) {
            if (e == cardTypeData[i].id) {
                this.setState({
                    readMode: cardTypeData[i].readMode,
                    [name]: e
                })
            }
        }
    }

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

    render() {
        let searchColConfig = {
            xs: { span: 24 },
            sm: { span: 12 },
            md: { span: 10 },
            lg: { span: 6 }
        }

        let searchBtnConfig = {
            xs: { span: 24 },
            sm: { span: 12 },
            md: { span: 10 },
            lg: { span: 8 }
        }

        var date = new Date();

        //卡类型
        let cardTypeOption = []
        this.state.cardTypeData && this.state.cardTypeData.map((item, index) => {
            cardTypeOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
        })

        return (<div style={{ background: '#F1F1F1' }} className='outpatient-body'>
            {/**读卡 */}
            <ReadCard ref={ref => this.readCard = ref}></ReadCard>
            <ColumnAuthoritysModel
                clientWidth='800px'
                compontName="OutPatientPage"
                configType="C"
                onRef={this.onColumnRef}
                reloadData={this.initData}
            // visible={this.state.visible}
            // onCancel={
            //     () => {
            //         this.setState({
            //             visible: false,
            //         }, () => {
            //             this.initData();
            //         })
            //     }
            // }
            />
            <Card>
                <Row gutter={15}>
                    <Col  {...searchBtnConfig}>
                        <Select style={{ width: '120px' }} placeholder='请选择卡类型'
                            allowClear
                            showSearch
                            value={this.state.patCardTypeID ? this.state.patCardTypeID : (this.state.cardStatus)}
                            getPopupContainer={triggerNode => triggerNode.parentNode}
                            onChange={this.handleSelectChange.bind(this, 'patCardTypeID')}>
                            {cardTypeOption}
                        </Select>
                        <Search className={this.state.readMode == 'R' ? 'disable-input-title' : ''}
                            placeholder={this.setMessage('OutPatientPagecardType', 'message')} style={{ width: '300px', 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  {...searchColConfig}>
                        {this.setMessage('OutPatientPagePatInfo', 'descripts')}<Input onChange={Util.commonInputChange.bind(this, 'number')}
                            onKeyDown={this.searchPatientMsg.bind(this)}
                            placeholder={this.setMessage('OutPatientPagePatInfo', 'message')} style={{ width: '240px' }} />
                    </Col>

                    <Col {...searchColConfig}>
                        {/* 挂号日期：<RangePicker onChange={this.changeRegistrTime.bind(this)}
                            defaultValue={[moment(date, dayFormat), moment(date, dayFormat)]}
                            style={{ width: 300 }} /> */}
                        <RangeDatePicker label={this.setMessage('OutPatientPagetime', 'descripts')} format='YYYY-MM-DD' width={300}
                            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' }}
                    dataSource={this.state.dataSource}
                    loadData={this.loadData.bind(this)}
                    onRow={this.onClickRow}
                    onCell={this.onCell}
                    rowClassName={this.setRowClassName}
                    bordered
                    title={() => {
                        return (<div style={{ display: 'flex' }}><div className='patient-select-title'>
                            <div>{this.setMessage('OutPatientPagetotal', 'descripts')}{this.state.sumData ? this.state.sumData.totalCount : 0}</div>
                            <div>{this.setMessage('OutPatientPageadmitted', 'descripts')}{this.state.sumData ? this.state.sumData.finishCount : 0}</div>
                            <div>{this.setMessage('OutPatientPageHaveNo', 'descripts')}{this.state.sumData ? this.state.sumData.overCount : 0}</div>
                            <div>{this.setMessage('OutPatientPagetreated', 'descripts')}{this.state.sumData ? this.state.sumData.waitCount : 0}</div>
                            <div><Checkbox onChange={this.commonCheckbox.bind(this, 'checked')} /> {this.setMessage('OutPatientPagepatients', 'descripts')}</div>
                        </div>
                            <div style={{ marginLeft: '50%' }}>
                                <Button className='patient-saveButton' onClick={this.loadCallNum.bind(this)}>{this.setMessage('OutPatientPageCall', 'descripts')}</Button>
                                <Button className='patient-saveButton' onClick={this.loadData.bind(this, 1, '')}>{this.setMessage('OutPatientPageReCall', 'descripts')}</Button>
                                <Button className='patient-saveButton' onClick={this.loadPassNum.bind(this)}>{this.setMessage('OutPatientPagePassNo', 'descripts')}</Button>
                            </div>
                        </div>)
                    }}
                    rowKey={(data) => {
                        return data.patAdmID
                    }}
                    scroll={{ y: store.getState().tableHeight.y + 'px' }}
                    onHeaderRow={column => {
                        return {
                            onDoubleClick: () => {
                                // this.setState({
                                //     visible: true,
                                // })
                                this.columnRef.onOpenModel();
                            },
                        };
                    }}

                    pagination={false}>
                </Table>
                {/* <Pagination
                    size="small"
                    showQuickJumper
                    showSizeChanger
                    defaultCurrent={1}
                    current={this.state.page}
                    total={this.state.total}
                    onShowSizeChange={this.changePageSize.bind(this)}
                    onChange={this.onChange.bind(this)}
                    style={{ textAlign: "right", marginTop: '13px' }}
                /> */}
                <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}
                    loading={this.state.loading} onChange={this.onChange.bind(this)} />
            </div>
        </div>)

    }
}

export default OutPatientPage;
