// 关联医院
import React from 'react';
import { Form, Select, Button, DatePicker, Icon, Popconfirm, Checkbox, message } from 'antd';
import { $http } from 'containers/config/https';
import '../style/childStyle.less';
import Moment from 'moment';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';

const { Option } = Select;

class OLAssociatedHospital extends React.Component {
    constructor() {
        super();
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        this.state = {
            selectData: {}, // 下拉框数据
            hosp: undefined, // 医院
            status: true, // 仅显示生效
            tableData: [], // 列表数据
            total: 0,
            page: 1,
            pageSize: 10,
            rowData: {}, // 编辑回显数据
            user: userData,
            medID: '',
            loading: false
        };
        this.columns = [
            {
                key: 1,
                title: '序号',
                dataIndex: 'key',
                align: "center",
                width: '20%',
            },
            {
                key: 2,
                title: '医院',
                dataIndex: 'hospDesc',
                align: "center",
                width: '40%',
            },
            {
                key: 3,
                title: '状态',
                dataIndex: 'status',
                align: "center",
                width: '20%',
            },
            {
                title: '操作',
                key: 4,
                align: "center",
                width: '20%',
                render: (text, record) => (
                    <span>
                        <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
                        <Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)} >
                            <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
                        </Popconfirm>
                    </span>
                ),
            }
        ];
    }

    componentDidMount() {
        this.getSelectData();
        if ((this.props.medData && this.props.medData.medID ? this.props.medData.medID : '') !== this.state.medID) {
            this.setState({ medID: this.props.medData.medID }, () => {
                this.handleQuery();
            })
        } else {
            this.child.handleLoading();
        }
    }

    componentWillReceiveProps(nextProps) {
        if ((nextProps.medData && nextProps.medData.medID ? nextProps.medData.medID : '') !== this.state.medID) {
            this.setState({ medID: nextProps.medData.medID }, () => {
                this.handleQuery();
            })
        }
    }

    // 调用子组件的连接事件
    onRef = (ref) => {
        this.child = ref
    }

    // 获取下拉框数据
    getSelectData = () => {
        let { user } = this.state;
        let data = {
            params: [{
                logonHospID: user.hospID,
                logonGroupID: user.groupID,
                hospFlag: 'Y',
            }]
        }
        $http.post('urlS', this, {
            code: "03010037",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.result) {
                    this.setState({ selectData: res.result })
                }
            }
        })
    }
    compilePage = (page, pageSize) => {
        this.setState({
            page,
            pageSize,
        }, () => {
            this.getTableData()
        })

    }

    // 请求列表数据
    getTableData() {
        this.setState({ loading: true });
        let { page, pageSize, status, hosp, user, medID } = this.state;
        let data = {
            params: [{
                userID: user.userID, // 用户id
                logonHospID: user.hospID, // 登陆医院id
                groupID: user.groupID, // 角色id
                medID, // 医嘱项id
                active: status ? 'Y' : 'N', // 状态
                hospID: hosp, // 医院
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: "Describe",
                sortOrder: "asc"
            }]
        }
        $http.post('urlS', this, {
            code: "03010040",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.result) {
                    for (var i = 0; i < res.result.data.length; i++) {
                        res.result.data[i].key = i + 1
                    }
                    this.setState({ tableData: res.result.data, total: res.result.totalCount, loading: false }, () => {
                        // 数据加载成功关闭loading
                        this.child.handleLoading();
                    })
                } else {
                    this.setState({ tableData: [], total: 0, loading: false }, () => {
                        // 数据加载成功关闭loading
                        this.child.handleLoading();
                    })
                }
            },
            error: function () {
                this.setState({ tableData: [], total: 0, loading: false }, () => {
                    // 数据加载成功关闭loading
                    this.child.handleLoading();
                })
            }
        })
    }

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

    handleHospID = e => {
        this.setState({ hosp: e }, () => {
            this.handleQuery();
        })
    }

    // 是否生效
    handleCheckbox = e => {
        this.setState({ status: e.target.checked }, () => {
            this.handleQuery();
        })
    }
    // 重置
    resetFields = () => {
        this.props.form.resetFields(); //清空所有
        this.setState({
            rowData: {}
        })
    }
    // 保存
    handleSave = () => {
        const { form: { validateFields } } = this.props;
        let { user, medID } = this.state;
        validateFields((errors, values) => {
            if (errors === null) {
                let data = {
                    params: []
                };
                let obj = JSON.parse(JSON.stringify(values));
                obj.userID = user.userID;
                obj.logonHospID = user.hospID;
                obj.groupID = user.groupID;
                obj.medID = medID; // 医嘱项id
                obj.startDate = obj.startDate ? Moment(obj.startDate).format("YYYY-MM-DD") : '';
                obj.stopDate = obj.stopDate ? Moment(obj.stopDate).format("YYYY-MM-DD") : '';
                data.params.push(obj);
                $http.post('urlADS', this, {
                    code: '03010038',
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            message.success('新增成功');
                            this.handleQuery();
                            this.resetFields();
                        }
                    }
                })
            }
        })
    }

    // 重置
    resetFields = () => {
        this.props.form.resetFields(); //清空所有
        this.setState({
            rowData: {}
        })
    }

    // 删除
    handleDelete = record => {
        let { user } = this.state;
        let data = {
            params: [{
                id: record.id,
                userID: user.userID,
                logonHospID: user.hospID,
                groupID: user.groupID,
            }]
        }
        $http.post('urlADS', this, {
            code: '03010039',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    message.success('删除成功');
                    // 刷新列表数据
                    this.getTableData();
                }
            }
        })
    }

    render() {
        let { selectData, hosp, status, tableData, total, page, rowData, loading } = this.state;
        const { getFieldDecorator } = this.props.form;
        // 组件所需参数
        const param = {
            // 表头配置
            columns: this.columns,
            // 表格数据
            data: tableData,
            // 数据总条数
            total: total,
            // 当前页数
            page: page,
            // 表格的宽度
            x: 900,
            y: 360,
            TableClassName: "ols",
            height: '400px',
            loading
        };

        // 医院
        let hospOption = selectData.hosp && selectData.hosp.map((item, index) => {
            return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
        })
        return (
            <div className="associated">
                <div>
                    <div style={{ background: 'rgba(228, 228, 228, 1)', height: '32px', lineHeight: '32px', fontWeight: '700' }}>
                        添加使用医院
                        <span style={{ fontSize: '12px', color: '#157EDF', fontWeight: '100', marginLeft: '10px' }}>(说明：关联医院后仅该医院可使用该医嘱项)</span>
                    </div>
                    <div>
                        <Form>
                            <Form.Item label="医院：">
                                {getFieldDecorator('hospID', {
                                    initialValue: rowData.hospID ? rowData.hospID : undefined,
                                    rules: [{ required: true, message: '医院不能为空' }]
                                })(
                                    <Select showSearch optionFilterProp="seatchprop" allowClear style={{ width: '200px', marginRight: '8px' }} placeholder="请选择">
                                        {hospOption}
                                    </Select>
                                )}
                            </Form.Item>
                            <Form.Item label="生效日期：">
                                {getFieldDecorator('startDate', {
                                    initialValue: rowData.startDate ? rowData.startDate : undefined,
                                    rules: [{ required: true, message: '生效日期不能为空' }]
                                })(
                                    <DatePicker style={{ width: '150px', marginRight: '8px' }} format="YYYY-MM-DD" allowClear />
                                )}
                            </Form.Item>
                            <Form.Item label="失效日期：">
                                {getFieldDecorator('stopDate', {
                                    initialValue: rowData.stopDate ? rowData.stopDate : undefined,
                                })(
                                    <DatePicker style={{ width: '150px', marginRight: '8px' }} format="YYYY-MM-DD" allowClear />
                                )}
                            </Form.Item>
                            <span style={{ display: 'inline-block', margin: '4px 8px 0 0' }}>
                                <Button type="primary" onClick={this.handleSave}>保存</Button>
                            </span>
                            <span style={{ display: 'inline-block', marginTop: '4px' }}>
                                <Button onClick={this.resetFields}>清空</Button>
                            </span>
                        </Form>
                    </div>
                </div>
                <div>
                    <div style={{ background: 'rgba(228, 228, 228, 1)', height: '32px', lineHeight: '32px', fontWeight: '700' }}>
                        已添加医院
                        <span style={{ float: 'right', fontWeight: '100' }}>
                            <Select value={hosp} onChange={this.handleHospID} onPressEnter={this.handleHospNameEnter} showSearch optionFilterProp="seatchprop" allowClear style={{ width: '200px', marginRight: '8px' }} placeholder="根据医院过滤数据">
                                {hospOption}
                            </Select>
                            <Checkbox checked={status} onChange={this.handleCheckbox} style={{ fontSize: '12px', color: '#000' }}>仅显示生效</Checkbox>
                        </span>
                    </div>
                    <PubilcTablePagination param={param} handelThis={this} onRef={this.onRef} />
                </div>
            </div>
        )
    }
};
const OLAssociatedHospitalForm = Form.create()(OLAssociatedHospital);
export default OLAssociatedHospitalForm;