import React from 'react';
import { Table, Input, InputNumber, Popconfirm, Form,Divider} from 'antd';

// const data = [];
// for (let i = 0; i < 100; i++) {
//   data.push({
//     key: i.toString(),
//     name: `Edrward ${i}`,
//     age: 32,
//     address: `London Park no. ${i}`,
//   });
// }
const EditableContext = React.createContext();

class EditableCell extends React.Component {

   

  getInput = () => {
    if (this.props.inputType === 'number') {
      return <InputNumber />;
    }
    return <Input />;
  }

  renderCell = ({ getFieldDecorator }) => {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item style={{ margin: 0 }}>
            {getFieldDecorator(dataIndex, {
              rules: [
                {
                  required: true,
                  message: `请输入 ${title}!`,
                },
              ],
              initialValue: record[dataIndex],
            })(this.getInput())}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  render() {
    return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
  }
}

class EditableTable extends React.Component {
  
  static defaultProps = {
        editCallback: ()=>{},
        deleteCallback:()=>{},
        callbackFromChild:()=>{},
        config:{
            action:{
                deleteBtn:true,
                editBtn:true,  
                editPermissionBtn:false
            }
        } 
  }

  constructor(props) {
    super(props);
    this.state = { data:[], editingKey: '',loading: false,};

    this.columns = [

      ...props.columns,
      {
        title: '操作',
        dataIndex: 'operation',
        render: (text, record) => {
          const { editingKey,edit,del } = this.state;
          const editable = this.isEditing(record);
          const {deleteBtn,editBtn,editPermissionBtn} = this.props.config.action;
        //   console.log({editingKey,record});
          return editable ? (
              <span>
                    <EditableContext.Consumer>
                        {form => (
                        <a
                            onClick={() => this.save(form, record.id)}
                            style={{ marginRight: 8 }}
                        >
                            保存
                        </a>
                        )}
                    </EditableContext.Consumer>
                    <Popconfirm title="是否确定取消?" onConfirm={() => this.cancel(record.id)}>
                        <a>取消</a>
                    </Popconfirm>     
            </span>
          ) : (
            <span>
             
             {
                 editBtn&&<a disabled={editingKey !== ''} onClick={() => this.edit(record.id)}>
                            编辑
                        </a>
             }
             <Divider type="vertical" />
             {
                 deleteBtn&&<Popconfirm title="确定删除该条数据吗?" onConfirm={() => this.handleDelete(record.id)}>
                       <a>删除</a>
                       </Popconfirm>
             }
             {
                 editPermissionBtn&&<a disabled={editingKey !== ''} onClick={() => this.editPermission(record)}>
                                       编辑权限
                                    </a>
             }
             </span>
 
          );
        },
      },
    ];
  }

//   shouldComponentUpdate(nextProps,nextState){
//     //    console.log({nextProps,nextState});
//        if(nextProps.data == this.state.data){
//            return false
//        }else{
//            return true
//        }
//   }

  componentDidMount(){
    this.setState({
        data:this.props.data
    });
    
  }

  componentDidUpdate(prevProps, prevState){
    // console.log({prevProps, prevState});
    if(prevProps.ifUpdateList){
        console.log('update');
        this.setState({
            data:this.props.data
        });
    }
  }

  isEditing = record => {
    //   console.log(record.id,this.state.editingKey);
      return record.id === this.state.editingKey;
  }

  handleDelete = (key)=> {
    //   this.props.deleteCallback()
    this.props.deleteCallback([key]);
  }

  cancel = () => {
    // this.setState({ editingKey: ''});
  };

  save(form, key) {
    // console.log({form,key});
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      const newData = [...this.state.data];
      const index = newData.findIndex(item => key === item.key);

      if (index > -1) {
        const item = {
            ...newData[index],
            ...row
        };

        this.props.editCallback(item);
        this.setState({editingKey: '' });
        
      } else {
        // newData.push(row);
        // this.setState({ data: newData, editingKey: '' });
      }
    });
  }

  edit(key) {
    // console.log({key});
    this.setState({ editingKey: key});
  }

  editPermission(record){
     this.props.callbackFromChild(record);
  }

  changePage(current){
      console.log('页码改变');
      this.setState({ loading: true });
      this.props.paginationCallback({'currPage':current})
  }


  render() {
    const components = {
      body: {
        cell: EditableCell,
      },
    };

    
    
    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: col.dataIndex === 'age' ? 'number' : 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: this.isEditing(record),
        }),
      };
    });

    
    const {
        currPage,
        totalCount,
    } = this.props.pages;
    

    const paginationProps = {
        showSizeChanger: false,
        showQuickJumper: false,
        showTotal: () => `共${totalCount}条`,
        pageSize: 10,
        current: currPage,
        total: totalCount,
        onChange: (current) => this.changePage(current),
    }

    return (
      <EditableContext.Provider value={this.props.form}>
        {/* <Button onClick={this.handleAdd} type="primary" style={{ marginBottom: 16 }}>
          新增人员
        </Button> */}
        <Table
          components={components}
          bordered
          dataSource={this.state.data}
          columns={columns}
          loading={this.state.loading}
          rowClassName="editable-row"
          pagination={
            paginationProps
          }
        />
      </EditableContext.Provider>
    );
  }
}

const EditableFormTable = Form.create()(EditableTable);


export default EditableFormTable;