import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Form, Button, Row, Col, Radio, Input, InputNumber, Modal, Checkbox } from 'amos-antd';
import { Select } from 'amos-framework';
import { isInt, isNum } from 'ray-validate';
import { AmosFetch } from '../../../../utils/processor';
import { OltSerUrl } from '../../../../consts/urlConsts';
import { message } from 'amos-framework';
import { dataTypeEnum, capacatyclassifyEnum } from './../../common/DeviceEnum';
import { enums2array } from './../../common/DeviceLang';

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(capacatyclassifyEnum).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 AddEditCapacityProperty
 * @extends {Component}
 */
class AddEditCapacityProperty extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentenumRange: undefined
    };
  }

  componentDidMount() {}

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

  /**
   * 根据类型获取当前显示的FormItem集合
   *
   * @memberof AddEditInterfaceProperty
   */
  getDynamicCode = () => {
    let { valueStr, enumRange, minValue, maxValue, precision } = this.props.propertyInfo;
    let currentenumRange = this.state.currentenumRange === undefined ? (enumRange === null ? '' : enumRange) : this.state.currentenumRange;
    let { getFieldProps, getFieldValue } = this.props.form;
    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: '枚举范围不能为空！' }]
    });
    //默认值int
    const defaultIntProps = getFieldProps('defaultIntValue', {
      initialValue: valueStr ? parseInt(valueStr) : '',
      rules: [{ required: false, message: '默认值不能为空！' }, { validator: this.checkIntExcludeNull }]
    });
    //最小值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', {
      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: '精度不能为空！' }
      ]
    });
    //输出时最小值int
    const minIntOutputProps = getFieldProps('minIntOutput', {
      initialValue: minValue,
      rules: [
        //{ required: false, message: '最小值不能为空！' },
        { validator: this.checkIntExcludeNull }
      ]
    });
    //输出时最大值int
    const maxIntOutputProps = getFieldProps('maxIntOutput', {
      initialValue: maxValue,
      rules: [
        //{ required: false, message: '最大值不能为空！' },
        { validator: this.checkIntExcludeNull }
      ]
    });
    //输出时精度
    const precisionOutputProps = getFieldProps('precisionOutput', {
      initialValue: precision === undefined ? 2 : precision,
      rules: [
        //{ required: false, message: '精度不能为空！' }
      ]
    });
    //输出时最小值float
    const minFloatOutputProps = getFieldProps('minFloatOutput', {
      initialValue: minValue,
      rules: [
        //{ required: false, message: '最小值不能为空！' },
        { validator: this.checkFloatExcludeNull }
      ]
    });
    //输出时最大值float
    const maxFloatOutputProps = getFieldProps('maxFloatOutput', {
      initialValue: maxValue,
      rules: [
        //{ required: false, message: '最大值不能为空！' },
        { validator: this.checkFloatExcludeNull }
      ]
    });
    //输出时枚举范围
    const enumRangeOutputProps = getFieldProps('enumRangeOutput', {
      initialValue: currentenumRange,
      rules: [{ required: false, message: '枚举范围不能为空！' }]
    });
    let htmlArray = [];
    if (value === '1') {
      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 (type === '4') {
        htmlArray.push(
          <FormItem {...formItemLayout} hasFeedback label="最小值: ">
            <Input {...minIntOutputProps} placeholder="最小值" />
          </FormItem>
        );
        htmlArray.push(
          <FormItem {...formItemLayout} hasFeedback label="最大值: ">
            <Input {...maxIntOutputProps} placeholder="最大值" />
          </FormItem>
        );
      }
    } else if (value === '3') {
      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 (type === '3') {
        //无
      }
    } else if (value === '4') {
      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 (type === '4') {
        htmlArray.push(
          <FormItem {...formItemLayout} hasFeedback label="枚举范围: ">
            <Input {...enumRangeOutputProps} placeholder="由中文英文及字符组成，字符之间以一个半角逗号作为间隔" />
          </FormItem>
        );
      }
    } else if (value === '5') {
      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 (type === '4') {
        //无
      }
    } else if (value === '6') {
      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 (type === '4') {
        //无
      }
    } else if (value === '2') {
      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>
        );
      } else if (type === '4') {
        htmlArray.push(
          <FormItem {...formItemLayout} hasFeedback label="精度: ">
            <label>小数点后</label>
            <InputNumber min={0} max={32} defaultValue={0} {...precisionOutputProps} />
            <label>位</label>
          </FormItem>
        );
        htmlArray.push(
          <FormItem {...formItemLayout} hasFeedback label="最小值: ">
            <Input {...minFloatOutputProps} placeholder="最小值" />
          </FormItem>
        );
        htmlArray.push(
          <FormItem {...formItemLayout} hasFeedback label="最大值: ">
            <Input {...maxFloatOutputProps} placeholder="最大值" />
          </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 (type === '4') {
        nameArray.push('minIntOutput');
        nameArray.push('maxIntOutput');
      }
    } else if (value === '3') {
      if (type === '1') {
        nameArray.push('defaultBoolean');
      } else if (type === '2') {
        nameArray.push('defaultAppointedBoolean');
      } else if (type === '4') {
        //无
      }
    } else if (value === '4') {
      if (type === '1') {
        nameArray.push('enumRange');
        nameArray.push('defaultEnumValue');
      } else if (type === '2') {
        nameArray.push('enumRange');
      } else if (type === '4') {
        nameArray.push('enumRangeOutput');
      }
    } else if (value === '5') {
      if (type === '1') {
        nameArray.push('defaultStringValue');
      } else if (type === '2') {
        nameArray.push('defaultAppointedString');
      } else if (type === '4') {
        //无
      }
    } else if (value === '6') {
      if (type === '1') {
        nameArray.push('defaultPwdValue');
      } else if (type === '2') {
        nameArray.push('defaultAppointedPwd');
      } else if (type === '4') {
        //无
      }
    } 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');
      } else if (type === '4') {
        nameArray.push('precisionOutput');
        nameArray.push('minFloatOutput');
        nameArray.push('maxFloatOutput');
      }
    }
    return nameArray;
  };

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

  handleSave = obj => {
    let propertyInfo = this.props.propertyInfo;
    let minValue = 0;
    let maxValue = 0;
    let valueStr = '';
    let enumRange = '';
    let precision = 0;
    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 = String(obj[key]);
      } else if (obj.hasOwnProperty(key) && key.startsWith('enumRange')) {
        enumRange = obj[key];
      } else if (obj.hasOwnProperty(key) && key.startsWith('precision')) {
        precision = obj[key];
      }
    }
    let keyvalue = new Date().getTime();
    valueStr = valueStr === null ? '' : valueStr;
    Object.assign(obj, { minValue, maxValue, valueStr, enumRange, precision, key: keyvalue });
    let interfaceProList = [
      {
        key: keyvalue,
        name: obj.name,
        type: obj.type,
        dataType: obj.dataType
      }
    ];
    let { deviceId } = this.props;
    if (deviceId === undefined) {
      //更新capacity对象，进而device对象
      this.props.addCapacityProperty(obj);
      //更新card
      this.props.autoCardCalculate(interfaceProList);
      this.props.form.resetFields();
      this.props.callBack();
    } else {
      if (propertyInfo.id) {
        obj.id = propertyInfo.id;
      }
      //保存到数据库
      this.saveCapacityProperty(obj);
    }
  };

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

  /**
   *
   * 整型验证
   * @memberof AddEditInterfaceProperty
   */
  checkInt = (rule, value, callback) => {
    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) => {
    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
   */
  checkIntExcludeNull = (rule, value, callback) => {
    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
   */
  checkFloatExcludeNull = (rule, value, callback) => {
    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 AddEditCapacityProperty
   */
  saveCapacityProperty = obj => {
    let { deviceId } = this.props;
    Object.assign(obj, { cpblId: this.props.capacityId });
    AmosFetch.post(OltSerUrl.capacityPropertyUpdate, { data: obj })
      .then(res => {
        if (res.ok) {
          return res.json();
        } else {
          throw new Error('从服务端获取数据失败！');
        }
      })
      .then(data => {
        if (data.result === 'SUCCESS') {
          message.success('新增属性成功！');
        } else {
          message.danger('新增属性失败！');
        }
        //更新card
        this.props.getDeviceInfoById(deviceId);
        this.props.form.resetFields();
        this.props.callBack();
      });
  };

  render() {
    let { form, propertyInfo } = this.props;
    let { name, type, displayName, dataType, unit, descr } = propertyInfo;
    let { getFieldProps } = form;
    //接口
    //属性名
    const propertyNameProps = getFieldProps('name', {
      initialValue: name ? name : '',
      rules: [{ required: true, min: 1, max: 50, message: '支持1-20位非空格字符！' }]
    });
    //分类
    const classifyProps = getFieldProps('type', {
      initialValue: `${type}`,
      rules: [{ required: true, message: '分类不能为空！' }]
    });
    //显示名称
    const displayNameProps = getFieldProps('displayName', {
      initialValue: displayName ? displayName : '',
      rules: [{ required: true, min: 1, max: 20, message: '支持1-20位非空格字符！' }]
    });
    //数据类型
    const typeProps = getFieldProps('dataType', {
      initialValue: `${dataType}`,
      rules: [{ required: true, message: '数据类型不能为空！' }]
    });
    //单位
    const unitProps = getFieldProps('unit', {
      initialValue: unit ? unit : '',
      rules: [{ required: false, min: 1, max: 20, message: '支持1-20位非空格字符！' }]
    });
    //描述
    const descriptionProps = getFieldProps('descr', {
      initialValue: descr ? descr : '',
      rules: [{ required: false, message: '描述不能为空！' }]
    });
    //是否必填
    const disRequiredProps = getFieldProps('isRequired', {
      initialValue: propertyInfo ? propertyInfo.isRequired : false,
      valuePropName: 'checked',
      rules: []
    });
    return (
      <div className="device-interface-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={{ lineHeight: '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>
    );
  }
}

AddEditCapacityProperty.propTypes = {
  form: PropTypes.any,
  callBack: PropTypes.func,
  addCapacityProperty: PropTypes.func, //设备新增
  autoCardCalculate: PropTypes.func, //设备新增
  deviceId: PropTypes.number,
  capacityId: PropTypes.number,
  getDeviceInfoById: PropTypes.func, //详情新增
  propertyInfo: PropTypes.any
};
AddEditCapacityProperty.defaultProps = {
  propertyInfo: { type: '1', dataType: '1', enumRange: '' }
};
export default AddEditCapacityProperty;
