/**
 * 医嘱项目关联检验

 */
import React from 'react';
import {
    Card, Table, Input, Form, Select, Row, Col, AutoComplete, Radio,
    DatePicker, Button, Tree, Icon, Divider, message, Popconfirm, Tooltip,
} from 'antd';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import { Util, dayFormat, timeFormat } from 'tools/index';
import { $http } from 'containers/config/https';
import RangeDatePicker from 'components/rangePicker/index';
import CommonPagination from 'components/pagination/index';
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;

class CorrelationMedicalPage 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: 20,
            userData: userData,
            size: 'small',
            hospID: userData.hospID,
            startDate: moment(date).format(dayFormat),
            endDate: ''
        }
    }

    componentDidMount() {
        this.initData()
        this.loadData(1)
        this.loadHospitalMsg()//获取医院
    }

    loadData(page, pageSize, e) {
        var params = {
            params: [{
                groupID: this.state.userData.groupID,
                hospID: this.state.userData.hospID,
                medID: e == 'search' ? this.state.selectmedID : this.state.medID,
                lisID: e == 'search' ? this.state.selecrlisID : this.state.lisID
            }],
            pagination: [{
                pageSize: this.state.pageSize,
                currentPage: page
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040232",
            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: [{
                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
                    })
                }
            }
        });
    }

    loadLisProgram() {
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
                findCode: this.state.findLisCode,
                flag:'Y'
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040231",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        programList: res.result.data
                    })
                }
            }
        });
    }

    //获取医嘱项
    loadAdviceMessage() {
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
                findCode: this.state.findCode,
                detailFlag: '',
            }]
        }
        $http.post('urlDeault', this, {
            code: "01010002",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        adviceMessage: res.result.Data
                    })
                }
            }
        });
    }

    //用于保存
    handleChangeAutoComplete(name, e) {
        if (e) {
            this.setState({
                [name]: e
            }, () => {
                if (this.state.findCode.length >= 2) {
                    this.loadAdviceMessage()
                }
            })
        } else {
            this.setState({
                [name]: e
            })
        }
    }

    //用于保存
    handleLisAutoComplete(name, e) {
        if (e) {
            this.setState({
                [name]: e
            }, () => {
                if (this.state.findLisCode.length >= 2) {
                    this.loadLisProgram()
                }
            })
        } else {
            this.setState({
                [name]: e
            })
        }
    }

    //用于查询
    handleAutoCompleteLis(name, e) {
        if (e) {
            this.setState({
                [name]: e
            }, () => {
                if (this.state.selecrlisID.length >= 2) {
                    this.loadLisProgramSelect()
                }
            })
        } else {
            this.setState({
                [name]: e
            })
        }
    }

    loadLisProgramSelect() {
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
                findCode: this.state.selecrlisID,
                flag:'Y'
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040231",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        programListSelect: res.result.data
                    })
                }
            }
        });
    }

    //用于查询
    handleAutoCompleteMedID(name, e) {
        if (e) {
            this.setState({
                [name]: e
            }, () => {
                if (this.state.selectmedID.length >= 2) {
                    this.loadAdviceMessageSelect()
                }
            })
        } else {
            this.setState({
                [name]: e
            })
        }
    }


    //获取医嘱项
    loadAdviceMessageSelect() {
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
                findCode: this.state.selectmedID,
                detailFlag: '',
            }]
        }
        $http.post('urlDeault', this, {
            code: "01010002",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        adviceMessageSelect: res.result.Data
                    })
                }
            }
        });
    }

    initData() {
        this.columns = [
            {
                title: '医院',
                dataIndex: 'hospDesc',
                width: 180,
                align: 'center',
            }, {
                title: '医嘱项',
                dataIndex: 'medDesc',
                width: 280,
                align: 'center',
            }, {
                title: 'Lis项目',
                dataIndex: 'lisDesc',
                width: 280,
                align: 'center',
            }, {
                title: '开始日期',
                dataIndex: 'startDate',
                width: 150,
                align: 'center',
            }, {
                title: '失效日期',
                dataIndex: 'stopDate',
                width: 150,
                align: 'center',
            }, {
                title: '创建日期',
                dataIndex: 'createDate',
                width: 150,
                align: 'center',
            }, {
                title: '创建人',
                dataIndex: 'createUser',
                width: 150,
                align: 'center',
            }, {
                title: '操作',
                dataIndex: 'opertion',
                width: 180,
                align: 'center',
                render: (text, data) => {
                    return (
                        <span>
                            <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
                            <span className='span' onClick={this.handleEdit.bind(this, data)}>编辑</span>
                            <Divider type="vertical" />
                            <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
                            <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={this.handleDel.bind(this, data)} >
                                <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
                            </Popconfirm>
                        </span >
                    )
                }
            }
        ]
    }

    handleEdit(data) {
        this.setState({
            hospID: String(data.hospID),
            startDate: data.startDate,
            endDate: data.stopDate,
            findCode: data.medDesc,
            findLisCode: data.lisDesc,
            medID: data.medID,
            lisID: data.lisID,
            rowId: data.id
        }, () => {
            this.loadAdviceMessage()
            this.loadLisProgram()
        })
    }

    handleDel(data) {
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
                userID: this.state.userData.userID,
                groupID: this.state.userData.groupID,
                id: data.id
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040234",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('删除成功！')
                    this.loadData(1, '', 'search')
                }
            }
        });
    }

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

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

    onClickRow = (record, index) => {
        return {
            onClick: () => {
                if (record.id == this.state.rowId) {
                    this.setState({
                        rowId: undefined
                    }, () => {
                        this.clearInput()
                    })
                } else {
                    this.setState({
                        rowId: record.id,
                    }, () => {
                        this.handleEdit(record)
                    })
                }
            }
        }
    }

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

    handleChangeDatePicker(name, e) {
        var date = new Date()
        if (name == 'startDate') {
            this.setState({
                [name]: e ? moment(e).format(dayFormat) : moment(date).format(dayFormat)
            })
        } else {
            this.setState({
                [name]: e ? moment(e).format(dayFormat) : ''
            })
        }
    }

    clearInput() {
        var date = new Date()
        this.setState({
            hospID: this.state.userData.hospID,
            medID: undefined,
            lisID: undefined,
            findCode: undefined,
            findLisCode: undefined,
            rowId: undefined,
            adviceMessage: [],
            programList: [],
            startDate: moment(date).format(dayFormat),
            endDate: ''
        })
    }

    handleSave() {
        if (Util.isEmpty(this.state.hospID)) {
            message.error('医院不能为空！')
            return
        }
        if (Util.isEmpty(this.state.medID)) {
            message.error('医嘱项不能为空！')
            return
        }
        if (Util.isEmpty(this.state.lisID)) {
            message.error('Lis项目不能为空！')
            return
        }
        if (Util.isEmpty(this.state.startDate)) {
            message.error('生效日期不能为空！')
            return
        }
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
                userID: this.state.userData.userID,
                groupID: this.state.userData.groupID,
                medID: this.state.medID,
                lisID: this.state.lisID,
                id: this.state.rowId,
                startDate: moment(this.state.startDate).format(dayFormat),
                stopDate: this.state.endDate ? moment(this.state.endDate).format(dayFormat) : ''
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040233",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('保存成功！')
                    this.clearInput()
                    this.loadData(1, '', 'search')
                }
            }
        });
    }

    render() {
        //医院
        var hospitalDataOption = []
        this.state.hospitalData && this.state.hospitalData.map((item, index) => {
            hospitalDataOption.push(<Option key={index} value={item.id} name={item.descripts} code={item.descriptsSPCode}>{item.descripts}</Option>)
        })

        //医嘱项
        let adviceMessageOption = []
        this.state.adviceMessage && this.state.adviceMessage.map((item, index) => {
            adviceMessageOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
        })

        //医嘱项
        let adviceMessageSelectOption = []
        this.state.adviceMessageSelect && this.state.adviceMessageSelect.map((item, index) => {
            adviceMessageSelectOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
        })

        //检验项目
        let programListOption = []
        this.state.programList && this.state.programList.map((item, index) => {
            programListOption.push(<Option key={index} value={String(item.id)}>{item.descripts}</Option>)
        })

        //检验项目
        let programListSelectOption = []
        this.state.programListSelect && this.state.programListSelect.map((item, index) => {
            programListSelectOption.push(<Option key={index} value={String(item.id)}>{item.descripts}</Option>)
        })

        return <div className='correlation-body' style={{ background: '#f1f2f5', height: '100%', width: '100%' }}>
            <Card>
                <Row>
                    <Col span={4}>
                        <span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span>医院：<Select style={{ width: '75%' }} allowClear showSearch
                            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
                            } value={this.state.hospID} placeholder='请选择医院' onChange={Util.handleSelectChange.bind(this, 'hospID')}>
                            {hospitalDataOption}
                        </Select>
                    </Col>
                    <Col span={4}>
                        <span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span>医嘱项：<AutoComplete style={{ width: '75%' }}
                            onChange={this.handleChangeAutoComplete.bind(this, 'findCode')} allowClear placeholder='输入医嘱项查询医嘱'
                            onSelect={Util.handleSelectChange.bind(this, 'medID')} value={this.state.findCode}>
                            {adviceMessageOption}
                        </AutoComplete>
                    </Col>
                    <Col span={5}>
                        <span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span>Lis项目：<AutoComplete style={{ width: '75%' }}
                            onChange={this.handleLisAutoComplete.bind(this, 'findLisCode')} allowClear placeholder='输入lis项目项查询检验项目'
                            onSelect={Util.handleSelectChange.bind(this, 'lisID')} value={this.state.findLisCode}>
                            {programListOption}
                        </AutoComplete>
                    </Col>
                    <Col span={4}>
                        <span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span>生效日期：
                        <DatePicker onChange={this.handleChangeDatePicker.bind(this, 'startDate')} value={moment(this.state.startDate, dayFormat)} format={dayFormat} />
                    </Col>
                    <Col span={4}>
                        失效日期：<DatePicker onChange={this.handleChangeDatePicker.bind(this, 'endDate')} placeholder='请选择失效日期'
                            value={this.state.endDate ? moment(this.state.endDate, dayFormat) : ''} format={dayFormat} />
                    </Col>

                    <Button type='primary' onClick={this.handleSave.bind(this)}>{Util.isEmpty(this.state.rowId) ? '新增' : '修改'}</Button>
                    <Button style={{ marginLeft: 10 }} onClick={this.clearInput.bind(this)}>清空</Button>
                </Row>
            </Card>
            <Card style={{ marginTop: 10 }}>
                <Table columns={this.columns} style={{ height: store.getState().tableHeight.y + 130 + 'px' }}
                    dataSource={this.state.dataSource}
                    onRow={this.onClickRow} bordered
                    rowClassName={this.setRowClassName}
                    rowKey={(data) => {
                        return data.id
                    }}
                    title={() => {
                        return <Row>
                            <Col span={4}>
                                医嘱项：<AutoComplete style={{ width: '75%' }}
                                    onChange={this.handleAutoCompleteMedID.bind(this, 'selectmedID')} allowClear placeholder='输入医嘱项查询医嘱'
                                    onSelect={Util.handleSelectChange.bind(this, 'selectmedID')}>
                                    {adviceMessageSelectOption}
                                </AutoComplete>
                            </Col>
                            <Col span={5}>
                                Lis项目：<AutoComplete style={{ width: '75%' }}
                                    onChange={this.handleAutoCompleteLis.bind(this, 'selecrlisID')} allowClear placeholder='输入lis项目项查询检验项目'
                                    onSelect={Util.handleSelectChange.bind(this, 'selecrlisID')}>
                                    {programListSelectOption}
                                </AutoComplete>
                            </Col>

                            <Button type='primary' onClick={this.loadData.bind(this, 1, '', 'search')}>查询</Button>
                        </Row>
                    }}
                    scroll={{ y: store.getState().tableHeight.y + 30 + 'px' }}
                    pagination={false}>
                </Table>
                <CommonPagination size={this.state.size} current={this.state.page} total={this.state.total}
                    search={this.state.search} pageSize={true}
                    onShowSizeChange={this.changePageSize.bind(this)} complete={true} dataSource={this.state.dataSource}
                    onChange={this.onChange.bind(this)} />
            </Card>
        </div>
    }

}

export default CorrelationMedicalPage;