import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Form,Input,Radio,Modal,Button,InputNumber,Row,Col,Checkbox } from 'amos-antd';
import { Select } from 'amos-framework';
import { UUID, trim } from 'amos-tool';
import { isInt,isNum } from 'ray-validate';
import { dataTypeEnum,classifyEnum } from  './../common/InterfaceEnum';
import { enums2array } from './../common/InterfaceLang';
import { AmosFetch, formatUrl } from '../../../utils/processor';
import { OltSerUrl } from '../../../consts/urlConsts';
import { message } from 'amos-framework';
import {objOfStrPropTrim,noSpaceLengthValidate} from './../../common/utils/validate';

const RadioGroup = Radio.Group;
const Option = Select.Option;
const FormItem = Form.Item;
const dataTypeOption = enums2array(dataTypeEnum).map((item)=>
  <Option key={item.key} value={`${item.key}`}>{item.label}</Option>) ;
const classifyOption = enums2array(classifyEnum).map((item)=>
  <Radio key={item.key} value={`${item.key}`}>{item.label}</Radio>) ;
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 5 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 }
  }
};
const fieldNames = [ 'name','type','displayName','dataType','unit','descr', 'isRequired' ];
/**
 *
 * 新增/编辑接口属性
 * @class AddEditInterfaceProperty
 * @extends {Component}
 */
