// 核心库
import React from 'react'
import { connect } from 'dva'
// 组件库
import { Form, Table, Button, InputNumber, Popconfirm, message } from 'antd'
import { LayoutCard } from '@woowalker/feui'
import WriteOffNetworkModal from './WriteOffNetworkModal'

const EditableContext = React.createContext();

class EditableCell extends React.Component {
  renderCell = ({ getFieldDecorator }) => {
    const {
      editing,
      dataIndex,
      title,
      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],
            })(
              <InputNumber />
            )}
          </Form.Item>
        ) : (
            children
          )}
      </td>
    );
  };

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


class EaWriteOffNetworkPage extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      head: [],
      data: [],
      editingKey: ''
    }
  }

  componentDidMount() {
    this.loadData()
  }

  onModalRef = (ref) => {
    this.modalChild = ref
  }

  showModal = () => {
    this.modalChild.showModal()
  }

  loadData = () => {
    const json = {
      OrgId: this.props.login.OrgId,
    };
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'EA/AdjustAccounts/GetWriteOffNetworkData',
      payload: json,
      onlyData: false,
      onComplete: (re) => {
        if (re && re.IsSuccessful && re.Data && re.Data.data) {
          const { data, head } = re.Data
          const currState = {
            data,
            head
          }
          this.setState(currState)
        }
      }
    })
  }

  dataSave = () => {
    const json = {
      OrgId: this.props.login.OrgId,
      Data: this.state.data
    };
    this.props.dispatch({
      type: 'app/getDataByPost',
      url: 'EA/AdjustAccounts/WriteOffNetworkDataSave',
      payload: json,
      onlyData: false,
      onComplete: (re) => {
        if (re && re.IsSuccessful && re.Data) {
          if (re.Data.IsSucceed) {
            message.success(re.Data.Msg);
          }
          else
            message.error(re.Data.Msg);
        }
      }
    })
  }

  isEditing = record => record.key === this.state.editingKey;

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

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

  save(form, key) {
    form.validateFields((error, row) => {
      if (error) {
        return;
      }

      const { data, head } = this.state
      let total = 0
      head.forEach((n, i) => {
        let val = +row[n.DataIndex]
        total += val;
      })
      if (total > 100) {
        message.error("核销比例总和不能大于100！")
        return
      }

      const newData = [...data];
      const index = newData.findIndex(item => key === item.key);
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        this.setState({ data: newData, editingKey: '' },()=>{
          this.dataSave()
        });
      } else {
        newData.push(row);
        this.setState({ data: newData, editingKey: '' },()=>{
          this.dataSave()
        });
      }    
    });  
  }

  render() {
    const { data, head } = this.state
    const { formParam, login, dispatch } = this.props
    const columns = [
      {
        title: (
          <div style={{
            position: 'relative',
            width: 160
          }}>
            <div style={{ textAlign: 'right' }}>核销节点</div>
            <div style={{ textAlign: 'left' }}>辅助生产节点</div>
            <div style={{
              position: 'absolute',
              width: '168px',
              height: '1px',
              top: '20px',
              left: '-3px',
              backgroundColor: '#1A3A50',
              transform: 'rotate(15deg)'
            }}>
            </div>
          </div>
        ),
        dataIndex: "Name",
        width: 160
      }
    ]

    head.forEach((n, i) => {
      const item = {
        title: n.Title,
        dataIndex: n.DataIndex,
        key: n.DataIndex,
        editable: true,
        onCell: record => ({
          record,
          dataIndex: n.DataIndex,
          title: n.Title,
          editing: this.isEditing(record),
        }),
      }
      columns.push(item)
    })

    columns.push(
      {
        title: '操作',
        dataIndex: 'operation',
        render: (text, record) => {
          const { editingKey } = this.state;
          const editable = this.isEditing(record);
          return editable ? (
            <span>
              <EditableContext.Consumer>
                {form => (
                  <a
                    onClick={() => this.save(form, record.key)}
                    style={{ marginRight: 8 }}
                  >
                    保存
                  </a>
                )}
              </EditableContext.Consumer>
              <Popconfirm title="确定取消?" onConfirm={() => this.cancel(record.key)}>
                <a>取消</a>
              </Popconfirm>
            </span>
          ) : (
              <a disabled={editingKey !== ''} onClick={() => this.edit(record.key)}>
                编辑
              </a>
            );
        },
      }
    )

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

    return (
      <>
        <LayoutCard style={{ textAlign: 'right' }}>
          <Button icon="plus" onClick={this.showModal}>新增节点</Button>
          {/* <Button type='primary' icon="save" onClick={this.dataSave} style={{ marginLeft: 8 }}>保存</Button> */}
          <EditableContext.Provider value={this.props.form}>
            <Table
              id='EaWriteOffNetworkPageExport'
              components={components}
              bordered
              size='small'
              columns={columns}
              dataSource={data}
              scroll={{ x: 1300 }}
              style={{ marginTop: 8 }}
              rowClassName="editable-row"
              pagination={{ onChange: this.cancel }}
            />
          </EditableContext.Provider>
        </LayoutCard>
        <WriteOffNetworkModal
          onRef={this.onModalRef}
          onLoadData={this.loadData}
          login={login}
          formParam={formParam}
          dispatch={dispatch} />
      </>
    )
  }
}

EaWriteOffNetworkPage.propTypes = {
}

export default connect(({ login, app, search }) => ({ login, app, search }))(Form.create()(EaWriteOffNetworkPage))