// 剂量转换单位
import React from 'react';
import { Form, Input, Select, Button, message, Row, Icon, Divider, Popconfirm } 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 OLDoseConversionUnit 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: '',
            doseUnitID: undefined, // 等效单位
            loading: false
        };
        this.columns = [
            {
                key: 1,
                title: '序号',
                dataIndex: 'key',
                align: "center",
                width: 80
            },
            // {
            //     key: 2,
            //     title: '医院',
            //     dataIndex: 'hospDesc',
            //     align: "center",
            //     width: 150
            // },
            {
                key: 3,
                title: '等价数量',
                dataIndex: 'doseQty',
                align: "center",
                width: 80
            },
            {
                key: 4,
                title: '等价单位',
                dataIndex: 'doseUnitDesc',
                align: "center",
                width: 150
            },
            // {
            //     key: 5,
            //     title: '状态',
            //     dataIndex: 'states',
            //     align: "center",
            //     render(states){
            //         let config = {
            //             'Y': '生效',
            //             'N': '失效'
            //         }
            //         return config[states];
            //     }
            // },
            {
                key: 6,
                title: '默认数量',
                dataIndex: 'defaultQty',
                align: "center",
                width: 80
            },
            {
                title: '操作',
                key: 7,
                align: "center",
                width: 130,
                render: (text, record) => (
                    <span>
                        <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
                        <span className='span' onClick={() => this.handleCompile(record)}>编辑</span>
                        {/* 分割线 */}
                        <Divider type="vertical" />
                        <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();
                this.resetFields();
            })
        }
    }

    // 调用子组件的连接事件
    onRef = (ref) => {
        this.child = ref
    }
    compilePage = (page, pageSize) => {
        this.setState({
            page,
            pageSize,
        }, () => {
            this.getTableData()
        })

    }

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

    // 请求列表数据
    getTableData() {
        this.setState({ loading: true });
        let { page, pageSize, status, hosp, medID, doseUnitID } = this.state;
        let data = {
            params: [{
                medID, // 医嘱项id
                hospID: hosp,
                doseUnitID,
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: "Describe",
                sortOrder: "asc"
            }]
        }
        $http.post('urlS', this, {
            code: "02020015",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.result) {
                    for (var i = 0; i < res.result.rows.length; i++) {
                        res.result.rows[i].key = i + 1
                    }
                    this.setState({ tableData: res.result.rows, total: res.result.total, 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();
        })
    }

    handledoseUnitID = e => {
        this.setState({ doseUnitID: 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 { rowData, user, medID } = this.state;
        validateFields((errors, values) => {
            if (errors === null) {
                let data = {
                    params: []
                };
                let obj = JSON.parse(JSON.stringify(values));
                obj.ID = rowData && rowData.ID ? rowData.ID : undefined;
                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: '02020014',
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            message.success(rowData && rowData.ID ? '编辑成功' : '新增成功');
                            this.handleQuery();
                            this.resetFields();
                        }
                    }
                })
            }
        })
    }

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

    // 编辑
    handleCompile = record => {
        this.setState({ rowData: record })
    }

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

    render() {
        let { selectData, hosp, status, tableData, total, page, rowData, doseUnitID, 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>)
        })
        // 等效单位
        let unitOption = selectData.unit && selectData.unit.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>
                            <Row>
                                {/* <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('doseQty', {
                                        initialValue: rowData.doseQty ? rowData.doseQty : undefined,
                                        rules: [{ required: true, message: '等效数量不能为空' }]
                                    })(
                                        <Input type="number" className="input-number" style={{ width: '70px', marginRight: '8px' }} placeholder="请输入" />
                                    )}
                                </Form.Item>
                                <Form.Item label="等效单位">
                                    {getFieldDecorator('doseUnitID', {
                                        initialValue: rowData.doseUnitID ? rowData.doseUnitID : undefined,
                                        rules: [{ required: true, message: '等效单位不能为空' }]
                                    })(
                                        <Select showSearch optionFilterProp="seatchprop" allowClear style={{ width: '100px', marginRight: '8px' }} placeholder="请选择">
                                            {unitOption}
                                        </Select>
                                    )}
                                </Form.Item>
                                <Form.Item label="默认数量：">
                                    {getFieldDecorator('defaultQty', {
                                        initialValue: rowData.defaultQty ? rowData.defaultQty : undefined,
                                    })(
                                        <Input type="number" className="input-number" style={{ width: '70px', marginRight: '8px' }} placeholder="请输入" />
                                    )}
                                </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>
                            </Row>
                            {/* <Row>
                                <Form.Item label="生效日期：">
                                    {getFieldDecorator('stDate', {
                                        initialValue: rowData.stDate ? rowData.stDate : undefined,
                                        rules: [{ required: true, message: '生效日期不能为空' }]
                                    })(
                                        <DatePicker style={{width: '150px', marginRight: '8px'}} format="YYYY-MM-DD" allowClear />
                                    )}
                                </Form.Item>
                                <Form.Item label="失效日期：">
                                    {getFieldDecorator('endDate', {
                                        initialValue: rowData.endDate ? rowData.endDate : undefined,
                                    })(
                                        <DatePicker style={{width: '150px', marginRight: '8px'}} format="YYYY-MM-DD" allowClear />
                                    )}
                                </Form.Item>
                                <span style={{display: 'inline-block', marginTop: '4px'}}>
                                    <Button style={{marginRight: '8px'}} onClick={this.resetFields}>清空</Button>
                                    <Button type="primary" onClick={this.handleSave}>保存</Button>
                                </span>
                            </Row> */}
                        </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> */}
                            <Select value={doseUnitID} onChange={this.handledoseUnitID} onPressEnter={this.handleHospNameEnter} showSearch optionFilterProp="seatchprop" allowClear style={{ width: '100px', marginRight: '8px' }} placeholder="等效单位">
                                {unitOption}
                            </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 OLDoseConversionUnitForm = Form.create()(OLDoseConversionUnit);
export default OLDoseConversionUnitForm;