import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Form,Button,Row,Col,Modal } from 'amos-antd';
import { Select } from 'amos-framework';
import { AmosFetch } from '../../../../utils/processor';
import { OltSerUrl } from '../../../../consts/urlConsts';
import { message } from 'amos-framework';
import { interfaceDirectionEnum } from  './../../common/DeviceEnum';
import { enums2array } from './../../common/DeviceLang';

const Option = Select.Option;
const FormItem = Form.Item;
const Direction = enums2array(interfaceDirectionEnum).map((item)=>
  <Option key={item.key} value={`${item.key}`}>{item.label}</Option>) ;
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 5 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 }
  }
};
/**
 *
 * 新增/编辑设备接口
 * @class AddEditDeviceInterface
 * @extends {Component}
 */
class AddEditDeviceInterface extends Component {
  constructor(props) {
    super(props);
    this.state = {

    };
  }

  componentDidMount(){

  }

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

  /**
   *
   *
   * @memberof AddEditDeviceInterface
   */
  handleSave = (obj) => {
    let { interfaceMap } = this.props;
    let keyvalue = new Date().getTime();
    Object.assign(obj,{ key: keyvalue,intfcDisplayName: interfaceMap[parseInt(obj.intfcId)] });
    let interfaceProList = [{
      key: obj.key,
      intfcId: obj.intfcId,
      intfcDirection: obj.intfcDirection,
      displayName: interfaceMap[parseInt(obj.intfcId)],
      name: interfaceMap[parseInt(obj.intfcId)]
    }];
    let { deviceId } = this.props;
    if (deviceId === undefined) {
      //更新device对象
      this.props.addDeviceInterface(obj);
      //更新card
      this.props.autoCardCalculate(interfaceProList);
      this.props.form.resetFields();
      this.props.callBack();
    } else {
      //保存到数据库
      this.saveDeviceInterface(obj);
      //更新card
      // this.props.getDeviceInfoById(deviceId);
      // this.props.form.resetFields();
      // this.props.callBack();
    }
  }


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

  saveDeviceInterface = (obj) => {
    let { deviceId,propertyInfo } = this.props;
    let id = propertyInfo ? propertyInfo.devIntfcID : undefined;
    Object.assign(obj,{ deviceId,id });
    AmosFetch.post(OltSerUrl.deviceInterfaceUpdate,{ 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 { getFieldProps } = this.props.form;
    let { interfaceOption,propertyInfo } = this.props;
    let { intfcId,intfcDirection } = propertyInfo;
    //接口
    const interfaceProps = getFieldProps('intfcId', {
      initialValue: intfcId ? `${intfcId}` : interfaceOption.length > 0 ? interfaceOption[0].key : '',
      rules: [
          { required: true, message: '设备接口不能为空！' }
      ]
    });
    //接口方向
    const directionProps = getFieldProps('intfcDirection', {
      initialValue: intfcDirection ? `${intfcDirection}` : Direction[0].key,
      rules: [
          { required: true, message: '设备接口方向不能为空！' }
      ]
    });
    return (
      <div className='device-interface-add-modal'>
        <Form horizontal onSubmit={this.handleSubmit}>
          <FormItem {...formItemLayout} hasFeedback label='设备接口: '>
            <Select style={{ width: '100%',height: '32px' }}
              placeholder='设备接口'
              {...interfaceProps}
            >
              {interfaceOption}
            </Select>
          </FormItem>
          <FormItem {...formItemLayout} hasFeedback label='设备接口方向: '  >
            <Select style={{ width: '100%',height: '32px' }}
              {...directionProps}
            >
              {Direction}
            </Select>
          </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>
    );
  }
}

AddEditDeviceInterface.propTypes = {
  form: PropTypes.any,
  callBack: PropTypes.func,
  addDeviceInterface: PropTypes.func,//设备新增
  autoCardCalculate: PropTypes.func,//设备新增
  interfaceOption: PropTypes.array,
  interfaceMap: PropTypes.object,//设备新增
  deviceId: PropTypes.number,
  getDeviceInfoById: PropTypes.func,//详情新增
  propertyInfo: PropTypes.any
};
AddEditDeviceInterface.defaultProps = {
  propertyInfo: { intfcDirection: '0' }
};

export default AddEditDeviceInterface;
