/*
 * @Author: your name
 * @Date: 2021-04-27 13:59:57
 * @LastEditTime: 2021-07-07 16:00:28
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /react-antd-admin-template/src/views/groupManage/groupMana/table.js
 */
/*
 * @Author: your name
 * @Date: 2021-04-27 11:19:40
 * @LastEditTime: 2021-04-27 13:29:14
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /react-antd-admin-template/src/views/groupManage/groupIdentity/table.js
 */

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

const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);


class EditableCell extends React.Component {
  state = {
    editing: false,
  };

  toggleEdit = () => {
    const editing = !this.state.editing;
    
    this.setState({ editing }, () => {
      if (editing) {
        this.input.focus();
      }
    });
  };

  save = e => {
    const { record, handleSave } = this.props;
    this.form.validateFields((error, values) => {
      if (error && error[e.currentTarget.id]) {
        return;
      }
      this.toggleEdit();
      handleSave({ ...record, ...values });
    });
  };

  renderCell = form => {
    this.form = form;
    const { children, dataIndex, record, title } = this.props;
    const { editing } = this.state;
    return editing ? (
      <Form.Item style={{ margin: 0 }}>
        {form.getFieldDecorator(dataIndex, {
          rules: [
            {
              required: false,
            },
          ],
          initialValue: record[dataIndex],
        })(<InputNumber ref={node => (this.input = node)} min={0} onPressEnter={this.save} onBlur={this.save} />)}
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{ paddingRight: 24 }}
        onClick={this.toggleEdit}
      >
        {children}
      </div>
    );
  };

  render() {
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editable ? (
          <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
        ) : (
          children
        )}
      </td>
    );
  }
}
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} = this.state;
        //   console.log({editingKey,record});
          return (
            <span>
                 <a disabled={editingKey !== ''} onClick={() => this.editItem(record)}>
                        编辑
                 </a>
                 <Divider type="vertical" />
                 <Popconfirm title=" 是否确定删除?" onConfirm={()=>this.delItem(record)}>
                    <a disabled={editingKey !== ''} >
                            删除
                    </a>
                 </Popconfirm>
             </span>
 
          );
        },
      },
    ];
  }



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

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

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

  delItem=(record)=>{
      this.props.deleteCallback(record);
  }

  changePage(current){
    this.setState({ loading: true });
    this.props.paginationCallback({'currPage':current})
  }

  // rowSelection object indicates the need for row selection
  rowSelection(){
    const {set_checkedBox} = this.props;
    return {
      onChange: (selectedRowKeys, selectedRows) => {
        console.log('selectedRowKeys',selectedRowKeys, 'selectedRows: ', selectedRows);
        selectedRowKeys.length>0&&set_checkedBox(selectedRowKeys);
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
        name: record.name,
      }),
    }
  };
  //直接从表格中更新
  handleSave = row => {
      this.props.updateFromTableCell(row);
  };

  render() {
    
    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave
        }),
      };
    });

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

    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };

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

    return (
        <Table
          bordered
          // rowSelection={this.rowSelection()}
          components={components}
          loading={this.state.loading}
          pagination={paginationProps}
          dataSource={this.state.data}
          columns={columns}
          rowClassName="editable-row"
        />
    );
  }
}

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


export default EditableFormTable;