class AddEditInterfaceProperty extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentenumRange: undefined,
      isEdited: false
    };
  }

  componentDidMount(){

  }

  onEnumRangeChange = (e) => {
    this.setState({ currentenumRange: e.target.value });
  }

  /**
   * 根据类型获取当前显示的FormItem集合
   *
   * @memberof AddEditInterfaceProperty
   */
  getDynamicCode = () => {
    let { getFieldProps,getFieldValue } = this.props.form;
    let { valueStr,enumRange,minValue,maxValue,precision } = this.props.propertyInfo;
    let currentenumRange = this.state.currentenumRange === undefined ? (enumRange === null ? '' :enumRange) : this.state.currentenumRange;
    let value = getFieldValue('dataType');//数据类型
    let type = getFieldValue('type');//分类：变量、常量、标签
    //常量时的指定值Int
    const appointedIntProps = getFieldProps('defaultAppointedInt', {
      initialValue: valueStr ? parseInt(valueStr) : '',
      rules: [
          { required: true, message: '常量值不能为空！' },
          { validator: this.checkInt }
      ]
    });
    //常量时的指定值float
    const appointedFloatProps = getFieldProps('defaultAppointedFloat', {
      initialValue: valueStr ? parseFloat(valueStr) : '',
      rules: [
          { required: true, message: '常量值不能为空！' },
          { validator: this.checkFloat }
      ]
    });
    //常量时的指定值string
    const appointedStringProps = getFieldProps('defaultAppointedString', {
      initialValue: valueStr ? valueStr : '',
      rules: [
          { required: true,min: 0,max: 255, message: '最大长度255！' }
      ]
    });
    //常量时的指定值boolean
    const appointedBooleanProps = getFieldProps('defaultAppointedBoolean', {
      initialValue: valueStr,
      rules: [
          { required: true, message: '常量值不能为空！' }
      ]
    });
    //常量时的指定值pwd
    const appointedPwdProps = getFieldProps('defaultAppointedPwd', {
      initialValue: valueStr ? valueStr : '',
      rules: [
          { required: true,min: 0,max: 255, message: '最大长度255！' }
      ]
    });
    //枚举范围
    const enumRangeProps = getFieldProps('enumRange', {
      initialValue: currentenumRange,
      rules: [
          { required: true, message: '枚举范围不能为空！' },
          { validator: noSpaceLengthValidate(null,true,'枚举范围不能为空！') }
      ]
    });
    //默认值int
    const defaultIntProps = getFieldProps('defaultIntValue', {
      initialValue: valueStr ,
      rules: [
          { required: false, message: '默认值不能为空！' },
          { validator: this.checkInt }
      ]
    });
    //最小值int
    const minIntValueProps = getFieldProps('minIntValue', {
      initialValue: minValue,
      rules: [
          //{ required: true, message: '最小值不能为空！' },
          { validator: this.checkInt }
      ]
    });
    //最大值int
    const maxIntValueProps = getFieldProps('maxIntValue', {
      initialValue: maxValue,
      rules: [
          //{ required: true, message: '最大值不能为空！' },
          { validator: this.checkInt }
      ]
    });
    //默认值float
    const defaultFloatProps = getFieldProps('defaultFloatValue', {
      initialValue: valueStr ? parseFloat(valueStr) : '',
      rules: [
          { required: false, message: '默认值不能为空！' },
          { validator: this.checkFloatExcludeNull }
      ]
    });
    //最小值float
    const minFloatValueProps = getFieldProps('minFloatValue', {
      initialValue: minValue,
      rules: [
          //{ required: true, message: '最小值不能为空！' },
          { validator: this.checkFloat }
      ]
    });
    //最大值float
    const maxFloatValueProps = getFieldProps('maxFloatValue', {
      initialValue: maxValue,
      rules: [
          //{ required: true, message: '最大值不能为空！' },
          { validator: this.checkFloat }
      ]
    });
    //默认值枚举
    const defaultEnumProps = getFieldProps('defaultEnumValue', {
      initialValue: valueStr ? valueStr : '',
      rules: [
          { required: false, message: '默认值不能为空！' }
      ]
    });
    //默认值string
    const defaultStringProps = getFieldProps('defaultStringValue', {
      initialValue: valueStr ? valueStr : '',
      rules: [
          { required: false,min: 0,max: 255, message: '最大长度255！' }
      ]
    });
    //默认值pwd
    const defaultPwdProps = getFieldProps('defaultPwdValue', {
      initialValue: valueStr ? valueStr : '',
      rules: [
          { required: false,min: 0,max: 255, message: '最大长度255！' }
      ]
    });
    //布尔型默认值
    const defaultBooleanProps = getFieldProps('defaultBoolean', {
      initialValue: valueStr,
      rules: [
          { required: false, message: '默认值不能为空！' }
      ]
    });
    //精度
    const precisionProps = getFieldProps('precision', {
      initialValue: precision === undefined ? 2 : precision,
      rules: [
          //{ required: true, message: '精度不能为空！' }
      ]
    });
    let htmlArray = [];
    if (value === '1') {//int
      if (type === '1') {
        htmlArray.push(<FormItem {...formItemLayout} hasFeedback label='最小值: '  >
          <Input {...minIntValueProps} placeholder='最小值' />
        </FormItem>);
        htmlArray.push(<FormItem {...formItemLayout} hasFeedback label='最大值: '  >
          <Input {...maxIntValueProps} placeholder='最大值' />
        </FormItem>);
        htmlArray.push(<FormItem {...formItemLayout} hasFeedback label='默认值: '  >
          <Input {...defaultIntProps} placeholder='默认值' />
        </FormItem>);
      } else if (type === '2')
      {
        htmlArray.push(<FormItem {...formItemLayout} hasFeedback label='数值: '  >
          <Input {...appointedIntProps} placeholder='(数值)最多支持32位整型数据' />
        </FormItem>);
      }
    } else if (value === '3')//boolean
    {
      if (type === '1') {
        htmlArray.push(<FormItem {...formItemLayout} hasFeedback label='默认值: '  >
          <RadioGroup {...defaultBooleanProps}>
            <Radio key='1' value='1'>{'true'}</Radio>
            <Radio key='0' value='0'>{'false'}</Radio>
          </RadioGroup>
        </FormItem>);
      } else if (type === '2')
      {
        htmlArray.push(<FormItem {...formItemLayout} hasFeedback label='值: '  >
          <RadioGroup {...appointedBooleanProps}>
            <Radio key='1' value='1'>{'true'}</Radio>
            <Radio key='0' value='0'>{'false'}</Radio>
          </RadioGroup>
        </FormItem>);
      }
    } else if (value === '4')//enum
    {
      if (type === '1') {
        htmlArray.push(<FormItem {...formItemLayout} hasFeedback label='枚举范围: '  >
          <Input
            {...enumRangeProps}
            placeholder='由中文英文及字符组成，字符之间以一个半角逗号作为间隔'
            onChange={this.onEnumRangeChange}
          />
        </FormItem>);
        let enumList = currentenumRange.split(',');
        let enumOption = [];
        for (var index = 0; index < enumList.length; index++) {
          let enumValue = enumList[index];
          if (enumValue === '') {
            continue;
          }
          enumOption.push( <Option key={index} value={`${enumValue}`}>{enumValue}</Option>);
        }
        htmlArray.push(<FormItem {...formItemLayout} hasFeedback label='默认值: '  >
          <Select style={{ width: '100%',height: '32px' }}
            {...defaultEnumProps}
            placeholder='请先输入枚举范围'
          >
            {enumOption}
          </Select>
        </FormItem>);
      } else if (type === '2')
      {
        htmlArray.push(<FormItem {...formItemLayout} hasFeedback label='枚举范围: '  >
          <Input {...enumRangeProps} placeholder='由中文英文及字符组成，字符之间以一个半角逗号作为间隔' />
        </FormItem>);
      }
    } else if (value === '5')//string
    {
      if (type === '1') {
        htmlArray.push(<FormItem {...formItemLayout} hasFeedback label='默认值: '  >
          <Input {...defaultStringProps} placeholder='默认值' />
        </FormItem>);
      } else if (type === '2')
      {
        htmlArray.push(<FormItem {...formItemLayout} hasFeedback label='默认值: '  >
          <Input {...appointedStringProps} placeholder='默认值' />
        </FormItem>);
      }
    } else if (value === '6')//password
    {
      if (type === '1') {
        htmlArray.push(<FormItem {...formItemLayout} hasFeedback label='默认值: '  >
          <Input {...defaultPwdProps} type='password' placeholder='默认值' />
        </FormItem>);
      } else if (type === '2')
      {
        htmlArray.push(<FormItem {...formItemLayout} hasFeedback label='默认值: '  >
          <Input {...appointedPwdProps} type='password' placeholder='默认值' />
        </FormItem>);
      }
    } else if (value === '2')//float
    {
      if (type === '1') {
        htmlArray.push(<FormItem {...formItemLayout} hasFeedback label='精度: '  >
          <label>小数点后</label><InputNumber min={0} max={32} defaultValue={0} {...precisionProps} /><label>位</label>
        </FormItem>);
        htmlArray.push(<FormItem {...formItemLayout} hasFeedback label='最小值: '  >
          <Input {...minFloatValueProps} placeholder='最小值' />
        </FormItem>);
        htmlArray.push(<FormItem {...formItemLayout} hasFeedback label='最大值: '  >
          <Input {...maxFloatValueProps} placeholder='最大值' />
        </FormItem>);
        htmlArray.push(<FormItem {...formItemLayout} hasFeedback label='默认值: '  >
          <Input {...defaultFloatProps} placeholder='默认值' />
        </FormItem>);
      } else if (type === '2')
      {
        htmlArray.push(<FormItem {...formItemLayout} hasFeedback label='数值: '  >
          <Input {...appointedFloatProps} placeholder='(数值)最多支持小数点前后32位浮点型数据' />
        </FormItem>);
      }
    }
    return htmlArray;
  }

  /**
   *
   * 根据类型获取当前显示的name集合
   * @memberof AddEditInterfaceProperty
   */
  getDynamicCodeName = () => {
    let { getFieldValue } = this.props.form;
    let value = getFieldValue('dataType');
    let type = getFieldValue('type');//分类：变量、常量、标签
    let nameArray = [];
    if (value === '1') {
      if (type === '1') {
        nameArray.push('minIntValue');
        nameArray.push('maxIntValue');
        nameArray.push('defaultIntValue');
      } else if (type === '2')
      {
        nameArray.push('defaultAppointedInt');
      }
    } else if (value === '3')
    {
      if (type === '1') {
        nameArray.push('defaultBoolean');
      } else if (type === '2')
      {
        nameArray.push('defaultAppointedBoolean');
      }
    } else if (value === '4')
    {
      if (type === '1') {
        nameArray.push('enumRange');
        nameArray.push('defaultEnumValue');
      } else if (type === '2')
      {
        nameArray.push('enumRange');
      }
    } else if (value === '5')
    {
      if (type === '1') {
        nameArray.push('defaultStringValue');
      } else if (type === '2')
      {
        nameArray.push('defaultAppointedString');
      }
    } else if (value === '6')
    {
      if (type === '1') {
        nameArray.push('defaultPwdValue');
      } else if (type === '2')
      {
        nameArray.push('defaultAppointedPwd');
      }
    } else if (value === '2')
    {
      if (type === '1') {
        nameArray.push('precision');
        nameArray.push('minFloatValue');
        nameArray.push('maxFloatValue');
        nameArray.push('defaultFloatValue');
      } else if (type === '2')
      {
        nameArray.push('defaultAppointedFloat');
      }
    }
    return nameArray;
  }

   /**
   * 保存按钮事件
   */
  handleSubmit = (e) => {
    e.preventDefault();
    let currentfieldNames = [ ...fieldNames,...this.getDynamicCodeName() ];
    let options = {  };
    this.props.form.validateFields(currentfieldNames,options,(errors, values) => {
      if (errors) {
        return;
      }
      values = objOfStrPropTrim(values);
      this.handleSave(values);
    });
  }

  handleSave = (obj) => {
    console.log(obj);
    let minValue = 0;
    let maxValue = 0;
    let valueStr = '';
    let enumRange = '';
    let precision = 0;
    let isRequired = false;
    for (var key in obj) {
      if (obj.hasOwnProperty(key) && key.startsWith('min')) {
        minValue = obj[key];
      } else if (obj.hasOwnProperty(key) && key.startsWith('max')) {
        maxValue = obj[key];
      } else if (obj.hasOwnProperty(key) && key.startsWith('default')) {
        valueStr = `${obj[key]  }`;
      } else if (obj.hasOwnProperty(key) && key === 'enumRange') {
        enumRange = obj[key];
      } else if (obj.hasOwnProperty(key) && key === 'precision') {
        precision = obj[key];
      }
    }
    if (this.props.addIntfcArrt) {//接口新增页面添加属性
      obj.uuid = UUID.uuid(8,2);
      obj.minValue = minValue;
      obj.maxValue = maxValue;
      obj.valueStr = valueStr;
      obj.enumRange = enumRange;
      obj.precision = precision;
      this.props.addIntfcArrt(obj);
      message.success('成功！');
    } else {//接口详情页面添加/编辑属性
      obj.minValue = minValue;
      obj.maxValue = maxValue;
      obj.valueStr = valueStr;
      obj.enumRange = enumRange;
      obj.precision = precision;
      this.saveIntfcAttr(obj);
    }

    this.props.form.resetFields();
    this.props.callBack();
  }

  saveIntfcAttr = (obj) => {
    let { intfcId, propertyInfo } = this.props;
    let id = intfcId || propertyInfo.intfcId;
    if (propertyInfo && propertyInfo.id){
      obj.id = propertyInfo.id;
    }
    AmosFetch.post(formatUrl(OltSerUrl.intfcAttrSave,{ id }),{ data: obj })
    .then(res => {
      if (res.ok) {
        return res.json();
      }
      else
      {
        throw new Error('从服务端获取数据失败！');
      }
    }).then((data)=>{
      if (data.result === 'SUCCESS'){
        message.success('操作成功！');
        this.props.requestIntfcAttrs();
      } else {
        message.danger('操作失败！');
      }
    });
  }


  handleCancel = (obj) => {
    this.props.form.resetFields();
    this.props.callBack();
  }

  /**
   *
   * 整型验证
   * @memberof AddEditInterfaceProperty
   */
  checkInt = (rule, value, callback) => {
    value = trim(value);
    if (value === '' || value === undefined || value === null){
      callback();
    } else if (isInt(parseInt(value))) {
      let length = value.toString().length;
      if (length > 0 && length < 33) {
        callback();
      } else {
        callback('最多支持32位整型数据');
      }
    } else {
      callback('最多支持32位整型数据');
    }
  }

  /**
   *
   * 浮点数验证
   * @memberof AddEditInterfaceProperty
   */
  checkFloat = (rule, value, callback) => {
    value = trim(value);
    if (value === '' || value === undefined || value === null){
      callback();
    } else if (isNum(parseInt(value))) {
      let length = value.toString().length;
      if (length > 0 && length < 33) {
        callback();
      } else {
        callback('最多支持小数点前后32位浮点型数据');
      }
    } else {
      callback('最多支持小数点前后32位浮点型数据');
    }
  }

  /**
   *
   * 浮点数验证(允许为空)
   * @memberof AddEditInterfaceProperty
   */
  checkFloatExcludeNull = (rule, value, callback) => {
    value = trim(value);
    if (value === '' || value === undefined || value === null)
    {
      callback();
    } else if (isNum(parseInt(value))) {
      let length = value.toString().length;
      if (length > 0 && length < 33) {
        callback();
      } else {
        callback('最多支持小数点前后32位浮点型数据');
      }
    } else {
      callback('最多支持小数点前后32位浮点型数据');
    }
  }

  render() {
    let { form,propertyInfo } = this.props;
    let { getFieldProps } = form;
    //属性名
    const propertyNameProps = getFieldProps('name', {
      initialValue: propertyInfo ? propertyInfo.name : propertyInfo,
      rules: [
          { required: true,min: 1,max: 20, message: '支持1-20位非空格字符！' },
          { validator: noSpaceLengthValidate(20,true,'属性名不能为空！') }
      ]
    });
    //分类
    const classifyProps = getFieldProps('type', {
      initialValue: propertyInfo && propertyInfo.type ? `${propertyInfo.type}` : '1',
      rules: [
          { required: true, message: '分类不能为空！' }
      ]
    });
    //显示名称
    const displayNameProps = getFieldProps('displayName', {
      initialValue: propertyInfo ? propertyInfo.displayName : propertyInfo,
      rules: [
          { required: true,min: 1,max: 20, message: '支持1-20位非空格字符！' },
          { validator: noSpaceLengthValidate(20,true,'显示名称不能为空！') }
      ]
    });
    //数据类型
    const typeProps = getFieldProps('dataType', {
      initialValue: propertyInfo ? `${propertyInfo.dataType}` : propertyInfo,
      rules: [
          { required: true, message: '数据类型不能为空！' }
      ]
    });
    //单位
    const unitProps = getFieldProps('unit', {
      initialValue: propertyInfo ? propertyInfo.unit : propertyInfo,
      rules: [
          { required: false,min: 1,max: 20, message: '支持1-20位非空格字符！' }
      ]
    });
    //描述
    const descriptionProps = getFieldProps('descr', {
      initialValue: propertyInfo ? propertyInfo.descr : propertyInfo,
      rules: [

      ]
    });
    //是否必填
    const disRequiredProps = getFieldProps('isRequired', {
      initialValue: propertyInfo ?propertyInfo.isRequired : false,
      valuePropName: 'checked', 
      rules: [

      ]
    });
    return (
      <div className='interface-property-add-modal'>
        <Form horizontal onSubmit={this.handleSubmit}>
          <FormItem {...formItemLayout} hasFeedback label='属性名: '>
            <Input {...propertyNameProps} placeholder='属性名（支持1-20位非空格字符）' />
          </FormItem>
          <FormItem {...formItemLayout} hasFeedback label='分类: '  >
            <RadioGroup {...classifyProps}>
              {classifyOption}
            </RadioGroup>
          </FormItem>
          <FormItem {...formItemLayout} hasFeedback label='显示名称: '  >
            <Input {...displayNameProps} placeholder='属性名（支持1-20位非空格字符）' />
          </FormItem>
          <FormItem {...formItemLayout} hasFeedback label='数据类型：'  >
            <Select style={{ width: '100%',height: '32px' }}
              {...typeProps}
            >
              {dataTypeOption}
            </Select>
          </FormItem>
          <div>
            {this.getDynamicCode()}
          </div>
          <FormItem {...formItemLayout} hasFeedback label='单位: '  >
            <Input {...unitProps} placeholder='单位（支持1-20位非空格字符）' />
          </FormItem>
          <FormItem {...formItemLayout} hasFeedback label='描述: '  >
            <Input {...descriptionProps}  />
          </FormItem>
          <FormItem {...formItemLayout} hasFeedback label='是否必填: '  >
            <Checkbox
              {...disRequiredProps}
              style={{ 'line-height': '31px',float: 'left','margin-left': '7px' }}
            />
          </FormItem>
          <FormItem wrapperCol={{
            xs: { span: 24, offset: 0 },
            sm: { span: 24, offset: 0 }
          }}
          >
            <Row>
              <Col span={3} offset={14}>
                <Button type="primary" htmlType="submit">提交</Button>
              </Col>
              <Col span={3} offset={1}>
                <Button onClick={this.handleCancel}>取消</Button>
              </Col>
            </Row>
          </FormItem>
        </Form>
      </div>
    );
  }
}

AddEditInterfaceProperty.propTypes = {
  form: PropTypes.any,
  callBack: PropTypes.func,
  propertyInfo: PropTypes.any
};

AddEditInterfaceProperty.defaultProps = {
  propertyInfo: { type: 1,dataType: 1,enumRange: '' }
};

export default AddEditInterfaceProperty;
