// 接口服务配置
import React from 'react';
import { Select, Input, Row, Col, Button, Spin, message, Icon, Form, Modal, Card } 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';

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

const formItemLayout = {
    labelCol: { span: 10 },
    wrapperCol: { span: 14 },
}
const RWServiceTypeConfigDetail = Form.create()(
    class RWServiceTypeConfigDetail extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                data: [],
                values: {},
                hospital: []     // 医院
            }
        }
        componentDidMount() {
            // 初始化设置table的高度以及表体的高度 内容高度 height 
            // if (document.querySelector('.ant-table-body')) {
            //     document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y - 40 + 'px'
            // }
            // this.getSelectData();
        }
        //获取下拉框数据
        getSelectData() {
            let data = {
                params: [{ }]
            }
            $http.post('urlS', this, {
                code: "01040102",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            hospital: res.result.data
                        })
                    }
                }
            })
        }
        setRowClassName = (record) => {
            return record.hospID === this.state.rowId ? 'clickRowStyle' : '';
        }
        FindData = () => {
            const { propMethod: { findData } } = this.props;
            this.showModal(false);
            findData();
            this.reset();
        }
        handleStatus = (v) => {
        }
        save = () => {
            this.props.form.validateFields((err, values) => {
                const { data: params } = this.props;
                if (!err) {
                    let data = {
                        params: [{
                            id: params && params.id ? params.id : "",
                            code: values.code || "",
                            descripts: values.descripts || "",
                            serviceIP: values.serviceIP || "",
                            port: values.port || "",
                            authorization: values.authorization || ""
                        }]
                    }
                    $http.post("urlS", this, {
                        code: "01040120",
                        data: data,
                        success: function (res) {
                            if (+res.errorCode === 0) {
                                if (params && params.id) {
                                    message.success("修改成功")
                                    this.FindData();
                                } else {
                                    message.success("新增成功")
                                    this.FindData();
                                }
                            } else {
                                message.error('失败：' + res.errorMessage);
                            }
                        },
                        error: function (error) {
                            message.error('失败：' + error);
                        }
                    })
                } else {
                }
            })
        }
        reset = () => {
            this.props.form.resetFields();
        }
        showModal = (bool) => {
            const { propMethod: { showModal } } = this.props;
            showModal(bool);
            this.reset();
        }
        render() {
            const { modalVisible, data: params } = this.props;
            const { getFieldDecorator } = this.props.form;
            const { hospital } = this.state;

            return (
                <Modal onCancel={() => this.showModal(false)} title={<span>{params ? params.hospDesc : ''}</span>} visible={modalVisible} width={1200} footer={<div style={{ display: "flex", justifyContent: "flex-end" }}>
                    <Button style={{ marginRight: '30px' }} onClick={() => this.showModal(false)}>取消</Button>
                    <Button style={{ marginRight: '30px' }} type="primary" onClick={this.save}>{params && params ? "更新" : "新增"}</Button>
                    <Button type="primary" onClick={this.reset}>重置</Button>
                </div>} >
                    <Row style={{ margin: "0" }}>
                        <Col span={24} style={{ paddingLeft: "0px" }}>
                            <Card>
                                <Form style={{ height: "100%", overflow: "hidden auto" }}>
                                    <Row>                                        
                                        <Col span={8}>
                                            <FormItem {...formItemLayout} label='代码'>
                                                {getFieldDecorator('code', {
                                                    initialValue: params && params.code ? params.code : undefined,
                                                    rules: [{ required: true, message: '请输入代码', },
                                                    ],
                                                })(
                                                    <Input />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={8}>
                                            <FormItem {...formItemLayout} label='描述'>
                                                {getFieldDecorator('descripts', {
                                                    initialValue: params && params.descripts ? params.descripts : undefined,
                                                    rules: [{ required: true, message: '请输入描述' }],
                                                })(
                                                    <Input />
                                                )}
                                            </FormItem>
                                        </Col>  
                                        <Col span={8} >
                                            <FormItem {...formItemLayout} label='服务器地址'>
                                                {getFieldDecorator('serviceIP', {
                                                    initialValue: params && params.serviceIP ? params.serviceIP : undefined,
                                                    rules: [{ message: '', },
                                                    ],
                                                })(
                                                    <Input />
                                                )}
                                            </FormItem>
                                        </Col>                                      
                                    </Row>                                    
                                    <Row>                                        
                                        <Col span={8} >
                                            <FormItem {...formItemLayout} label='端口'>
                                                {getFieldDecorator('port', {
                                                    initialValue: params && params.port ? params.port : undefined,
                                                    rules: [{ message: '', },
                                                    ],
                                                })(
                                                    <Input />
                                                )}
                                            </FormItem>
                                        </Col>
                                        <Col span={8} >
                                            <FormItem {...formItemLayout} label='授权'>
                                                {getFieldDecorator('authorization', {
                                                    initialValue: params && params.authorization ? params.authorization : undefined,
                                                    rules: [{ message: '', },
                                                    ],
                                                })(
                                                    <Input />
                                                )}
                                            </FormItem>
                                        </Col>                                    
                                    </Row>                                    
                                </Form>
                            </Card>
                        </Col>
                    </Row>
                </Modal>
            );
        }
    });

