import React,{Component} from 'react';
import {
    Table,Button, Col, Row, message,Pagination,Modal
} from 'antd';
import { $http } from '../../containers/config/https';
import EditFieldLink from './EditFieldLink'
import store from '../../store';

const confirm = Modal.confirm;
class CBDataLink extends Component {
    constructor(props) {
        super(props);
        this.state = {
            ClassName:"",
            RefId:"",
            TableWidth:0,
            Columns:[],
            total: 0,
            page: 1,
            pageSize: 10,
            Data:[],
            Total:0,
            RowId:"",
            visible:false,
            ModelTitle:""
        };
    }
    componentWillReceiveProps(nextProps){
        var ClassName="",RefId=""
        if(nextProps.ClassName !== undefined){
            ClassName=nextProps.ClassName
        }else{
            ClassName=""
        }
        if(nextProps.RefId !== undefined){
            RefId=nextProps.RefId
        }else{
            RefId=""
        }
        if(RefId===this.state.RefId){
            return 
        }
        if(RefId===""){
            this.setState({
                Data:[],
                Total:0,
                RefId:"",
                ClassName:ClassName
            })
            return 
        }
        this.getColumn(ClassName)
        this.getData(ClassName,RefId)
        this.setState({
            ClassName:ClassName,
            RefId:RefId
        })
    }
    componentDidMount() {
        // 初始化设置table的高度以及表体的高度
        document.querySelector('.cbdatalink .ant-table-body').style.height = store.getState().tableHeight.y + 'px'
    }
    componentWillMount() {
        var ClassName=this.props.ClassName
        var RefId=this.props.RefId
        if(ClassName!==""){
            this.getColumn(ClassName)
        }
        if((RefId!=="")&&(ClassName!=="")){
            this.getData(ClassName,RefId)
        }
        this.setState({
            ClassName:ClassName,
            RefId:RefId
        })
    }
    getColumn=(ClassName)=>{
        let data = {
            params: [{ClassName:ClassName}]
        }
        $http.post("urlS",this, {
            code: "4002",
            data: data,
            success: function (res) { 
                if (+res.errorCode === 0) {
                   this.setState({
                       Columns:res.result.Data,
                       TableWidth:res.result.tableWidth
                    })
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            },
            error:function (error) {
                message.error('失败：' + error);
            }
        })
    }
    getData=(ClassName,RefId)=>{
        let {page, pageSize} = this.state;
        let data = {
            params: [{
                ClassName:ClassName,
                RefId:RefId
            }],
            pagination:[{
              pageSize: pageSize,
              currentPage: page,
              sortColumn: "",
              sortOrder: ""
            }]
        }
        $http.post("urlS",this, {
            code: "4016",
            data: data,
            success: function (res) { 
                if (+res.errorCode === 0) {
                   this.setState({Data:res.result.Data})
                   this.setState({ Total: res.result.TotalCount})
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            },
            error:function (error) {
                message.error('失败：' + error);
            }
        })
    }
    // 页码改变的回调，参数是改变后的页码及每页条数
    PageChange = (page, pageSize)=> {
        this.setState({page: page, pageSize: pageSize}, () => {
          // 重新调用查询方法
            let ClassName = this.state.ClassName 
            let RefId=this.state.RefId 
            this.getData(ClassName,RefId)
        });
    }
    // 条数改变的回调
    onShowSizeChange = (current, size) => {
        this.setState({page: current, pageSize: size}, () => {
            // 重新调用查询方法
            let ClassName = this.state.ClassName
            let RefId=this.state.RefId  
            this.getData(ClassName,RefId)
        });
    }
    setRowClassName = (record) => {
      return record.ID === this.state.RowId ? 'clickRowStyle' : '';
    }
    tableClickRow = (record) => {
        //给右边的编辑form传值
        //this.refs.editfield.resetFields()
        return {
            onClick: () => {
                if(this.state.RowId===""){
                    this.setState({
                        RowId: record.ID,
                    });
                }else{
                    if(this.state.RowId!==record.ID){
                        this.setState({
                            RowId: record.ID,
                        });
                    }else{
                        this.setState({
                            RowId: ""
                        });
                    }
                }
                         
            },
        };
    }
    Add=()=>{
        if(this.state.ClassName!==""){
            if(this.refs[this.state.ClassName]){
                this.refs[this.state.ClassName].resetFields()
            }
        }
        this.setState({
            ModelTitle:"新增",
            visible:true,
            RowId:""
        })
    }
    Edit=()=>{
        if(this.state.RowId===""){
            message.error("请选择要修改的数据");
            return
        }
        if(this.state.ClassName!==""){
            if(this.refs[this.state.ClassName]){
                //this.refs[this.state.ClassName].resetFields()
            }
        }
        this.setState({
            ModelTitle:"修改",
            visible:true
        })
    }
    Delete=()=>{
		const userData=sessionStorage.userData?JSON.parse(sessionStorage.userData):{}
        var ID=this.state.RowId
        var ClassName=this.state.ClassName
        var that=this
        confirm({
            title: '删除',
            content: '是否要删除数据?',
            onOk() {
                if(ID===""){
                    message.error("请选择要删除的数据");
                    return 
                }
                let data = {
                    params: [{
                        ClassName:ClassName,
                        ID:ID,
                        userID:userData.userID
                    }]
                }
                $http.post("urlS",that, {
                    code: "4018",
                    data: data,
                    success: function (res) { 
                        if (+res.errorCode === 0) {
                            message.success('删除成功');
                            that.getData(that.state.ClassName,that.state.RefId)
                        }else{
                            message.error('失败：' + res.errorMessage);
                        }
                    },
                    error:function (error) {
                        message.error('失败：' + error);
                    }
                })
            },
            onCancel() {
              
            },
          });
    }
    handleOk = (e) => {
        if(this.state.ClassName!==""){
            if(this.refs[this.state.ClassName]){
                this.refs[this.state.ClassName].resetFields()
            }
        }
        this.setState({
          visible: false,
          ModelTitle:""
        });
    }
    
    handleCancel = (e) => {
        if(this.state.ClassName!==""){
            if(this.refs[this.state.ClassName]){
                this.refs[this.state.ClassName].resetFields()
            }
        }
        this.setState({
          visible: false,
          ModelTitle:""
        });
    }
    render() {
        var btnBisabled=this.state.RefId===""?true:false
        return (
            <div className="cbdatalink">
                <div className="table-operations">
                    <Row type="flex" justify="space-between">
                        <Col span={4}>
                            <Button type="primary" disabled={btnBisabled}   onClick={this.Add}>新增</Button>
                        </Col>
                        <Col span={4}>
                            <Button type="primary" disabled={btnBisabled} onClick={this.Edit}>修改</Button>
                        </Col>
                        <Col span={4}>
                            <Button type="primary" disabled={btnBisabled} onClick={this.Delete}>删除</Button>
                        </Col>
                        <Col span={4}>
                        </Col>
                        <Col span={8}>
                        </Col>
                    </Row>      
                </div>
                <Row type="flex" >
                    <Col span={18}> </Col>
                        <Col span={6}> </Col>
                </Row> 
                <br />
                
                <div>
                <Table
                    dataSource={this.state.Data}
                    columns={this.state.Columns}
                    rowClassName={this.setRowClassName}
                    pagination={false}
                    bordered
                    onRow={this.tableClickRow}
                    rowKey="ID"
                    style={{height: store.getState().tableHeight.y  + 'px'}}
                    scroll={{ x: this.state.TableWidth, y: store.getState().tableHeight.y-45 }}
                           
                />
                {/* 分页: total--总条数  defaultCurrent--默认的当前页 hideOnSinglePage--只有一页时隐藏分页器 */}
                    <Pagination
                        size="small"
                        showQuickJumper
                        showSizeChanger
                        defaultCurrent={1}
                        current={this.state.page}
                        total={this.state.Total}
                        onChange={this.PageChange}
                        onShowSizeChange={this.onShowSizeChange}
                        style={{textAlign: "right", marginTop: '10px'}}
                    />
            </div>
            <div>
                <Modal
                title={this.state.ModelTitle}
                visible={this.state.visible}
                onOk={this.handleOk}
                onCancel={this.handleCancel}
                destroyOnClose={true}
                width="800px"
                footer={[
                    
                  ]}
                >
                    <EditFieldLink  rowId={this.state.RowId} RefId={this.state.RefId} ClassName={this.state.ClassName} handelThis={this} ref={this.state.ClassName}/>
                                                    
                </Modal>
            </div>
        </div>
        );
    }
}

export default CBDataLink;