/**
 * 设备绑定记录
 */
import React from 'react';
import {
    Card, Table, Input, Form, Select, Row, Col, Checkbox, Tabs,
    DatePicker, Button, Popconfirm, Icon, Divider, message, Modal,
} from 'antd';
import { Util, dayFormat } from 'tools/index';
import { $http } from 'containers/config/https';
import CommonPagination from 'components/pagination/index';
import RangeDatePicker from 'components/rangePicker/index';
import ShowBindDeviceModal from './component/ShowBindDeviceModal';
import { PAGE_NUM_MORE_STATUS } from 'tools/statusConstants';
import store from 'store';
import moment from 'moment';
import './style/index.less';

const { RangePicker } = DatePicker;
const Option = Select.Option;
const Search = Input.Search;
const confirm = Modal.confirm;
const TabPane = Tabs.TabPane;

class DeviceBindRecordPage 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,
            userData: userData,
            activeKey: '1',
            size: 'small',
            curPageDetail: PAGE_NUM_MORE_STATUS[0].code,
            regDateFrom: moment(date).format(dayFormat),
            regDateTo: moment(date).format(dayFormat),
        }
    }

    componentDidMount() {
        this.initData()
        this.loadData(1)
        this.loadHospitalMsg()//机构
        this.loadEquipmentType()//设备类型
        document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 90 + 'px';
    }

    initData() {
        this.columns = [
            {
                title: '设备厂商',
                dataIndex: 'companyDesc',
                width: 200,
                align: 'left',
            },
            {
                title: '设备类型',
                dataIndex: 'deviceTypeDesc',
                width: 100,
                align: 'left',
            },
            {
                title: '设备型号',
                dataIndex: 'deviceModel',
                width: 100,
                align: 'left',
            },
            {
                title: '设备编号',
                dataIndex: 'SN',
                width: 100,
                align: 'left',
            },
            {
                title: '设备发放机构',
                dataIndex: 'hospDesc',
                width: 150,
                align: 'left',
            },
            {
                title: '姓名',
                dataIndex: 'patName',
                width: 100,
                align: 'left',
            },
            {
                title: '病人ID',
                dataIndex: 'patNo',
                width: 100,
                align: 'left',
            },
            {
                title: '性别',
                dataIndex: 'patSex',
                width: 100,
                align: 'left',
            },
            {
                title: '年龄',
                dataIndex: 'patAge',
                width: 100,
                align: 'left',
            },
            {
                title: '绑定时间',
                dataIndex: 'createDate',
                width: 100,
                align: 'left',
                render: (text, data) => {
                    return <span>{data.createDate}&nbsp;&nbsp;{data.createTime}</span>
                }
            },
            {
                title: '操作',
                dataIndex: 'opertion',
                width: 100,
                align: 'center',
                render: (text, data, index) => {
                    return <span>
                        <span className='span' style={{ color: 'rgba(240,65,52,1)' }}
                            onClick={this.handleDel.bind(this, data, index)}>解除绑定</span>
                        <Divider type="vertical" />
                        <span style={{ cursor: "pointer", color: '#1890ff' }}
                            onClick={this.handleEditMsg.bind(this, data)}>编辑</span>
                    </span>
                }
            },
        ]
    }

    handleDel(data) {
        var that = this;
        confirm({
            title: '确认解除绑定',
            content: <span>确认将当前患者与设备<span style={{ color: '#1999db', fontSize: '16px' }}>{data.deviceTypeDesc}</span>解除绑定？
            解除绑定后，患者检测数据将不能实时上传！</span>,
            okText: that.state.userData.language == 'EN' ? 'Ok' : '确定',
            cancelText: that.state.userData.language == 'EN' ? 'cancel' : '取消',
            onOk() {
                that.handleCannelDevice(data)
            },
            onCancel() {
                return
            }
        })
    }

    handleCannelDevice(data) {
        var params = {
            params: [{
                userID: this.state.userData.userID,
                patDeviceID: data.patDeviceID,
                active: 'N'
            }]
        }
        $http.post('urlS', this, {
            code: "03070127",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('解绑成功！')
                    this.loadData(1)
                }
            }
        })
    }

    handleEditMsg(data) {
        this.setState({
            isShowBindDeviceModal: true,
            patDeviceID: data.patDeviceID,
            patID: data.patID,
            editStatus: true,
            deviceTypeID: String(data.deviceTypeID),
            deviceModelID: String(data.deviceModelID),
            companyID: String(data.companyID),
            SN: String(data.SN),
        }, () => {
            this.onRefs.loadAllData()
        })
    }

    loadData(page, pageSize, e) {
        var params = {
            params: [{
                hospID: this.state.hospID,
                startDate: this.state.regDateFrom,
                endDate: this.state.regDateTo,
                deviceTypeID: this.state.deviceTypeID,
                SN: this.state.SN,
                number: this.state.number
            }],
            pagination: [{
                pageSize: this.state.size == 'small' ? this.state.pageSize : PAGE_NUM_MORE_STATUS[0].code,
                currentPage: page
            }]
        }
        $http.post('urlS', this, {
            code: "03070125",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        dataSource: res.result.data,
                        total: res.result.totalCount,
                        page: page,
                        search: e
                    })
                }
            }
        })
    }

    //获取医院信息
    loadHospitalMsg() {
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
                logonHospID: this.state.userData.hospID,
                logonGroupID: this.state.userData.groupID,
                hospRequired: '1',
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040001",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        hospitalData: res.depDoctor
                    })
                }
            }
        });
    }

    loadEquipmentType() {
        var params = {
            params: [{}]
        }
        $http.post('urlS', this, {
            code: "03070129",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        equipmentMsg: res.result
                    })
                }
            }
        })
    }

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

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

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

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

    hideModal(name) {
        this.setState({
            [name]: false,
            deviceTypeID: undefined,
            deviceModelID: undefined,
            companyID: undefined,
            SN: undefined,
        })
    }

    showBindDeviceModal() {
        this.setState({
            isShowBindDeviceModal: true,
            patID: undefined,
            editStatus: false
        }, () => {
            this.onRefs.loadClearData()
        })
    }

    onSubmit(data) {
        data.patDeviceID = this.state.patDeviceID
        var params = {
            params: [data]
        }
        $http.post('urlS', this, {
            code: this.state.editStatus == true ? '03070127' : "03070126",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('保存成功！')
                    this.setState({
                        editStatus: false,
                        deviceTypeID: undefined,
                        deviceModelID: undefined,
                        companyID: undefined,
                        SN: undefined,
                    }, () => {
                        this.loadData(1)
                        this.hideModal('isShowBindDeviceModal')
                    })
                }
            }
        })
    }

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

    render() {
        //所属医院参数
        let hospitalOption = [];
        this.state.hospitalData && this.state.hospitalData.map((item, index) => {
            hospitalOption.push(<Option key={index} value={item.id} name={item.descripts} code={item.descriptsSPCode}>{item.descripts}</Option>)
        })

        //设备类型
        var equipmentMsgOption = []
        this.state.equipmentMsg && this.state.equipmentMsg.map((item, index) => {
            equipmentMsgOption.push(<Option key={index} value={String(item.id)} code={item.code} name={item.descriptsSPCode}>{item.descripts}</Option>)
        })

        return <div className='information-basic-body' style={{ background: '#F0F2F5' }}>
            {/**绑定设备 */}
            <ShowBindDeviceModal isShow={this.state.isShowBindDeviceModal}
                onRef={this.onLoad}
                hospitalData={this.state.hospitalData}
                patID={this.state.patID}
                deviceTypeID={this.state.deviceTypeID}
                deviceModelID={this.state.deviceModelID}
                SN={this.state.SN}
                editStatus={this.state.editStatus}
                companyID={this.state.companyID}
                onSubmit={this.onSubmit.bind(this)}
                onHide={this.hideModal.bind(this, 'isShowBindDeviceModal')}>
            </ShowBindDeviceModal>
            <Card style={{ height: '5%' }}>
                <Row>
                    <Col span={5}>
                        <RangeDatePicker label={'日期：'} format='YYYY-MM-DD' width={'77%'}
                            startDate={this.state.regDateFrom} endDate={this.state.regDateTo}
                            startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)} />
                    </Col>

                    <Col span={4}>
                        机构：<Select placeholder="请选择机构" style={{ width: '70%' }}
                            showSearch allowClear
                            filterOption={(input, option) =>
                                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                || option.props.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                            onChange={Util.handleSelectChange.bind(this, 'hospID')}
                            getPopupContainer={triggerNode => triggerNode.parentNode}>
                            {hospitalOption}
                        </Select>
                    </Col>
                    <Col span={4}>
                        设备类型： <Select style={{ width: '70%' }} allowClear showSearch placeholder='请选择设备类型'
                            filterOption={(input, option) =>
                                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                || option.props.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            } onChange={Util.handleSelectChange.bind(this, 'deviceTypeID')}
                            getPopupContainer={triggerNode => triggerNode.parentNode}>
                            {equipmentMsgOption}
                        </Select>
                    </Col>
                    <Col span={4}>
                        设备编号：<Input placeholder='请输入设备编号' style={{ width: '70%' }}
                            onChange={Util.commonInputChange.bind(this, 'SN')} />
                    </Col>
                    <Col span={4}>
                        人员标识：<Input placeholder='病人ID/姓名/证件号码/手机号码' style={{ width: '70%' }}
                            onChange={Util.commonInputChange.bind(this, 'number')} />
                    </Col>
                    <Col span={3}>
                        <Button type='primary' onClick={this.loadData.bind(this, 1, '', 'search')}>查询</Button>
                        <Button type='primary' style={{ marginLeft: 10 }} onClick={this.showBindDeviceModal.bind(this)}><Icon type='plus' />绑定设备</Button>
                    </Col>
                </Row>
            </Card>

            <Card style={{ marginTop: 10, height: '93%' }}>
                <Table columns={this.columns} style={{ textAlign: 'center' }}
                    dataSource={this.state.dataSource}
                    rowKey={(data) => {
                        return data.patDeviceID
                    }}
                    scroll={{ y: store.getState().tableHeight.y + 100 }}
                    pagination={false} bordered>

                </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)} />
            </Card>
        </div>
    }

}

export default DeviceBindRecordPage;
