// 自定义数据值域维护
import React from 'react';
import { $http } from 'containers/config/https';
import { Modal, Table, Input, Button, Popconfirm, Form, Icon, Divider, message } from 'antd';

const EditableContext = React.createContext();

class EditableCell extends React.Component {
  getInput = () => {
    return <Input />;
  };

  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],
            })(this.getInput())}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

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


class RangeMaintenance extends React.Component {
  constructor(props) {
    super(props);
    this.state = { 
      data: [], 
      editingKey: '' ,
      visible: false,
      userInfo: {},
      rowData: {}
    };
    this.columns = [
      {
        title: '实际值',
        dataIndex: 'code',
        editable: true,
        align: 'center',
        width: 150
      },
      {
        title: '显示值',
        dataIndex: 'descripts',
        editable: true,
        align: 'center',
        width: 150
      },
      {
        title: '操作',
        dataIndex: 'operation',
        align: 'center',
        width: 130,
        render: (text, record) => {
          const { editingKey } = this.state;
          const editable = this.isEditing(record);
          return editable ? (
            <span>
							<Icon type="form" style={{color: '#108EE9'}}></Icon>
							<EditableContext.Consumer>
								{form => (
									<a
										onClick={() => this.handleSave(form, record)}
										style={{ marginRight: 8 }}
									>
										保存
									</a>
								)}
							</EditableContext.Consumer>
							<Icon type="delete" style={{color: 'rgba(240,65,52,1)'}}></Icon>
							<Popconfirm title={record&&record.ID ? "是否要取消编辑?" : "该数据没有保存是否确定取消?"} onConfirm={() => this.cancel(record)}>
								<span className='span' style={{color: 'rgba(240,65,52,1)'}}>取消</span>
							</Popconfirm>
						</span>
          ) : (
            <div>
							<Icon type="edit" style={{color: '#108EE9'}}></Icon>
							<span className='span' disabled={editingKey !== ''} onClick={() => this.handleCompile(record)}>
								编辑
							</span>
							<Divider type="vertical" />
							<Icon type="delete" style={{color: 'rgba(240,65,52,1)'}}></Icon>
					 		<Popconfirm title="删除不可恢复，你确定要删除吗?" onConfirm={() => this.handleDelete(record)}>
					 			<span className='span' style={{color: 'rgba(240,65,52,1)'}}>删除</span>
					 		</Popconfirm>
						</div>
          );
        },
      },
    ];
  }

  componentDidMount() {
		this.props.onRef(this);
	}

	// 显示弹出层
	showModal = (record) => {
    this.setState({visible: true, userInfo: record}, () => {
      this.getTableData();
    });
	}

	// 取消
	handleCancel = () => {
		this.setState({
			visible: false,
		});
	}

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

  cancel = (record) => {
    if (record&&record.ID) {
      this.setState({ editingKey: '' });
    } else {
      this.handleDelete(record)
    }
  };

  handleSave = (form, key) => {
    let {userInfo, rowData} = this.state;
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      let ID = rowData&&rowData.ID ? rowData.ID : undefined;
      let data = {
        params: [{
          CBEMRODSParRef: ID ? '' : userInfo.ID,
          ID,
          code: row.code,
          descripts: row.descripts
        }]
      }
      $http.post('urlADS', this, {
        code: ID ? "06010041" : "06010040",
        data: data,
        success: function (res) { 
          if (+res.errorCode === 0) {
            // 成功提示
            message.success(`${ID ? '保存' : '新增'}成功`);
            this.getTableData();
          }
        }
      })
    });
  }

  handleCompile = (record) => {
    this.setState({ editingKey: record.key, rowData: record });
  }

  // 获取其他自定义数据值 维护使用
  getTableData = () => {
    let {userInfo} = this.state;
    this.setState({data: [], editingKey: ""});
    let data = {
			params: [{
        ID: userInfo.ID
      }],
		}
		$http.post('urlS', this, {
			code: "06010044",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0 && res.result) {
					for(var i = 0; i < res.result.length; i++) {
						res.result[i].key = i + 1;
					}
					this.setState({ data: res.result, editingKey: ""})
				}
      }
		})
  }

  // 新增
  handleAdd = () => {
    const { data } = this.state;
		let leg = data&&data.length ? data.length + 1 : 1
    const newData = {
      key: leg,
      code: undefined,
      descripts: undefined,
    };
    this.setState({
      data: [...data, newData],
    }, () => {
			if (!this.state.editingKey) {
				this.setState({editingKey: leg})
			}
		});
  }

  // 删除
	handleDelete = record => {
		if(record&&record.ID) {
			let data = {
				params: [{
					ID: record.ID
				}]
			}
			$http.post('urlADS', this, {
				code: '06010042',
				data: data,
				success: function (res) { 
					if (+res.errorCode === 0) {
						message.success('删除成功');
						// 刷新列表数据
						this.getTableData();
					}
				}
			})
		} else { // 当ID值不存在时本地删除
			const dataSource = [...this.state.data];
			this.setState({ data: dataSource.filter(item => item.key !== record.key) });
		}
  };

  render() {
    let {visible} = this.state;
    const components = {
      body: {
        cell: EditableCell,
      },
    };

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

    return (
      <Modal
				visible={visible}
				title="自定义数据值域维护"
				onCancel={this.handleCancel}
        footer={<div style={{textAlign: 'right'}}>
          <Button
            type="primary"
            onClick={this.handleAdd} 
          >新增</Button>
        </div>}
			>
        <EditableContext.Provider value={this.props.form}>
          <Table
            style={{maxHeight: '500px', overflow: 'auto'}}
            components={components}
            bordered
            dataSource={this.state.data}
            columns={columns}
            rowClassName="editable-row"
            pagination={false}
          />
        </EditableContext.Provider>
      </Modal>
    );
  }
}

const RangeMaintenanceForm = Form.create()(RangeMaintenance);
export default RangeMaintenanceForm;
 