/**
 * 检验项目

 */
import React from 'react';
import {
    Card, Table, Input, Form, Select, Row, Col, AutoComplete, Switch,
    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 InspectionItemsPage extends React.Component {
    constructor(props) {
        super(props)
        var userData = JSON.parse(sessionStorage.getItem('userData'))
        var date = new Date()
        this.state = {
            dataSource: [],
            rightData: [],
            total: 0,
            page: 1,
            pageSize: 10,
            userData: userData,
            size: 'small',
            hospID: userData.hospID,
            startDate: moment(date).format(dayFormat),
            startTime: moment(date).format(dayFormat),
            endDate: '',
            endTime: ''
        }
    }

    componentDidMount() {
        this.initData()
        this.loadData(1)
        this.loadHospitalMsg()//获取医院
        this.loadSelectMessage()
        document.querySelector('.inspection-left-table .ant-table-body').style.height = store.getState().tableHeight.y + 'px'
        document.querySelector('.inspection-right-table .ant-table-body').style.height = store.getState().tableHeight.y + 'px'
    }

    loadData(page, pageSize, e) {
        var params = {
            params: [{
                groupID: this.state.userData.groupID,
                hospID: this.state.userData.hospID,
            }],
            pagination: [{
                pageSize: this.state.pageSize,
                currentPage: page
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040231",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        dataSource: res.result.data,
                        total: res.result.totalCount,
                        page: page,
                        search: e,
                    })
                }
            }
        });
    }

    //获取下拉
    loadSelectMessage() {
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040240",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        tubeGroupList: res.result.tubeGroupList,
                        specList: res.result.specList,
                        containerList: res.result.containerList,
                    })
                }
            }
        });
    }

    //获取医院信息
    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
                    })
                }
            }
        });
    }

    //获取医嘱项
    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
            })
        }
    }

    initData() {
        this.columns = [
            {
                title: '代码',
                dataIndex: 'code',
                width: 120,
                align: 'center',
            }, {
                title: '描述',
                dataIndex: 'descripts',
                width: 320,
                align: 'center',
            }, {
                title: '医院',
                dataIndex: 'hospDesc',
                width: 120,
                align: 'center',
            }, {
                title: '英文描述',
                dataIndex: 'enDesc',
                width: 180,
                align: 'center',
            }, {
                title: '取报告提示',
                dataIndex: 'takeNote',
                width: 180,
                align: 'center',
            }, {
                title: '采样提示',
                dataIndex: 'collectNote',
                width: 180,
                align: 'center',
            }, {
                title: '申请提示',
                dataIndex: 'requestNote',
                width: 180,
                align: 'center',
            }, {
                title: '合管组',
                dataIndex: 'tubeGroupDesc',
                width: 180,
                align: 'center',
            }, {
                title: '开始日期',
                dataIndex: 'startDate',
                width: 180,
                align: 'center',
            }, {
                title: '失效日期',
                dataIndex: 'stopDate',
                width: 180,
                align: 'center',
            }, {
                title: '创建日期',
                dataIndex: 'createDate',
                width: 180,
                align: 'center',
            }, {
                title: '操作',
                dataIndex: 'opertion',
                width: 180,
                align: 'center',
                fixed: 'right',
                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 >
                    )
                }
            }
        ],
            this.rightColumns = [
                {
                    title: '标本',
                    dataIndex: 'specDesc',
                    width: 120,
                    align: 'center',
                },
                {
                    title: '容器',
                    dataIndex: 'containerDesc',
                    width: 120,
                    align: 'center',
                },
                {
                    title: '默认',
                    dataIndex: 'isDefault',
                    width: 80,
                    align: 'center',
                },
                {
                    title: '开始日期',
                    dataIndex: 'startDate',
                    width: 180,
                    align: 'center',
                }, {
                    title: '失效日期',
                    dataIndex: 'stopDate',
                    width: 180,
                    align: 'center',
                }, {
                    title: '创建日期',
                    dataIndex: 'createDate',
                    width: 180,
                    align: 'center',
                }, {
                    title: '操作',
                    dataIndex: 'opertion',
                    width: 180,
                    align: 'center',
                    fixed: 'right',
                    render: (text, data) => {
                        return (
                            <span>
                                <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
                                <span className='span' onClick={this.handleEditRight.bind(this, data)}>编辑</span>
                                <Divider type="vertical" />
                                <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
                                <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={this.handleDelRight.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,
            code: data.code,
            descripts: data.descripts,
            enDesc: data.enDesc,
            takeNote: data.takeNote,
            collectNote: data.collectNote,
            requestNote: data.requestNote,
            tubeGroupID: data.tubeGroupID,
            rowId: data.id
        })
    }

    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: "01040236",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('删除成功！')
                    this.loadData(1, '', 'search')
                    this.clearInput()
                }
            }
        });
    }

    //分页切换
    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()
                        this.clearRightInput()
                    })
                } else {
                    this.setState({
                        rowId: record.id,
                    }, () => {
                        this.handleEdit(record)
                        this.loadRightData()
                        this.clearRightInput()
                    })
                }
            }
        }
    }

    //点击行，渲染当前行样式 
    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,
            startDate: moment(date).format(dayFormat),
            endDate: '',
            code: undefined,
            descripts: undefined,
            enDesc: undefined,
            takeNote: undefined,
            collectNote: undefined,
            requestNote: undefined,
            tubeGroupID: undefined,
        })
    }

    handleSave() {
        var params = {
            params: [{
                groupID: this.state.userData.groupID,
                hospID: this.state.userData.hospID,
                userID: this.state.userData.userID,
                id: this.state.rowId,
                startDate: this.state.startDate ? moment(this.state.startDate).format(dayFormat) : moment(date).format(dayFormat),
                stopDate: this.state.endDate ? moment(this.state.endDate).format(dayFormat) : '',
                code: this.state.code,
                descripts: this.state.descripts,
                enDesc: this.state.enDesc,
                takeNote: this.state.takeNote,
                collectNote: this.state.collectNote,
                requestNote: this.state.requestNote,
                tubeGroupID: this.state.tubeGroupID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040235",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('保存成功！')
                    this.clearInput()
                    this.loadData(1, '', 'search')
                }
            }
        });
    }

    /***********标本****** */

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

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

    loadRightData() {
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
                lisID: this.state.rowId,
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040237",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        rightData: res.result.data
                    })
                }
            }
        });
    }

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

    handleChangeSwitch(name, e) {
        this.setState({
            [name]: e ? 'Y' : 'N'
        })
    }

    onClickRightRow = (record, index) => {
        return {
            onClick: () => {
                if (record.id == this.state.rightID) {
                    this.setState({
                        rightID: undefined
                    }, () => {
                        this.clearRightInput()
                    })
                } else {
                    this.setState({
                        rightID: record.id,
                    }, () => {
                        this.handleEditRight(record)
                    })
                }
            }
        }
    }

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

    handleEditRight(data) {
        this.setState({
            specID: data.specID,
            containerID: data.containerID,
            startTime: data.startDate,
            endTime: data.stopDate,
            isDefault: data.isDefault,
            descripts: data.lisDesc,
            lisID: data.lisID
        })
    }

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

    //保存右边数据
    handleSaveRight() {
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
                userID: this.state.userData.userID,
                id: this.state.rightID,
                lisID: this.state.rowId,
                containerID: this.state.containerID,
                specID: this.state.specID,
                isDefault: this.state.isDefault,
                startDate: moment(this.state.startTime).format(dayFormat),
                stopDate: this.state.endTime ? moment(this.state.endTime).format(dayFormat) : ''
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040238",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('保存成功！')
                    this.loadRightData()
                    this.clearRightInput()
                }
            }
        });
    }

    //清除右边数据
    clearRightInput() {
        var date = new Date()
        this.setState({
            rightID: undefined,
            containerID: undefined,
            specID: undefined,
            isDefault: 'N',
            startTime: moment(date).format(dayFormat),
            endTime: ''
        })
    }

    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 tubeGroupListOption = []
        this.state.tubeGroupList && this.state.tubeGroupList.map((item, index) => {
            tubeGroupListOption.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 specListOption = []
        this.state.specList && this.state.specList.map((item, index) => {
            specListOption.push(<Option key={index} value={String(item.id)} code={item.code} name={item.descriptsSPCode}>{item.descripts}</Option>)
        })

        //标本
        let containerListOption = []
        this.state.containerList && this.state.containerList.map((item, index) => {
            containerListOption.push(<Option key={index} value={String(item.id)} code={item.code} name={item.descriptsSPCode}>{item.descripts}</Option>)
        })

        return <div className='correlation-body' style={{ background: '#f1f2f5', height: '100%', width: '100%' }}>
            <div style={{ width: '60%', float: 'left', height: store.getState().tableHeight.y + 230 + 'px' }}>
                <Card>
                    <Row>
                        <Col span={8}>
                            <span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span>代码：
                            <Input placeholder='请输入代码' style={{ width: '75%' }} onChange={Util.commonInputChange.bind(this, 'code')} value={this.state.code} />
                        </Col>
                        <Col span={8}>
                            <span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span>描述：
                            <Input placeholder='请输入描述' style={{ width: '75%' }} onChange={Util.commonInputChange.bind(this, 'descripts')} value={this.state.descripts} />
                        </Col>
                        <Col span={8}>
                            <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>
                    </Row>
                    <Row style={{ marginTop: 10 }}>
                        <Col span={8}>
                            英文描述：<Input placeholder='请输入英文描述' style={{ width: '69%' }}
                                onChange={Util.commonInputChange.bind(this, 'enDesc')} value={this.state.enDesc} />
                        </Col>
                        <Col span={8}>
                            取报告提示：<Input placeholder='请输入取报告提示' style={{ width: '65%' }}
                                onChange={Util.commonInputChange.bind(this, 'takeNote')} value={this.state.takeNote} />
                        </Col>
                        <Col span={8}>
                            采样提示：<Input placeholder='请输入采样提示' style={{ width: '69%' }}
                                onChange={Util.commonInputChange.bind(this, 'collectNote')} value={this.state.collectNote} />
                        </Col>
                    </Row>

                    <Row style={{ marginTop: 10 }}>
                        <Col span={8}>
                            申请提示：<Input placeholder='请输入申请提示' style={{ width: '69%' }}
                                onChange={Util.commonInputChange.bind(this, 'requestNote')} value={this.state.requestNote} />
                        </Col>
                        <Col span={8}>
                            合管组：<Select placeholder='请选择合管组' style={{ width: '74%' }} allowClear showSearch
                                onChange={Util.handleSelectChange.bind(this, 'tubeGroupID')} value={this.state.tubeGroupID}>
                                {tubeGroupListOption}
                            </Select>
                        </Col>
                        <Col span={8}>
                            <span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span>生效日期：
                        <DatePicker onChange={this.handleChangeDatePicker.bind(this, 'startDate')} style={{ width: '66%' }}
                                value={moment(this.state.startDate, dayFormat)} format={dayFormat} />
                        </Col>
                    </Row>

                    <Row style={{ marginTop: 10 }}>
                        <Col span={8}>
                            失效日期：<DatePicker onChange={this.handleChangeDatePicker.bind(this, 'endDate')} placeholder='请选择失效日期' style={{ width: '69%' }}
                                value={this.state.endDate ? moment(this.state.endDate, dayFormat) : ''} format={dayFormat} />
                        </Col>

                        <Button type='primary' onClick={this.handleSave.bind(this)}>保存</Button>
                        <Button style={{ marginLeft: 10 }} onClick={this.clearInput.bind(this)}>清空</Button>
                    </Row>
                </Card>

                <Card style={{ marginTop: 10 }} className='inspection-left-table'>
                    <Table columns={this.columns} style={{ height: store.getState().tableHeight.y + 'px' }}
                        dataSource={this.state.dataSource}
                        onRow={this.onClickRow} bordered
                        rowClassName={this.setRowClassName}
                        rowKey={(data) => {
                            return data.id
                        }}
                        scroll={{ x: 1200, y: store.getState().tableHeight.y - 50 + 'px' }}
                        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)} />
                </Card>
            </div>
            <div style={{ width: '39.8%', float: 'right', height: store.getState().tableHeight.y + 230 + 'px' }}>
                <Card style={{ height: 170 }}>
                    <Row>
                        <Col span={12}>
                            {/* <span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span>Lis项目：<AutoComplete style={{ width: '75%' }} disabled
                                onChange={this.handleLisAutoComplete.bind(this, 'findLisCode')} allowClear placeholder='输入lis项目项查询检验项目'
                                onSelect={Util.handleSelectChange.bind(this, 'lisID')} value={this.state.findLisCode}>
                                {programListOption}
                            </AutoComplete> */}
                            <span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span>Lis项目：<Input disabled value={this.state.descripts} style={{ width: '75%' }} />
                        </Col>
                        <Col span={12}>
                            <span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span>标本：<Select style={{ width: '75%' }} allowClear showSearch
                                onChange={Util.handleSelectChange.bind(this, 'specID')} placeholder='请选择标本' value={this.state.specID} 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
                                } >
                                {specListOption}
                            </Select>
                        </Col>
                    </Row>

                    <Row style={{ marginTop: 10 }}>
                        <Col span={12}>
                            <span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span>容器：<Select style={{ width: '75%' }} allowClear showSearch
                                onChange={Util.handleSelectChange.bind(this, 'containerID')} placeholder='请选择容器' value={this.state.containerID} 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
                                } >
                                {containerListOption}
                            </Select>
                        </Col>

                        <Col span={12}>
                            <span style={{ color: '#f5222d', fontFamily: 'SimSun' }}>*</span>生效日期：
                        <DatePicker onChange={this.handleChangeDate.bind(this, 'startTime')} style={{ width: '66%' }}
                                value={moment(this.state.startTime, dayFormat)} format={dayFormat} />
                        </Col>
                    </Row>

                    <Row style={{ marginTop: 10 }}>
                        <Col span={12}>
                            失效日期：<DatePicker onChange={this.handleChangeDate.bind(this, 'endTime')} placeholder='请选择失效日期'
                                value={this.state.endTime ? moment(this.state.endTime, dayFormat) : ''} format={dayFormat} />
                        </Col>

                        <Col span={12}>
                            <Switch checkedChildren="是" unCheckedChildren="否" checked={this.state.isDefault == 'Y' ? true : false}
                                onChange={this.handleChangeSwitch.bind(this, 'isDefault')} />

                            <Button type='primary' style={{ marginLeft: 10 }} onClick={this.handleSaveRight.bind(this)}>保存</Button>
                            <Button style={{ marginLeft: 10 }} onClick={this.clearRightInput.bind(this)}>清空</Button>
                        </Col>
                    </Row>
                </Card>

                <Card style={{ marginTop: 10 }} className='inspection-right-table'>
                    <Table columns={this.rightColumns} style={{ height: store.getState().tableHeight.y + 40 + 'px' }}
                        dataSource={this.state.rightData}
                        onRow={this.onClickRightRow} bordered
                        rowClassName={this.setRowRightClassName}
                        rowKey={(data) => {
                            return data.id
                        }}
                        scroll={{ x: 800, y: store.getState().tableHeight.y + 'px' }}
                        pagination={false}>
                    </Table>
                </Card>
            </div>
        </div>
    }

}

export default InspectionItemsPage;