// 传染病上报监控
import React from 'react';
import { Select, Input, Row, Col, Button, Spin, message, Icon, Form, Modal, Card, Switch, DatePicker } from 'antd';
import { $http } from '../../../containers/config/https';
import '../../../assets/css/system.css';
import PubilcTablePagination from '../../common/PubilcTablePagination.jsx';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import store from '../../../store/index';
import moment from 'moment';
import InfectiousModel from './InfectiousModel.jsx';

const { Option } = Select;
const FormItem = Form.Item;

const formItemLayout = {
    labelCol: { span: 10 },
    wrapperCol: { span: 14 },
}
const formItemLayoutSelect = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
}
let userData = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
class InfectiousReportMonitor extends React.Component {
    constructor() {
        super();
        this.state = {
            tableData: [],      // 表格数据
            total: 0,           // 表格数据总条数
            column: [],         // 表头
            showLoading: true,
            page: 1,
            pageSize: 10,
            headerHeight: 0,
            modalVisible: false,
            locTypeData: [],     // 科室类型下拉数据
            locData: [],         // 科室下拉数据
            statusData: [],      // 状态下拉数据
            EN: {},
            CN: {},
            // reportType: "notReport",
            rowId: '', // 选中行ID
            diseaseID: '',  // 疾病id
            rowData: {}, // 选中行数据
            admID: "",
            patID: '',
            statusID:'',
            record:{},
        };
    }

    componentDidMount() {
        // 初始化列表数据
        this.handleQuery();
        this.getColumn();
        this.getSelectData();
        this.getLocData();
        this.child.handleLoading();
        // 组件加载完毕关闭loading
        this.setState({ showLoading: false });
    }

    componentWillUnmount() {
        // 组件销毁前将静止让setState修改state的状态
        this.setState = (state, callback) => { return; }
    }

    // 中英文切换
    languageDisplay(name) {
        return userData.language != 'EN' ? (this.state.CN[name] && this.state.CN[name]['descripts'] ? this.state.CN[name]['descripts'] : '') : (this.state.CN[name] && this.state.EN[name]['descripts'] ? this.state.EN[name]['descripts'] : '')
    }

