/*
 * Creator:     ML
 * CreatDate:   2019-12-18
 * descripts：  床位关联床位费
 * */
import React from 'react';
import { Form, Select, Button, Row, Table, Col, Card } from 'antd';
import { $http } from 'containers/config/https';
import store from 'store';
import CommonPagination from 'components/pagination';
import BedCostToBedDetail from './component/BedCostToBedDetail';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import './style/index.less'

const FormItem = Form.Item;
const Option = Select.Option;
const paddRightCol = {
    paddingRight: '0px'
}
const formItemLayoutType = {
    labelCol: { span: 5 },
    wrapperCol: { span: 18 }
}

class TermNaAndRe extends React.Component {
    constructor() {
        super();
        this.state = {
            tableData: [], // 列表数据
            total: 0,
            page: 1,
            pageSize: 10,
            size: 'big',
            search: '',
            ICD: '',
            diaID: '',
            size: 'small',
            search: '',
            totalWidth: 0
        };
    }

    componentDidMount() {
        if (this.state.size == 'small') {
            this.setState({
                pageSize: 10
            })
        } else {
            this.setState({
                pageSize: 50
            })
        }
        this.getHopSelect()
        this.getFindDate()
        this.getMainTableColumns()
    }

    //动态表头
    onColumnRef = (ref) => {
        this.columnRef = ref;
    }

