import React, { Component } from 'react';
import { Button,Form,Collapse,Input,Row,Col,Radio,Modal,Icon } from 'amos-antd';
import PropTypes from 'prop-types';
import { AmosFetch } from '../../utils/processor';
import OltSerUrl from '../../consts/urlConsts';
import { message } from 'amos-framework';
import { trim } from 'amos-tool';
import ProtocolTestView from './protocolTestView';
import {objOfStrPropTrim,noSpaceLengthValidate} from './../common/utils/validate';

const createForm = Form.create();
const FormItem = Form.Item;
const Panel = Collapse.Panel;
const RadioGroup = Radio.Group;
const { TextArea } = Input;
const maxDescLength = 250;



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

  componentDidMount(){
    //查询脚本语言枚举类型
    AmosFetch.get(OltSerUrl.scriptLangType).then(res => {
      if (res.ok) {
        return res.json();
      }
      else
      {
        throw new Error('从服务端获取数据失败！');
      }
    }).then((data)=>{
      if (data.result === 'SUCCESS'){
        let scriptLangDatas = [];
        data ? data.dataList.map(e=>{
          if (e.name === 'Groovy'){
            scriptLangDatas.push({ value: e.id,label: e.name });
          } else {
            scriptLangDatas.push({ value: e.id,label: e.name, disabled: true });
          }

        }) : [];
        this.setState({ scriptLangData: scriptLangDatas });
      }
    });
  }

  onChange = (e) => {
    console.log('radio checked', e.target.value);
    this.setState({
      radiovalue: e.target.value
    });
  }

  //下一步
  onClickDown = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        values = objOfStrPropTrim(values);
        this.setState({
          itemInfo: values,
          activeKey: '2',
          btnVisible: false //测试关闭按钮开关
        });
      }
    });
  }

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

  //确定提交事件，向后台发送创建数据方法
  onClick = () => {
    let saveUrl = OltSerUrl.protocolSave;
    let protocolData = this.state.itemInfo;
    protocolData.dicIdScriptLang = this.state.radiovalue;
    const { getFieldValue } = this.props.form;
    let scriptCode = trim(getFieldValue('scriptCode'));
    if (!scriptCode || scriptCode === '' ){
      Modal.info({
        title: '提示',
        content: '代码不能为空！',
        okText: '确定'
      });
      return;
    }else{
      this.setState({waiting: true});
    }
    protocolData.scriptCode = scriptCode;
    AmosFetch.post(saveUrl,{ data: protocolData }).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 = () => {
    Modal.confirm({
      title: '删除',
      content: '是否删除所选信息？',
      okText: '确定',
      cancelText: '取消',
      onOk() {},
      onCancel() {}
    });
  };

  testBtnFuncOpen = () =>{
    this.setState({
      btnVisible: true
    });
  }

  testBtnFuncClose = () =>{
    this.setState({
      btnVisible: false
    });
  }

  render() {
    let { itemInfo,btnVisible,scriptLangData } = this.state;
    let { name,version,descr,scriptCode } = itemInfo;
    const { getFieldProps } = this.props.form;
    const formItemLayoutUp = {
      labelCol: { span: 10 },
      wrapperCol: { span: 4 }
    };
    const formItemLayoutDown = {
      labelCol: { span: 7 },
      wrapperCol: { span: 10 }
    };
    const nameProps = getFieldProps('name', {
      initialValue: name,
      rules: [
        { required: true, message: '名称不能为空！'},
        {validator:noSpaceLengthValidate(50,true,'名称不能为空！')}
      ]
    });

    const versionProps = getFieldProps('version', {
      initialValue: version,
      rules: [
        { required: true, message: '版本不能为空！' },
        {
          validator:noSpaceLengthValidate(20,true,'版本不能为空！')
        }
      ]
    });
    const descProps = getFieldProps('descr', {
      initialValue: descr,
      rules: [
        { validator: noSpaceLengthValidate(maxDescLength,false,null) }
      ]
    });
    const codeProps = getFieldProps('scriptCode', {
      initialValue: scriptCode
    });
    return (
      <div className='table-container'>
        <Collapse activeKey={this.state.activeKey} accordion>
          <Panel header="新建协议" key="1" showArrow={false} >
            <div style={{ textAlign: 'center' }} >
              <Row>
                <Col span={24}>
                  <FormItem hasFeedback label='名称' {...formItemLayoutUp} >
                    <Input className='amos-grid-form-input' {...nameProps} placeholder="请输入名称" />
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={24}>
                  <FormItem hasFeedback label='版本' {...formItemLayoutUp} >
                    <Input className='amos-grid-form-input' {...versionProps} placeholder="请输入版本" />
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={24}>
                  <FormItem label='描述' {...formItemLayoutUp} >
                    <Input className='amos-grid-form-input' {...descProps} placeholder="请输入描述" />
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Button  onClick={this.onClickDown} >下一步</Button>
              </Row>
            </div>
          </Panel>
          <Panel header="新建脚本信息" key="2" showArrow={false} >
            <div style={{ textAlign: 'center' }} >
              <Row>
                <Col span={24}>
                  <FormItem hasFeedback label='实现方式' {...formItemLayoutDown} wrapperCol={{ span: 5, offset: 0 }} >
                    <RadioGroup options={scriptLangData} onChange={this.onChange} value={this.state.radiovalue} />
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={24}>
                  <FormItem hasFeedback label='代码' {...formItemLayoutDown} >
                    <TextArea {...codeProps} autosize={{ minRows: 8, maxRows: 20 }} />
                  </FormItem>
                </Col>
              </Row>
              {
                //该功能暂时屏蔽掉，待后期需要打开即可
                // <Row>
                //   <Col span={24}>
                //     <FormItem hasFeedback label='协议基本测试' {...formItemLayoutDown} >
                //       <div style={{ float: 'left',  marginLeft: '3rem' }}>
                //         <a onClick={this.testBtnFuncOpen}><Icon type='plus-square-o' style={{ fontSize: 25, color: '#08c' }} /></a>
                //       </div>
                //       {
                //         btnVisible ?
                //           <div style={{ float: 'left',  marginLeft: '3rem' }}>
                //             <a onClick={this.testBtnFuncClose}><Icon type='close-square-o' style={{ fontSize: 25, color: '#08c' }} /></a>
                //           </div> :
                //           null
                //       }
                //     </FormItem>
                //   </Col>
                // </Row>
                // {
                //   btnVisible ?
                //     <ProtocolTestView /> :
                //     null
                // }
              }

            </div>
            <div style={{ height: '2rem' }} />
            <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>
    );
  }
}

AddProtocol.propTypes = {
  form: PropTypes.any,
  updateAddView: PropTypes.func
};

export default createForm(AddProtocol);
