//控制级别维护
import React from 'react';
import { Card, Row, Col, Form, DatePicker, Select, Button, Checkbox, Table, Switch, message, Pagination, Input, Icon, Divider, Popconfirm } from 'antd';
import { $http } from 'containers/config/https';
import CommonPagination from 'components/pagination/index';
import Moment from 'moment';
import store from 'store';

const { Option } = Select;
const FormItem = Form.Item;
const formItemLayout = {    // label 和input宽度
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
};
const formItemItem = {
    labelCol: { span: 10 },
    wrapperCol: { span: 14 }
};
const OPControlLevelMaintenance = Form.create()(
    class extends React.Component {
        constructor() {
            super();
            this.state = {
                userInfo: {}, //表单数据详情
                tableData: [], // 表格数据
                pageSize: 10,
                delID: '',
                uID: '',
                page: 1,
                total: 0,
                locEntry: "",
                locExcute: "",
                locDispensing: "",
                rowKey: '', //行选中id
                rowData: {}, //当前行数据
                language: JSON.parse(window.sessionStorage.userData),
                columns: [],
                detailWidthTotal: ''
            }
            // 库存单的数据表头
            this.columns = [

                {
                    title: '级别名称',
                    dataIndex: 'Code',
                    align: "center",
                    width: '10%'
                },
                {
                    title: '级别描述',
                    dataIndex: 'Descripts',
                    align: "center",
                    width: '15%'
                },
                {
                    title: '级别类型',
                    dataIndex: 'ChartType',
                    align: "center",
                    width: '10%'
                },
                {
                    title: '允许录入医嘱',
                    dataIndex: 'IfOrderEntry',
                    align: "center",
                    width: '20%',
                    render: (text, record) => (
                        <span>
                            <Switch checked={record.IfOrderEntry == 'Y' ? true : false} size="small" bordered defaultChecked />
                        </span>

                    ),
                },
                {
                    title: '允许执行医嘱',
                    dataIndex: 'IfOrderExcute',
                    align: "center",
                    width: '20%',
                    render: (text, record) => (
                        <span>
                            <Switch checked={record.IfOrderExcute == 'Y' ? true : false} size="small" bordered defaultChecked />
                        </span>
                    ),
                },
                {
                    title: '允许发药',
                    dataIndex: 'IfDispensing',
                    align: "center",
                    width: '20%',
                    render: (text, record) => (
                        <span>
                            <Switch checked={record.IfDispensing == 'Y' ? true : false} size="small" bordered defaultChecked />
                        </span>
                    ),
                },
                {
                    title: '操作',
                    key: 'op',
                    align: "center",
                    width: '5%',
                    render: (text, record) => (
                        <span>
                            <Popconfirm
                                title="确定要删除吗?"
                                onConfirm={this.delConfirm}
                                okText="是"
                                cancelText="否"
                            >
                                <span style={{ color: '#f00' }} className='span' onClick={() => this.setState({ delID: record.ID })}><Icon type="delete" />删除</span>
                            </Popconfirm>
                        </span>
                    ),
                },
            ]
        }

        componentDidMount() {
            //初始化数据
            this.handleQuery();
        }
        //查询数据
        handleQuery = () => {
            let { page, pageSize, uID } = this.state;
            let data = {}
            data = {
                params: [{
                }],
                pagination: [{
                    pageSize: pageSize,
                    currentPage: page,
                    sortColumn: 'code',
                    sortOrder: 'asc'
                }]
            }
            $http.post('urlS', this, {
                code: '05100001',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0 && res.data) {
                        for (var i = 0; i < res.data.length; i++) {
                            res.data[i].key = i;
                        }
                        this.setState({ tableData: res.data, total: res.data.length, loading: false })

                    } else {
                        this.setState({ tableData: [], total: 0, loading: false })
                    }
                }
            })
        }

        //弹窗点击确定
        handleAdd = () => {
            this.props.form.validateFields((err, values) => {
                if (err) {
                    return;
                }
                let data = {};
                let code = '05100002';
                data = {
                    params: [{
                        ID: this.state.rowKey,
                        userID: JSON.parse(window.sessionStorage.userData).userID,
                        updateID: JSON.parse(window.sessionStorage.userData).userID,
                        Hosp: JSON.parse(window.sessionStorage.userData).hospID,
                        Code: values.Code,
                        Descripts: values.Descripts,
                        ChartType: values.ChartType,
                        IfOrderEntry: this.state.locEntry,
                        IfOrderExcute: this.state.locExcute,
                        IfDispensing: this.state.locDispensing,
                    }]
                }

                $http.post('urlS', this, {
                    code: code,
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {

                            if (this.state.rowKey) {
                                message.success("修改成功")
                                this.resetFields();
                                this.handleQuery();
                            } else {
                                message.success("新增成功")
                                this.resetFields();
                                this.handleQuery();
                            }
                        } else {
                            message.error('失败：' + res.errorMessage);
                        }
                        this.setState({ loading: false, visible: false });
                    },
                    error: function (error) {
                        message.error('失败：' + error);
                    }
                })
            })
        };
        //删除确认
        delConfirm = (e) => {
            this.handleDel();
        }
        //删除
        handleDel() {
            let data = {
                params: [{
                    delID: this.state.delID,
                }]
            }
            $http.post('urlS', this, {
                code: '05100004',
                data: data,
                success: function (res) {
                    if (res.errorCode === "0") {
                        message.success('删除成功！');
                        //刷新列表数据
                        this.handleQuery()
                    }
                }
            })
        }
        //Switch开关
        changeSwitch = (e, name) => {
            console.log(e + name)
            this.setState({
                [name]: e ? 'Y' : 'N'
            })
        }

        // 表格行的类名
        setRowClassName = (record) => {
            return record.ID === this.state.rowKey ? 'clickRowStyle' : '';
        };
        //清空表格内容
        resetFields = () => {
            this.props.form.resetFields();
            this.setState({ Code: '', Descripts: '', IfOrderEntry: '', IfOrderExcute: '', IfDispensing: '', ChartType: '', rowKey: '', rowData: '' });
        };
        handleReset = () => {
            this.resetFields();
            this.setState({ tableData: [], total: 0 });
        }
        // 设置行属性
        onClickRow = (record) => {
            return {
                // 单击行选中
                onClick: (e) => {
                    e.stopPropagation();
                    this.resetFields();

                    if (this.state.rowKey === '') {
                        // 保存行数据以及ID
                        this.setState({ rowKey: record.ID });
                        this.conLeveData(record)
                    } else {
                        if (this.state.rowKey !== record.ID) {
                            this.setState({ rowKey: record.ID });
                            this.conLeveData(record)
                        } else {
                            this.setState({ rowKey: '', userInfo: {} });
                            this.resetFields();
                        }
                    }
                }
            }
        };
        //选中行查询
        conLeveData = (record) => {
            this.setState({
                locEntry: record.IfOrderEntry,
                locExcute: record.IfOrderExcute,
                locDispensing: record.IfDispensing,
                ID: record.ID,
            })
            this.props.form.setFieldsValue({
                "Code": record.Code,
                "Descripts": record.Descripts,
                "ChartType": record.ChartType,
                "IfOrderEntry": record.IfOrderEntry,
                "IfOrderExcute": record.IfOrderExcute,
                "IfDispensing": record.IfDispensing,
            })
        };
        render() {
            const { getFieldDecorator } = this.props.form;
            const { userInfo, ChineseEnglishSize, columns } = this.state;
            return (
                <div className="OPControlLevelMaintenance" >
                    <Col span={24}>
                        <Row>
                            <Card
                                title={<div className="card-title-left-icon"><div></div>控制级别维护</div>}
                                size="small"
                            >
                                <Col span={24}>
                                    <Row >
                                        <Col span={5}>
                                            <FormItem {...formItemLayout} label="级别名称">
                                                {getFieldDecorator('Code', {
                                                    initialValue: undefined,
                                                    rules: [{ required: true, message: '名称不能为空' }],
                                                })(
                                                    <Input />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={5}>
                                            <FormItem {...formItemLayout} label="级别描述">
                                                {getFieldDecorator('Descripts', {
                                                    initialValue: undefined,
                                                })(
                                                    <Input />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={5}>
                                            <FormItem {...formItemLayout} label="级别类型">
                                                {getFieldDecorator('ChartType', {
                                                    initialValue: undefined,
                                                })(
                                                    <Select allowClear style={{ width: '100%' }}>
                                                        <Option value="1" key="1" >控制</Option>
                                                        <Option value="0" key="0" >预警</Option>
                                                    </Select>
                                                )}
                                            </FormItem>
                                        </Col>
                                    </Row>
                                    <Row>
                                        <Col span={5}>
                                            <FormItem {...formItemLayout} label="允许录入医嘱">
                                                {getFieldDecorator('IfOrderEntry', {
                                                    initialValue: this.state.locEntry == 'Y' ? true : false,
                                                    valuepropName: 'checked'
                                                })(
                                                    <Switch checked={this.state.locEntry == 'Y' ? true : false} onChange={(e) => this.changeSwitch(e, 'locEntry')} defaultChecked />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={5}>
                                            <FormItem {...formItemLayout} label="允许执行医嘱">
                                                {getFieldDecorator('IfOrderExcute', {
                                                    initialValue: this.state.locExcute == 'Y' ? true : false,
                                                    valuepropName: 'checked'
                                                })(
                                                    <Switch checked={this.state.locExcute == 'Y' ? true : false} onChange={(e) => this.changeSwitch(e, 'locExcute')} bordered defaultChecked />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={3}>
                                            <FormItem {...formItemLayout} label="允许发药">
                                                {getFieldDecorator('IfDispensing', {
                                                    initialValue: this.state.locDispensing == 'Y' ? true : false,
                                                    valuepropName: 'checked'
                                                })(
                                                    <Switch checked={this.state.locDispensing == 'Y' ? true : false} onChange={(e) => this.changeSwitch(e, 'locDispensing')} bordered defaultChecked />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col style={{ textAlign: 'center' }} span={3}>
                                            <Button onClick={this.handleAdd}>保存</Button>
                                        </Col>
                                    </Row>
                                </Col>
                            </Card>
                        </Row>
                        <Row>
                            <Col>
                                <Card
                                    size="small"
                                >
                                    <div style={{ height: store.getState().tableHeight.y + 94 + 'px' }}>
                                        <Table
                                            columns={this.columns.length > 0 ? this.columns : this.columns}
                                            dataSource={this.state.tableData}
                                            pagination={false}
                                            bordered
                                            style={{ height: store.getState().tableHeight.y + 61 + 'px' }}
                                            scroll={{ y: store.getState().tableHeight.y + 10 }}
                                            rowKey={record => record.key}
                                            onRow={this.onClickRow}
                                            rowClassName={this.setRowClassName}
                                        />
                                        {/* <CommonPagination size='small' current={this.state.page} total={this.state.total} search='search'
                                            onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.tableData}
                                            loading={this.state.loading} onChange={this.onChange.bind(this)} /> */}
                                    </div>
                                </Card>
                            </Col>
                        </Row>
                    </Col>



                </div >
            )
        }
    }
);
export default OPControlLevelMaintenance;