    // 获取主列表columns
    getMainTableColumns = () => {
        let data = {
            params: [{
                compontName: 'BedInformation',
                reactCode: ['BedInformation'],
                type: 'C',
            }]
        }
        $http.post('urlS', this, {
            code: '01040073',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let arr = res.result && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map(item => {
                        return {
                            align: item.align,
                            widthNum: parseInt(item.width),
                            width: item.width,
                            dataIndex: item.dataIndex,
                            title: <div onDoubleClick={() => this.columnRef.onOpenModel()}>{item.title}</div>,
                            display: item.display,
                            key: item.seqNo,
                        }
                    }) : '';
                    let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                    this.setState({ columns: filterArr, totalWidth: res.totalWidth })
                }
            }
        })
    }

    //获取医院下拉框
    getHopSelect = () => {
        let data = {
            params: [{
                hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : '',
                logonGroupID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).groupID : '',
                logonHospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : '',
            }],
        }
        $http.post('urlS', this, {
            code: '01040001',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        hospArr: res.result
                    })
                }
            }
        })
    }

    //医院选择带出科室
    handleBaseHosp = (id) => {
        this.props.form.setFieldsValue({ locID: undefined })
        if (id) {
            this.setState({
                hosID: id
            }, () => {
                this.getPublicBaseLocSelect()
            })
        } else {
            this.setState({
                hosID: '',
                publicBaseLocArr: []
            }, () => {
                this.getPublicBaseLocSelect()
            })
        }
    }

    //获取科室下拉框
    getPublicBaseLocSelect = () => {
        let data = {}
        data = {
            params: [{
                hospID: this.state.hosID || '',
                locTypeID: this.state.locID || ''
            }],
        }
        $http.post('urlS', this, {
            code: '01050029',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.result.Data) {
                    let arr = res.result.Data && res.result.Data.map((item, index) => {
                        res.result.Data[index].key = Number(index)
                    })
                    this.setState({
                        publicBaseLocArr: res.result.Data,
                    })
                } else {

                }
            }
        })
    }

    //调子组件
    onAttRef = (ref) => {
        this.childAtt = ref
    }

    onRef = (ref) => {
        this.onChildRef = ref
    }

    ondiaRef = (ref) => {
        this.onChilddiaRef = ref
    }

    searchICD = (e) => {
        this.onChildRef.showModal(e.target.value)
    }

    changeICD = (e) => {
        if (e && e.target.value.length == 0) {
            this.setState({
                ICD: ''
            })
        }
    }

    changediaICD = (e) => {
        if (e && e.target.value.length == 0) {
            this.setState({
                diaID: ''
            })
        }
    }

    searchdiaICD = (e) => {
        this.onChilddiaRef.showModal(e.target.value)
    }

    handleParms = (data) => {
        this.setState({
            ICD: data.id,
        })
        this.props.form.setFieldsValue({ ICDID: data.descripts, })
    }

    handlediaParms = (data) => {
        this.setState({
            diaID: data.id
        })
        this.props.form.setFieldsValue({ diaICDID: data.descripts })
    }

    handleClear = () => {
        if (this.state.ICD && this.state.ICD) {
            this.setState({
                // ICD,
            })
        } else {
            this.setState({ ICD: '' })
            this.props.form.setFieldsValue({ ICDID: undefined })
        }
    }

    handlediaClear = () => {
        if (this.state.diaID && this.state.diaID) {
            this.setState({
                // diaID,
            })
        } else {
            this.setState({ diaID: '' })
            this.props.form.setFieldsValue({ diaICDID: undefined })
        }
    }

    // 点击查询
    handleQuery = () => {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.setState({
                    values,
                    rowIds: '',
                }, () => {
                    //详情页面内容清空
                    this.childAtt.initDeatail()
                    this.onShowSizeChange('1', this.state.pageSize)
                })
            }
        })
    }

    //查询
    getFindDate = (values, e) => {
        let { page, pageSize, diaID, ICD } = this.state;
        let data = {
            params: [{
                hBHosID: values && values.getHop || '',
                hBLocID: values && values.locID || '',
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
            }]
        }
        $http.post('urlS', this, {
            code: '01040140',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        search: e,
                        tableData: res.result.data,
                        total: res.result.TotalCount,
                    })
                }
            }
        })
    }

    // 修改page和pageSize 跳转至---
    onChange = (e) => {
        this.setState({ page: e, pageSize: this.state.pageSize, }, () => {
            // 重新调用查询方法
            let { values } = this.state;
            this.getFindDate(values);
        })
    }

    //下拉选择页数
    onShowSizeChange = (page, pageSize) => {
        // console.log('page',page,'pagesize',pageSize)
        this.setState({ page: 1, pageSize: pageSize }, () => {
            // 重新调用查询方法
            let { values } = this.state;
            this.getFindDate(values, 'search');
        })
    }

    // 显示分页总条数
    showTotal(total) {
        return `共 ${total} 条`;
    }

    //点击Row
    onClickRow = (record) => {
        return {
            onClick: () => {
                this.setState({
                    parms: record,
                })
                this.childAtt.clearInfo()
                if (this.state.rowIds === '') {
                    this.setState({
                        rowIds: record.ID,
                    })
                    this.childAtt.getInfo(record)
                } else {
                    if (this.state.rowIds !== record.ID) {
                        this.setState({
                            rowIds: record.ID,
                        });
                        this.childAtt.getInfo(record)
                    } else {
                        this.setState({
                            rowIds: '',
                        });
                        this.childAtt.initDeatail()
                    }
                }
            },
        };
    }

    //点击查询后 表格行
    setRowClassNames = (record) => {
        return record.ID === this.state.rowIds ? 'clickRowStyle' : '';
    }

    render() {
        const { columns, totalWidth } = this.state;

        const { getFieldDecorator } = this.props.form;
        //医院
        let hosOp = []
        this.state.hospArr && this.state.hospArr.map((item) => {
            hosOp.push(<Option key={item.id} onClick={(e,) => this.handleBaseHosp(item.id)} value={String(item.id)}>{item.descripts}</Option>)
        })
        //科室类型
        let locOp = []
        this.state.publicBaseLocArr && this.state.publicBaseLocArr.map(item => {
            locOp.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
        })
        return (
            <div className="majorCategoriesDom">
                <div style={{ paddingTop: '6px' }}>
                    <Form layout={'horizontal'}>
                        <Row>
                            <Col span={4} style={paddRightCol}>
                                <FormItem {...formItemLayoutType} label='医院'>
                                    {getFieldDecorator('getHop', {
                                        initialValue: undefined,
                                        rules: [{ required: false, message: '' }],
                                    })(
                                        <Select
                                            allowClear
                                            onChange={this.handleBaseHosp}
                                        >
                                            {hosOp}
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={4} style={paddRightCol}>
                                <FormItem {...formItemLayoutType} label='科室'>
                                    {getFieldDecorator('locID', {
                                        initialValue: undefined,
                                        rules: [{ required: false, message: '' }],
                                    })(
                                        <Select
                                            allowClear
                                            placeholder="请先选择医院"
                                        >
                                            {locOp}
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={4}>
                                <Button style={{ margin: '3px 0 0 10px' }} type="primary" onClick={this.handleQuery}>查询</Button>
                            </Col>
                        </Row>
                    </Form>
                </div>
                <Row>
                    <Col span={8}>
                        <Card title="床位列表" className="titleDom table-body-height">
                            <Table
                                columns={columns}
                                dataSource={this.state.tableData}
                                pagination={false}
                                rowKey={record => record.key}
                                onRow={this.onClickRow}
                                rowClassName={this.setRowClassNames}
                                bordered
                                scroll={{ x: totalWidth, y: store.getState().tableHeight.y - 10 }}
                                style={{ height: store.getState().tableHeight.y + 40 + 'px', overflow: 'auto' }}
                            />
                            <CommonPagination size={this.state.size} current={this.state.page} total={this.state.total} search={this.state.search}
                                onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.tableData}
                                onChange={this.onChange.bind(this)} />

                        </Card>
                    </Col>
                    <Col span={16} style={{ marginLeft: '-1px' }}>
                        <Card title="床位关联床位费" className="titleDom">
                            <BedCostToBedDetail prioritySelectData={this.props.prioritySelectData} onAttRef={this.onAttRef} handleQuery={this.handleQuery}></BedCostToBedDetail>
                        </Card>
                    </Col>
                </Row>
                <ColumnAuthoritysModel
                    clientWidth='800px'
                    compontName='BedInformation'
                    configType="C"
                    onRef={this.onColumnRef}
                    reloadData={this.getMainTableColumns}
                />
            </div>
        )
    }
};
const TerminologyNaAndReg = Form.create()(TermNaAndRe);
export default TerminologyNaAndReg;