    // 获取表头信息
    getColumn = () => {
        let data = {
            params: [{
                compontName: "InfectiousReportMonitor",
                type: "C",
                reactCode: ['InfectiousReportMonitor']
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040073",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    let column = 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()}>{userData.language != 'EN' ? item.title : item.enDescripts}</div>,
                            display: item.display,
                            key: item.seqNo
                        }
                    }) : '';
                    this.setState({
                        column,
                        EN: res.result.language.EN,
                        CN: res.result.language.CN
                    },()=>{
                        this.getTableData()
                    })
                }
            }
        })
    }
    // 获取下拉数据
    getSelectData = () => {
        let data = {
            params: [{}]
        }
        $http.post('urlDeault', this, {
            code: "04190001",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    this.setState({
                        locTypeData: res.result.locType,
                        statusData: res.result.status
                    })
                }
            }
        })
    }
    // 获取科室下拉数据
    getLocData = () => {
        let data = {
            params: [{
                "hospID": JSON.parse(window.sessionStorage.userData).hospID || '', //医院id
                "type": "O^I^OI",
            }]
        }
        $http.post('urlS', this, {
            code: "04020008",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {

                    this.setState({
                        locData: res.result.Data || [], // 数据
                    });
                }
            }
        });
    }
    // 调用子组件的连接事件
    onRef = (ref) => {
        this.child = ref
    }

    // 提供修改page和pageSize的回调函数
    compilePage(page, pageSize) {
        // 修改page，或者pageSize
        this.setState({ page: page, pageSize: pageSize }, () => {
            // 重新调用查询方法
            let { status, name, quarters } = this.state;
            this.getTableData(name, status, quarters);
        })
    }

    // 请求列表数据
    getTableData = () => {
        let { page, pageSize } = this.state;
        let data = {};
        this.props.form.validateFields((error, values) => {
            if (error) {
                return;
            }
            data = {
                params: [{
                    patNumber: values.personnel ? values.personnel : '',
                    stDate: values.stDate ? moment(values.stDate).format('YYYY-MM-DD') : '',
                    endDate: values.endDate ? moment(values.endDate).format('YYYY-MM-DD') : '',
                    locType: values.locType ? values.locType : '',
                    loc: values.loc ? values.loc : '',
                    //status: values.status ? values.status : '',
                }],
                pagination: [{
                    pageSize: pageSize,
                    currentPage: page,
                    sortColumn: "",
                    sortOrder: ""
                }]
            };
            // if ((values.status == "notReport")||(values.status == unfefined)){

            // }
            if (values.status == "reproted"){
                $http.post('urlS', this, {
                    code: "04190012",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0 && res.result) {
                            this.setState({
                                reportType:values.status,
                                tableData: res.result.Data,
                                total: res.result.TotalCount
                            }, () => {
                                // 数据加载成功关闭loading
                                this.child.handleLoading()
                            })
                        } else {
                            this.setState({ tableData: [], total: 0 }, () => {
                                // 数据加载成功关闭loading
                                this.child.handleLoading();
                            })
                        }
                    },
                });
            }else{
                $http.post('urlS', this, {
                    code: "04190013",
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0 && res.result) {
                            this.setState({
                                reportType:values.status,
                                tableData: res.result.DiseaseMonitorArr,
                                total: res.result.total
                            }, () => {
                                // 数据加载成功关闭loading
                                this.child.handleLoading()
                            })
                        } else {
                            this.setState({ tableData: [], total: 0 }, () => {
                                // 数据加载成功关闭loading
                                this.child.handleLoading();
                            })
                        }
                    },
                });
            }

            //     error: function () {
            //         this.setState({ tableData: [], total: 0 }, () => {
            //             // 数据加载成功关闭loading
            //             this.child.handleLoading();
            //         })
            //     }

        });
    }

    // 查询
    handleQuery = () => {
        this.setState({ page: 1}, () => {
            this.getTableData();
        })
    }

    //控制模态框显示
    showModal = (bool) => {
        this.setState({ modalVisible: bool });
    }
    onColumnRef = (ref) => {
        this.columnRef = ref;
    }
    // 获取主列表columns
    getTableColumns = () => {
        let data = {
            params: [{
                compontName: 'InfectiousReportMonitor',
                type: 'C',
            }]
        }
    }

    selectState = (e) => {
        console.log(e)
    }
    onConsumeSomeRef = (ref) => {
        this.childConsumeSome = ref;
    }

    onClickRowPublic = (record) => {
        return {
            onDoubleClick: () => {
                // let patientData = {}
                // patientData = {
                //     admID: record.admID,
                //     patID: record.patID
                // }
                // sessionStorage.setItem('patientData', JSON.stringify(patientData));
                this.props.form.validateFields((error, values) => {
                    if (error) {
                        return;
                    }
                    this.setState({
                        rowId: values.status == "reproted" ? record.id : '',
                        diseaseID: record.diseaseID,
                    }, () => this.childConsumeSome.showModal(record))
                })
            }
        }
    }

    //选中行操作
    setRowClassNamePublic = (record) => {
        return record.id === this.state.rowId ? 'clickRowStyle' : '';
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        // 组件所需参数
        const param = {
            // 表头配置
            columns: this.state.column,
            // 表格数据
            data: this.state.tableData,
            // 数据总条数
            total: this.state.total,
            // 当前页数
            page: this.state.page,
            // 表格的宽度
            x: '100%',
            y: store.getState().tableHeight.y + 81 - this.state.headerHeight,
            height: store.getState().tableHeight.y + 50 - this.state.headerHeight + 'px',
            isOnRow: true
        }

        return (
            <Spin tip="加载中..." spinning={this.state.showLoading}>
                <div style={{ overflowY: 'hidden' }}>
                    <Form>
                        <Row style={{ margin: '23px 0 0 0' }}>
                            <Col span={4} >
                                <FormItem {...formItemLayout} label={this.languageDisplay('InfectiousReportMonitorpersonnel')}>
                                    {getFieldDecorator('personnel', {
                                        //initialValue: params && params.healBureauID ? String(params.healBureauID) : undefined,
                                        rules: [{ required: false, message: '' }],
                                    })(
                                        <Input allowClear={true} placeholder="病人ID/姓名/身份证号码/手机号码( Enter )" onPressEnter={this.handleQuery} />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={4} >
                                <FormItem {...formItemLayout} label={this.languageDisplay('InfectiousReportMonitorstDate')}>
                                    {getFieldDecorator('stDate', {
                                        initialValue: moment().subtract(2, 'days'),
                                        rules: [{ required: false, message: '' }],
                                    })(
                                        <DatePicker defaultPickerValue />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={4} >
                                <FormItem {...formItemLayout} label={this.languageDisplay('InfectiousReportMonitorendDate')}>
                                    {getFieldDecorator('endDate', {
                                        initialValue: moment(),
                                        rules: [{ required: false, message: '' }],
                                    })(
                                        <DatePicker defaultPickerValue />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={3} >
                                <FormItem {...formItemLayout} label={this.languageDisplay('InfectiousReportMonitorlocType')}>
                                    {getFieldDecorator('locType', {
                                        //initialValue: params && params.healBureauID ? String(params.healBureauID) : undefined,
                                        rules: [{ required: false, message: '' }],
                                    })(
                                        <Select
                                            style={{ width: '70%' }}
                                            onSelect={this.handleQuery}
                                            allowClear={true}
                                            optionFilterProp="role"
                                            showSearch={true}
                                        >
                                            {this.state.locTypeData.map(item => {
                                                return <Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>
                                            })}
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={4} >
                                <FormItem {...formItemLayoutSelect} label={this.languageDisplay('InfectiousReportMonitorloc')}>
                                    {getFieldDecorator('loc', {
                                        //initialValue: undefined,

                                        rules: [{ required: false, message: '' }],
                                    })(
                                        <Select
                                            allowClear={true}
                                            style={{ width: '70%' }}
                                            onSelect={this.handleQuery}
                                            optionFilterProp="role"
                                            showSearch={true}
                                        >
                                            {this.state.locData.map(item => {
                                                return <Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>
                                            })}
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={3} >
                                <FormItem {...formItemLayout} label={this.languageDisplay('InfectiousReportMonitorstatus')}>
                                    {getFieldDecorator('status', {
                                        initialValue: "notReport",
                                        rules: [{ required: false, message: '' }],
                                    })(
                                        <Select
                                            style={{ width: '70%' }}
                                            // onSelect={this.getTableData}
                                        >
                                            {this.state.statusData.map(item => {
                                                return <Option key={item.code} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} code={item.code} value={item.code}>{item.descripts}</Option>
                                            })}
                                        </Select>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={2}>
                                <Button onClick={this.handleQuery} style={{ margin: '4px 15px 20px 0', background: 'rgba(255,255,255,1)' }} >{this.languageDisplay('InfectiousReportMonitorsearch')}</Button>
                            </Col>
                        </Row>
                    </Form>
                </div>
                <div style={{ width: '100%', height: '10px', background: '#f0f2f5' }}></div>
                <div style={{ padding: '24px 0 0 0' }} className="table-body-height">
                    {/* handelThis将夫组件的属性与方法给子组件访问 */}
                    <PubilcTablePagination param={param} handelThis={this} onRef={this.onRef}
                        onClickRowPublic={this.onClickRowPublic}
                        setRowClassNamePublic={this.setRowClassNamePublic} />
                </div>
                <ColumnAuthoritysModel
                    clientWidth='800px'
                    compontName='InfectiousReportMonitor'
                    configType="C"
                    onRef={this.onColumnRef}
                    reloadData={this.getTableColumns}
                />
                <InfectiousModel
                    onRef={this.onConsumeSomeRef}
                    reportID={this.state.rowId}
                    diseaseID={this.state.diseaseID}
                    handleQuery={this.getTableData}
                    statusID={this.state.reportType?this.state.reportType:""}
                />
            </Spin>
        )
    }
}
export default Form.create()(InfectiousReportMonitor);
