import React, { Component } from 'react';
import PropTypes from 'prop-types';
// import { currentUser } from 'amos-security/lib/model/auth';
import { Card, Modal, Form, Input } from 'amos-antd';
import { AmosFetch } from '../../../../utils/processor';
import Icon from 'amos-icon';
import OltSerUrl from '../../../../consts/urlConsts';
import { message } from 'amos-framework';
import { currentUser } from './../../../../utils/userConfig';

const createForm = Form.create();
const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 }
  }
};
/**
 * 表格展示的卡片元素
 *
 * @class AddCard
 * @extends {Component}
 */
class AddCard extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  onClick = () => {
    this.setState({ visible: true });
  };

  /**
   * 关闭新增对话框
   */
  handCancel = () => {
    this.props.form.resetFields();
    this.setState({ visible: false });
  };

  /**
   * 提交
   */
  handleSubmit = () => {
    this.props.form.validateFields((errors, values) => {
      if (errors) {
        return;
      }
      let time = new Date().getTime();
      let persistObj = { createTime: time, name: values.newNodeName, orgCode: this.props.orgId, userId: currentUser().userId };
      this.saveSubgraphData(persistObj);
      this.props.form.resetFields();
      this.setState({ visible: false });
    });
  };

  //保存子图
  saveSubgraphData = paramdata => {
    AmosFetch.post(OltSerUrl.addSubgraph, { data: paramdata })
      .then(res => {
        if (res.ok) {
          return res.text();
        } else {
          throw new Error('从服务端获取数据失败！');
        }
      })
      .then(data => {
        let result = JSON.parse(data);
        let resultStatus = result.result;
        if (resultStatus === 'SUCCESS') {
          //界面刷新
          this.props.getSubviewByOrgCode(paramdata.orgCode);
          message.success('保存成功');
        } else {
          message.danger(`保存失败：${result.message}`);
        }
      });
  };

  //校验
  checkValidate = (rule, value, callback) => {
    let re = new RegExp(/^\S*$/);
    if (re.test(value)) {
      callback();
    } else {
      callback('支持1-20位非空格字符！');
    }
  };
  render() {
    let { getFieldProps } = this.props.form;
    //显示名称
    const nodeNameProps = getFieldProps('newNodeName', {
      initialValue: '',
      rules: [{ required: true, message: '支持1-20位非空格字符！' }, { validator: this.checkValidate }]
    });
    return (
      <div className="table-card">
        <Card title={'新建视图'} bodyStyle={{ textAlign: 'center' }}>
          <div className="topo-lib-item" onClick={this.onClick}>
            <Icon className="topo-lib-icon" icon="add" />
          </div>
        </Card>
        <Modal maskClosable={false} title="创建视图" closable visible={this.state.visible} onCancel={this.handCancel} onOk={this.handleSubmit} width={350}>
          <Form horizontal>
            <FormItem {...formItemLayout} hasFeedback label="视图名称: ">
              <Input {...nodeNameProps} placeholder="视图名称（支持1-20位非空格字符）" />
            </FormItem>
          </Form>
        </Modal>
      </div>
    );
  }
}

AddCard.propTypes = {
  form: PropTypes.any,
  cardData: PropTypes.any,
  updateAddView: PropTypes.func,
  getSubviewByOrgCode: PropTypes.func,
  orgId: PropTypes.any
};

export default createForm(AddCard);
