import React, { Component } from 'react';
import PropTypes from 'prop-types';
import CellOperatePanel from './CellOperatePanel';
import { OltSerUrl } from '../../../../consts/urlConsts';
import { Modal,Form,Input } from 'amos-antd';
import { AmosFetch } from '../../../../utils/processor';
import { message } from 'amos-framework';
import './commonDeviceCell.scss';


const createForm = Form.create();
const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 }
  }
};
/**
 *
 * 公共设备card
 * @class CommonDeviceCell
 * @extends {Component}
 */
class CommonDeviceCell extends Component {
  constructor(props){
    super(props);
    this.state = {
      visible: false
    };
  }
  componentWillMount() {

  }

  componentDidMount(){

  }

  componentWillReceiveProps(nextProps) {

  }

  componentWillUnmount() {

  }

  /**
   * 进入规则库界面
   */
  onIntoViewPanel = () => {
    let { subviewInfo,treeName,treeKey,orgId } = this.props;
    subviewInfo.orgName = treeName;
    subviewInfo.expandedKeys = treeKey;
    subviewInfo.orgId = orgId;
    this.props.updateView('2',subviewInfo);
  }

  getBodyBottomContent = () => {
    let { type,subviewInfo } = this.props;
    let content = [];
    if (type === 1) {
      content.push(<div style={{ paddingTop: '10px' }}>创建一个您的新视图</div>);
    } else if (type === 2) {
      content.push(<div style={{ paddingTop: '10px' }}>说明：房间设备最主要的是监控设备</div>);
      content.push(<CellOperatePanel device={subviewInfo} showEditPanel={this.showEditPanel} delView={this.delView} {...this.props} />);
    }
    return content;
  }


  getImg = () => {
    let content = [];
    let { imgUrl } = this.props;
    if (imgUrl === undefined) {
      content.push(<img src={`${OltSerUrl.fetchDeviceImg}/equip-view.png`} alt='' />);
    } else {
      content.push(<img src={`${OltSerUrl.fetchDeviceImg}/${imgUrl}`} alt='' />);
    }
    return content;
  }

  delView = (e) => {
    let { delSubgraph,subviewInfo } = this.props;
    Modal.confirm({
      title: '删除视图',
      content: '是否删除信息？',
      okText: '确定',
      cancelText: '取消',
      onOk() {
        delSubgraph(subviewInfo.id);
      },
      onCancel() {}
    });
  }

  clickCard = (e) => {
    e.stopPropagation();
    let { type } = this.props;
    if (type === 1) {
      this.setState({ visible: true });
    } else if (type === 2) {
      this.onIntoViewPanel();
    }
  }

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

  /**
   * 提交
   */
  handleSubmit = () => {
    this.props.form.validateFields((errors, values) => {
      if (errors) {
        return;
      }
      let { subviewInfo } = this.props;
      let persistObj = { name: values.newNodeName,orgCode: this.props.orgId };
      if (subviewInfo.id !== undefined) {
        Object.assign(persistObj,{ id: subviewInfo.id });
      }
      this.saveSubgraphData(persistObj);
    });
  }

  /**
   * 关闭新增对话框
   */
  handCancel = () => {
    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') {
        if (result.dataList === -1) {
          message.danger(`视图名称重复`);
        } else {
          //界面刷新
          this.props.getSubviewByOrgCode(paramdata.orgCode);
          message.success('操作成功');
          this.props.form.resetFields();
          this.setState({ visible: false });
        }
      } 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 { type,subviewInfo } = this.props;
    let { getFieldProps } = this.props.form;
    //显示名称
    const nodeNameProps = getFieldProps('newNodeName', {
      initialValue: subviewInfo.id === undefined ? '' : subviewInfo.name,
      rules: [
          { required: true, message: '支持1-20位非空格字符！' },
          { validator: this.checkValidate }

      ]
    });
    return (
      <div tabIndex={'0'} className='subgraph-card-root' onClick={this.clickCard}>
        <div className='subgraph-card-head'>
          <div className='subgraph-card-head-text'>
            {subviewInfo !== undefined ? subviewInfo.name : ''}
          </div>
        </div>
        <div className='subgraph-card-body'>
          <div className='subgraph-card-body-center'>
            {type === 1 ? <img src={require('./../../../../assets/iot/deviceManage/add_template.png')} alt='' /> :
            this.getImg()}
          </div>
          <div className='subgraph-card-body-text'>
            {this.getBodyBottomContent()}
          </div>
        </div>
        <Modal
          className='subgraph-modal'
          maskClosable={false}
          title='创建视图'
          closable
          visible={this.state.visible}
          width={350}
          footer={null}
          onCancel={this.handCancel}
        >
          <Form horizontal>
            <FormItem {...formItemLayout} hasFeedback label='名称: '>
              <Input {...nodeNameProps} placeholder='名称（支持1-20位非空格字符）' />
            </FormItem>
          </Form>
          <div className='modal-operate-root'>
            <div className='modal-operate-clone' onClick={this.handCancel} >取消</div>
            <div className='modal-operate-view' onClick={this.handleSubmit} >确定</div>
          </div>
        </Modal>
      </div>
    );
  }
}

CommonDeviceCell.propTypes = {
  form: PropTypes.any,
  type: PropTypes.number,
  imgUrl: PropTypes.string,
  clickDeviceTemplate: PropTypes.func,
  subviewInfo: PropTypes.func,
  cardData: PropTypes.any,
  updateAddView: PropTypes.func,
  getSubviewByOrgCode: PropTypes.func,
  updateView: PropTypes.func,
  orgId: PropTypes.any,
  delSubgraph: PropTypes.func
};

export default createForm(CommonDeviceCell);
