import React, { Component } from 'react';
import { Button,Form,Collapse,Input,Row,Col,Icon,Card,Modal } from 'amos-antd';
import { Select } from 'amos-framework';
import PropTypes from 'prop-types';
import { AmosFetch } from '../../utils/processor';
import { trim } from 'amos-tool';
import OltSerUrl from '../../consts/urlConsts';
import { message } from 'amos-framework';
import AddInterfaceProperty from './privateInterface/AddInterfaceProperty';
import './../common/style/commonStyle.scss';
import {objOfStrPropTrim,noSpaceLengthValidate} from './../common/utils/validate';
const createForm = Form.create();
const FormItem = Form.Item;
const Panel = Collapse.Panel;
const Option = Select.Option;
const maxDescLength = 500;


/**
 * 新建接口
 *
 * @class AddInterface
 * @extends {Component}
 */
class AddInterface extends Component {
  constructor(props) {
    super(props);
    this.state = {
      //默认打开新建接口面板
      activeKey: '1',
      //新建属性数据集合
      interfaceProList: [],
      //新建接口输入需要向后台提交保存的数据
      itemInfo: {},
      waiting: false//防止多次重复点击
    };
  }

  //下一步
  onClickDown = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        values = objOfStrPropTrim(values);
        this.setState({
          itemInfo: values,
          activeKey: '2'
        });
      }
    });
  }

  //上一步
  onClickUp = () => {
    this.setState({
      activeKey: '1'
    });
  }

  //确定提交事件，向后台发送创建数据方法
  onClick = () => {
    this.setState({waiting: true});
    //提交新增接口数据到后端
    let { itemInfo,interfaceProList } = this.state;
    itemInfo.dicIdCommMode = parseInt(itemInfo.type);
    itemInfo.remark = itemInfo.desc;
    itemInfo.attributes = interfaceProList;
    itemInfo.visibility = 1;
    AmosFetch.post(OltSerUrl.interfaceSave,{ data: itemInfo }).then(res => {
      if (res.ok) {
        return res.json();
      }
      else
      {
        throw new Error('从服务端获取数据失败！');
      }
    }).then((data)=>{
      if (data.result === 'SUCCESS'){
        message.success('新增通讯方式成功！');
        this.props.updateAddView('2');
      } else {
        this.setState({waiting: false});
        message.danger('新增接口失败！');
      }
    });
  }

  //删除一条数据
  delBtn = (flag) => {

    Modal.confirm({
      title: '删除',
      content: '是否删除所选信息？',
      okText: '确定',
      cancelText: '取消',
      onOk: ()=>{
        let interfaceProList = this.state.interfaceProList;
        for (var i = 0; i < interfaceProList.length; i++) {
          let element = interfaceProList[i];
          if (element.uuid === flag){
            interfaceProList.splice(i,1);
            break;
          }
        }
        this.setState({
          interfaceProList
        });
      },
      onCancel() {}
    });
  };

  //根据属性数据自动生成对应的所需要展示的card
  autoProView = () => {
    let interfaceProList = this.state.interfaceProList;
    let antoView = [];
    antoView.push(<div className='table-card' key={0}>
      <Card style={{ width: 250,height: 170 }}>
        <div style={{ textAlign: 'center',marginTop: '1rem' }}>
          <AddInterfaceProperty addIntfcArrt={this.addIntfcArrt} repuestType='addProperty' />
          <h3>新建设备接口参数</h3>
        </div>
      </Card>
    </div>);
    if ( interfaceProList.length > 0 ){
      interfaceProList.map(data =>{
        antoView.push(<div key={data.uuid} className='table-card'>
          <Card title={data.name} extra={<a onClick={()=>this.delBtn(data.uuid)} ><Icon type='close' className='basic-info-add' /></a>} style={{ width: 280,height: 170 }}>
            <a style={{ textDecoration: 'none' }}>
              <p>分&emsp;&emsp;类：{data.type === '1' ? '变量' : data.type === '2' ? '常量' : data.type === '3' ? '标签' : ''}</p>
              <p>数据类型：{data.dataType === '1' ? '整型' : data.dataType === '2' ? '浮点型' : data.dataType === '3' ? '布尔型' : data.dataType === '4' ? '枚举' : data.dataType === '5' ? '字符串' : data.dataType === '6' ? '密码' : ''}</p>
            </a>
          </Card>
        </div>);
      });
    }
    return antoView;
  }

  //回调新增属性方法
  addIntfcArrt = (attr) =>{
    let attrs = this.state.interfaceProList;
    this.setState({ interfaceProList: [ ...attrs,attr ] });
    this.autoProView();
  }

  render() {
    let { itemInfo } = this.state;
    let { name,type,desc } = itemInfo;
    const { communityDatas } = this.props;
    const { getFieldProps } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 10 },
      wrapperCol: { span: 4 }
    };
    const nameProps = getFieldProps('name', {
      initialValue: name,
      rules: [
        { required: true, message: '名称不能为空！' },
        { validator: noSpaceLengthValidate(50,true,'名称不能为空！') }
      ]
    });
    const typeProps = getFieldProps('type', {
      initialValue: type,
      rules: [
        { required: true, message: '通讯方式不能为空！' }
      ]
    });
    const descProps = getFieldProps('desc', {
      initialValue: desc,
      rules: [
        { validator: noSpaceLengthValidate(maxDescLength,false,null) }
      ]
    });
    return (
      <div className='table-container'>
        <Collapse activeKey={this.state.activeKey} accordion>
          <Panel header="新建设备接口" key="1" showArrow={false} >
            <div style={{ textAlign: 'center' }} >
              <Form onSubmit={this.onClickDown} >
                <Row>
                  <Col span={24}>
                    <FormItem hasFeedback label='名称' {...formItemLayout} >
                      <Input className='amos-grid-form-input'  {...nameProps} placeholder="请输入名称" />
                    </FormItem>
                  </Col>
                </Row>
                <Row>
                  <Col span={24}>
                    <FormItem hasFeedback label='通讯方式' {...formItemLayout} >
                      <Select {...typeProps}
                        style={{ width: '100%',textAlign: 'left',height: '32px' }}
                        dropdownStyle={{ width: '260px',maxHeight: '240px' }}
                        placeholder="请选择通讯方式"
                        className='interface-add-select'
                      >
                        {
                          communityDatas.map(comm => {
                            return (<Option key={`${comm.id}Option`} value={`${comm.id}`}>{comm.name}</Option>);
                          })
                        }
                      </Select>
                    </FormItem>
                  </Col>
                </Row>
                <Row>
                  <Col span={24}>
                    <FormItem label='描述' {...formItemLayout} >
                      <Input className='amos-grid-form-input' {...descProps} placeholder="请输入描述" />
                    </FormItem>
                  </Col>
                </Row>
                <Row>
                  <Button  onClick={this.onClickDown} >下一步</Button>
                </Row>
              </Form>
            </div>
          </Panel>
          <Panel header="新建设备接口参数" key="2" showArrow={false} >
            <Row>
              {
                  this.autoProView()
                }
            </Row>
            <div style={{ height: '3rem' }} />
            <Row  type='flex' justify='center' >
              <Button  onClick={this.onClickUp} >上一步</Button>
              <div style={{ width: '1.5rem' }} />
              <Button  onClick={this.onClick} disabled={this.state.waiting} >确定</Button>
            </Row>
          </Panel>
        </Collapse>
      </div>
    );
  }
}

AddInterface.propTypes = {
  form: PropTypes.any,
  updateAddView: PropTypes.func,
  communityDatas: PropTypes.array
};

export default createForm(AddInterface);