class RWServiceTypeConfig extends React.Component {
    constructor() {
        super();
        this.state = {
            tableData: [],      // 表格数据          
            total: 0,           // 表格数据总条数
            column: [],         // 表头
            showLoading: true,
            page: 1,
            pageSize: 10,
            headerHeight: 0,
            modalVisible: false,
            editData: {},
            hospital: []
        };
    }

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

    componentWillUnmount() {
        // 组件销毁前将静止让setState修改state的状态
        this.setState = (state, callback) => { return; }
    }
    //获取下拉框数据
    getSelectData() {
        let data = {
            params: [{ }]
        }
        $http.post('urlS', this, {
            code: "01040102",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        hospital: res.result.data
                    })
                }
            }
        })
    }
    // 获取表头信息
    getColumn = () => {
        let data = {
            params: [{
                compontName: "RWServiceTypeConfig",
                type: "C",
            }]
        }
        $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()}>{item.title}</div>,
                            display: item.display,
                            key: item.id
                        }
                    }) : '';
                    let obj = {
                        title: '操作',
                        key: 'zzz',
                        align: "center",
                        width: 50,
                        render: (text, record) => (
                            <span>
                                <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
                                <span className='span' onClick={() => this.handleCompile(record)}>{'编辑 | '}</span>
                                <Icon type="delete" style={{ color: 'rgba(240,65,52,1)' }}></Icon>
                                <span className='span' onClick={() => this.delete(record)}>删除</span>
                            </span>
                        )
                    }
                    column.push(obj);
                    this.setState({ column })
                }
            }
        })
    }
    // 调用子组件的连接事件
    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: [{
                    code: values.code ? values.code : '',
                    descripts: values.descripts ? values.descripts : '',
                    hospID: values.hospID ? values.hospID : ''
                }],
                pagination: [{
                    pageSize: pageSize,
                    currentPage: page,
                    sortColumn: "",
                    sortOrder: ""
                }]
            };
            $http.post('urlS', this, {
                code: "01040121",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0 && res.result) {
                        this.setState({ tableData: res.result.Data, total: res.result.TotalCount }, () => {
                            // 数据加载成功关闭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();
                    })
                }
            });
        });

    }
    delete = (record) => {
        let data = {
            params: [{
                id: record.id
            }],
        }
        $http.post("urlS", this, {
            code: "01040122",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    message.success("删除成功")
                    this.handleQuery()
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            },
            error: function (error) {
                message.error('失败：' + error);
            }
        })
    }
    // 查询
    handleQuery = () => {
        this.setState({ page: 1, pageSize: 10 }, () => {
            this.getTableData();
        })
    }

    // 新增跳转到新增界面
    handleAdd = () => {
        this.setState({ editData: undefined });
        this.showModal(true);
    }

    // 编辑
    handleCompile = (record) => {
        this.setState({ editData: record });
        this.showModal(true);
    }
    //控制模态框显示
    showModal = (bool) => {
        this.setState({ modalVisible: bool });
    }
    onColumnRef = (ref) => {
        this.columnRef = ref;
    }
    // 获取主列表columns
    getMainTableColumns = () => {
        let data = {
            params: [{
                compontName: 'RWServiceTypeConfig', // 读写服务配置
                type: 'C',
            }]
        }
    }
    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',
        }
        let hospitalArr = []
        this.state.hospital && this.state.hospital.map(item => {
            hospitalArr.push(<Option key={item.id} role={item.descripts + '^' + item.descriptsSPCode} title={item.descripts} value={String(item.id)}>{item.descripts}</Option>)
        });
        return (
            <Spin tip="加载中..." spinning={this.state.showLoading}>
                <div>
                    <Form>
                        <Row style={{ margin: '23px 0 0 0' }}>                            
                            <Col span={4} >
                                <FormItem {...formItemLayout} label='代码'>
                                    {getFieldDecorator('code', {
                                        rules: [{ message: '' }],
                                    })(
                                        <Input title="输入内容后可回车检索" placeholder="请输入( Enter )" onPressEnter={this.handleQuery} />
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={4} >
                                <FormItem {...formItemLayout} label='描述'>
                                    {getFieldDecorator('descripts', {
                                        rules: [{ message: '' }],
                                    })(
                                        <Input title="输入内容后可回车检索" placeholder="请输入( Enter )" onPressEnter={this.handleQuery} />
                                    )}
                                </FormItem>
                            </Col>                           
                            <Col offset={7} span={2}>
                                <Button onClick={this.handleQuery} style={{ margin: '4px 15px 20px 0', background: 'rgba(255,255,255,1)' }}>查询</Button>
                            </Col>
                            <Col span={2}>
                                <Button icon="plus" onClick={this.handleAdd} style={{ background: 'rgba(247,128,93,1)', color: '#fff', margin: '4px 0 0 0' }}>新增</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} />
                </div>
                <RWServiceTypeConfigDetail data={this.state.editData} modalVisible={this.state.modalVisible} propMethod={{ showModal: this.showModal, findData: this.handleQuery }} />
                <ColumnAuthoritysModel
                    clientWidth='800px'
                    compontName='RWServiceTypeConfig'
                    configType="C"
                    onRef={this.onColumnRef}
                    reloadData={this.getMainTableColumns}
                />
            </Spin>
        )
    }
}
export default Form.create()(RWServiceTypeConfig);
