import React,{Component} from 'react';
// import PropTypes from 'prop-types';

import { Pagination,Checkbox, Input, Row, Col, Button, message, Radio ,Table,DatePicker,Select,Card} from 'antd';
// import { Route, Redirect, Switch ,Router,Link,BrowserRouter,HashRouter} from 'react-router-dom';
import CBData from './CBData'
import { $http } from '../../containers/config/https';
import store from '../../store';
const RadioGroup = Radio.Group;
class TableDataConfigNew extends Component { 
    
    constructor(props) {
        super(props);
        this.state = {
            ClassData:[],
            FieldData:[],
            ClassName:"",
            ClassTitle:"",
            selectedRowKeys:[],
            code:"",
            desc:"",
            total: 0,
            page: 1,
            pageSize: 10,
            editdata:""
        };
        
        
    }
    setRowClassName=(record)=>{
        return record.Code === this.state.ClassName ? 'clickRowStyle' : '';
    }
    onClickRow=(record)=>{
        //给右边的编辑form传值
        return {
            onClick: () => {
                //var itemData=res.result
                this.setState({selectedRowKeys:[]})
                var ClassName="",ClassTitle=""
                if(this.state.ClassName===""){
                    ClassName=record.Code
                    ClassTitle=record.Descripts
                }else{
                    if(this.state.ClassName!==record.Code){
                        ClassName=record.Code
                        ClassTitle=record.Descripts
                    }else{
                        ClassName=""
                        ClassTitle=""
                    }
                }
                this.setState({
                    ClassName:ClassName,
                    ClassTitle:ClassTitle
                });
                if(ClassName!==""){
                    this.getFieldData(ClassName)
                }
            },
          };
    }
    getClassData=(code,desc)=>{
        let {page, pageSize} = this.state;
        let data = {
            params: [
                {
                    Descripts:this.state.desc,
                    Code:this.state.code
                }
            ],
            pagination:[{
              pageSize: pageSize,
              currentPage: page,
              sortColumn: "",
              sortOrder: ""
            }]
        }
        //console.log(data)
        $http.post("urlS",this, {
            code: "4010",
            data: data,
            success: function (res) { 
                if (+res.errorCode === 0) {  
                   this.setState({ClassData:res.result.Data})
                   this.setState({ total: res.result.TotalCount})
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            },
            error:function (error) {
                message.error('失败：' + error);
            }
        })    
    }
    componentDidMount() {
        this.getClassData("","")
        //this.getFieldData()
    }
    getFieldData=(className)=>{
        //var className=this.props.className
        let data = {
            params: [{ClassName:className}]
        }
        $http.post("urlS",this, {
            code: "4008",
            data: data,
            success: function (res) { 
                console.log(res)
                if (+res.errorCode === 0) {
                   var data=res.result
                   console.log(data)
                   this.setState({FieldData:data})
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            },
            error:function (error) {
                message.error('失败：' + error);
            }
        })    
    }
    
    handleUp=()=>{
        var keys=this.state.selectedRowKeys
        var data=this.state.FieldData
        var newKeys=[]
        console.log(keys)
        keys=keys.sort(function (m, n) {
            if (m < n) return -1
            else if (m > n) return 1
            else return 0
           });
        console.log(keys)
        for(var i=0;i<keys.length;i++){
            if(keys[i]===0) {
                newKeys.push(keys[i])
                continue
            }
            var curRowData=data[keys[i]]
            var upRowData=data[keys[i]-1]
            data[keys[i]]=upRowData
            data[keys[i]-1]=curRowData
            newKeys.push(keys[i]-1)
        }
        this.setState(
            {
                FieldData:data,
                selectedRowKeys:newKeys
            }
        )
        
       
    }
    handleDown=()=>{
        var keys=this.state.selectedRowKeys
        var data=this.state.FieldData
        var newKeys=[]
        keys=keys.sort(function (m, n) {
            if (m < n) return -1
            else if (m > n) return 1
            else return 0
           });
        for(var i=keys.length-1;i>=0;i--){
            if(keys[i]===data.length-1) {
                newKeys.push(keys[i])
                continue
            }
            // console.log(keys[i])
            var curRowData=data[keys[i]]
            var upRowData=data[keys[i]+1]
            data[keys[i]]=upRowData
            data[keys[i]+1]=curRowData
            newKeys.push(keys[i]+1)
        }
        // console.log(newKeys)
        this.setState(
            {
                FieldData:data,
                selectedRowKeys:newKeys
            }
        )
    }
    saveRecordEdit=()=>{
        var tableData=this.state.FieldData
        var idStr=""
        var EditData=[]
        for(var i=0;i<tableData.length;i++){
            var id=tableData[i].ID
            if(idStr===""){
                idStr=id
            }else{
                idStr=idStr+"^"+id
            }
            if(tableData[i].Descripts===""){
                message.error("字段"+tableData[i].Code+"的描述不能为空");
                return 
            }
            var itemEditData={}
            itemEditData.ID=id
            itemEditData.Descripts=tableData[i].Descripts
            itemEditData.FindFlag=tableData[i].FindFlag
            itemEditData.EditFlag=tableData[i].EditFlag
            itemEditData.ColumnFlag=tableData[i].ColumnFlag
            EditData.push(itemEditData)
        } 
        var className=this.state.ClassName
        let data = {
            
            params: [
                {
                    ClassName:className,
                    FieldSort:idStr,
                    EditData:EditData
                }
            ]
        }
        $http.post("urlADS",this, {
            code: "4009",
            data: data,
            success: function (res) { 
                console.log(res)
                if (+res.errorCode === 0) {
                    message.success('保存成功');
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            },
            error:function (error) {
                message.error('失败：' + error);
            }
        })    
    }
    CheckOnChange=(record,index,field)=>{
        if(record[field]==="Y"){
            record[field]="N"
        }else{
            record[field]="Y"
        }
        var data=this.state.FieldData
        data[index]=record
        this.setState({FieldData:data})
    }
    Add=()=>{
        let className=this.state.code
        if(className===""){
            message.error("请输入表名");
            return 
        }
        var desc=this.state.desc
        if(desc===""){
            message.error("请输入描述");
            return 
        }
        let data = {
            
            params: [
                {
                    Code:className,
                    Descripts:desc
                }
            ]
        }
        $http.post("urlADS",this, {
            code: "4011",
            data: data,
            success: function (res) { 
                if (+res.errorCode === 0) {
                    message.success('保存成功');
                    this.getClassData("","")
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            }
        })    
        
    }
    Find=()=>{

        this.getClassData(this.state.code,this.state.desc)
    }
    InputChange=(e)=>{
        this.setState(
            {code:e.target.value}
        )
    }
    DescChange=(e)=>{
        this.setState(
            {desc:e.target.value}
        )
    }
    handleData=()=>{
        if(this.state.ClassName===""){
            message.error("请选择要维护数据的表");
            return 
        }
        this.setState({
            editdata:1
        })
        //this.props.history.push({ pathname: "/cbdata",state:{ClassName:this.state.ClassName}});
        //this.context.router.history.push({ pathname: "/basic/cbdata",state:{ClassName:this.state.ClassName}});
    }
    DescriptsChange=(record,index,e)=>{
        record.Descripts=e.target.value
        var data=this.state.FieldData
        data[index]=record
        this.setState({FieldData:data})
    }
    // 页码改变的回调，参数是改变后的页码及每页条数
    PageChange = (page, pageSize)=> {
        this.setState({page: page, pageSize: pageSize}, () => {
          // 重新调用查询方法
          this.getClassData("","");
        });
    }
    // 条数改变的回调
    onShowSizeChange = (current, size) => {
        this.setState({page: current, pageSize: size}, () => {
            // 重新调用查询方法
            this.handleQuery();
        });
    }
    render() {
        if(+this.state.editdata===1){
            return (
                <div>
                    <CBData ClassName={this.state.ClassName} ClassTitle={this.state.ClassTitle} />
                </div>
            )
        }
        const classColumns = [
            {
              key: 1,
              title: '表名',
              dataIndex: 'Code',
              width: 150,
              align: "center"
            },
            {
              key: 2,
              title: '表描述',
              dataIndex: 'Descripts',
              width: 150,
              align: "center"
            }
        ]
        const fieldColumns = [
            {
              key: 1,
              title: '字段名',
              dataIndex: 'Code',
              width: 20,
              align: "center"
            },
            {
              key: 2,
              title: '字段描述',
              dataIndex: 'Descripts',
              width: 80,
              align: "center",
              render: (text, record,index) => {
                  var Descripts=record.Descripts
                  
                  return (
                      <Input value={Descripts} onChange={this.DescriptsChange.bind(this,record,index)}></Input>
                  )
              }
            },
            {
                key: 3,
                title: '字段类型',
                dataIndex: 'CompType',
                width: 50,
                align: "center",
                render: (text, record,index) => {
                    if(record.CompType==="Text"){
                        return (
                            <Input disabled={true} />
                        )
                    }else if(record.CompType==="Radio"){
                        return (
                            <RadioGroup disabled={true}>
                            <Radio value="Y">是</Radio>
                                <Radio value="N">否</Radio>
                            </RadioGroup>
                        )
                    }else if(record.CompType==="Date"){
                        return (
                            <DatePicker disabled={true} format="YYYY-MM-DD"/>
                        )
                    }else if(record.CompType==="DR"){
                        return (
                            <Select  style={{ width: 80 }} disabled={true} />
                        )
                    }else if(record.CompType==="Select"){
                        return (
                            <Select  style={{ width: 80 }} disabled={true} />
                        )
                    }
                    else{
                        return (
                            <Input disabled={true} />
                        )
                    }
                }
            },
            {
                key: 4,
                title: '查询标志',
                dataIndex: 'FindFlag',
                width: 40,
                align: "center",
                render: (text, record,index) => {
                    var FindFlag=record.FindFlag
                    if(FindFlag==="Y"){
                        FindFlag=true
                    }else{
                        FindFlag=false
                    }
                    return (
                        <Checkbox checked={FindFlag} onChange={this.CheckOnChange.bind(this,record,index,'FindFlag')}></Checkbox>
                    )
                }
            },
            {
                key: 5,
                title: '编辑标志',
                dataIndex: 'EditFlag',
                width: 40,
                align: "center",
                render: (text, record,index) => {
                    var EditFlag=record.EditFlag
                    if(EditFlag==="Y"){
                        EditFlag=true
                    }else{
                        EditFlag=false
                    }
                    var disabled=false
                    if(+record.ChangeEditFlag===0){
                        disabled=true
                    }
                    return (
                        <Checkbox checked={EditFlag} disabled={disabled} onChange={this.CheckOnChange.bind(this,record,index,'EditFlag')}></Checkbox>
                    )
                   
  
                }
            },
            {
                key: 6,
                title: '列输出标志',
                dataIndex: 'ColumnFlag',
                width: 40,
                align: "center",
                render: (text, record,index) => {
                    var ColumnFlag=record.ColumnFlag
                    if(ColumnFlag==="Y"){
                        ColumnFlag=true
                    }else{
                        ColumnFlag=false
                    }
                    return (
                        <Checkbox checked={ColumnFlag} onChange={this.CheckOnChange.bind(this,record,index,'ColumnFlag')}></Checkbox>
                    )
                }
            },
            {
                key: 7,
                title: '指向表',
                dataIndex: 'DirectTable',
                width: 30,
                align: "center",
            },
            {
              key: 8,
              title: '显示字段名',
              dataIndex: 'ShowField',
              width: 80,
              align: "center"
            }
        ]
        const rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({selectedRowKeys:selectedRowKeys})
            },
            getCheckboxProps: record => ({
              disabled: record.name === 'Disabled User', // Column configuration not to be checked
              name: record.name,
            }),
            selectedRowKeys:this.state.selectedRowKeys
          };
        return (
            
            <div>
                
                <Row type="flex" justify="space-between">
                    <Col span={7}>

                    <Card style={{height:'800px'}}>
                    <div>
                    <Row type="flex" >
                    <Col span={18}> 表名: <Input placeholder="请输入"style={{width: '200px', marginRight: '10px'}} onChange={this.InputChange} value={this.state.code} /> </Col>
                    <Col span={6}>   <Button type="primary" onClick={this.Find}>查询</Button>   </Col>
                    </Row> 
                    <br />
                    <Row type="flex" >
                    <Col span={18}> 描述: <Input placeholder="请输入"style={{width: '200px', marginRight: '10px'}} onChange={this.DescChange} value={this.state.desc} /> </Col>
                
                    <Col span={6}>   <Button type="primary" onClick={this.Add}>增加</Button>  </Col>
                    </Row> 
                    
                        <Table
                            dataSource={this.state.ClassData}
                            columns={classColumns}
                            rowClassName={this.setRowClassName}
                            pagination={false}
                            bordered
                            onRow={this.onClickRow}
                            style={{height: store.getState().tableHeight.y + 45 + 'px'}}
                            scroll={{ x: 300, y: store.getState().tableHeight.y }}
                            //rowSelection={{onChange:this.tableOnChange,type:"radio"}}
                        />
                        <Pagination
                            size="small"
                            showQuickJumper
                            showSizeChanger
                            defaultCurrent={1}
                            total={this.state.total}
                            onChange={this.PageChange}
                            onShowSizeChange={this.onShowSizeChange}
                            style={{textAlign: "right", marginTop: '10px'}}
                            />,
                        {/* 分页: total--总条数  defaultCurrent--默认的当前页 hideOnSinglePage--只有一页时隐藏分页器 */}
                       
                    </div>
                    </Card>
                    </Col>
                    
                    <Col span={17}>
                        <div className="table-operations">
                            <Row type="flex" justify="space-between">
                                <Col span={4}>
                                    <Button type="primary" onClick={this.saveRecordEdit}>保存修改</Button>
                                </Col>
                                <Col span={4}>
                                    <Button type="primary" onClick={this.handleUp}>向上移动</Button>
                                </Col>
                                <Col span={4}>
                                    <Button type="primary" onClick={this.handleDown}>向下移动</Button>
                                </Col>
                                <Col span={12}>
                                <Button type="primary" onClick={this.handleData}>数据维护</Button>
                                </Col>
                            </Row>
                            
                        </div>
                        <Row type="flex" >
                             <Col span={18}> </Col>
                
                                 <Col span={6}> </Col>
                             </Row> 
                             <br />
                        <div>
                            <Table 
                                rowSelection={rowSelection} 
                                bordered 
                                columns={fieldColumns} 
                                dataSource={this.state.FieldData} 
                                pagination={false} 
                               // style={{height: store.getState().tableHeight.y + 45 + 'px'}}
                              
                               
                            />
                            </div>
            
                        
                        
                    </Col>
                </Row>
            </div>
        );
    }
}
export default TableDataConfigNew;