import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Form,Button,Row,Col,Input,Modal,Radio } from 'amos-antd';
import { Select } from 'amos-framework';
import { utils } from 'amos-tool';
import { AmosFetch } from 'UTILS/processor';
import { OltSerUrl } from 'CONSTS/urlConsts';
import { message } from 'amos-framework';
import AddCapacityPropertyCard from './AddCapacityPropertyCard';
import { capacityClassifyEnum } from  './../../common/DeviceEnum';
import { enums2array } from './../../common/DeviceLang';
import { monitorTypeArr,periodArr } from './../../../createEquipment/common/TaskEnum';
import {objOfStrPropTrim,noSpaceLengthValidate} from './../../../common/utils/validate';

const Option = Select.Option;
const RadioGroup = Radio.Group;
const FormItem = Form.Item;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 5 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 }
  }
};

const fieldNames = ['name','type','intfcIds','protocolId','descr','monitortype', 'mongodb'];
/**
 *
 * 新增/编辑能力
 * @class AddEditDeviceCapacity
 * @extends {Component}
 */
class AddEditDeviceCapacity extends Component {
  constructor(props) {
    super(props);
    this.state = {
      capacityProperty: []
    };
  }

  componentDidMount(){

  }

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

  handleSave = (obj) => {
    const { interfaceMap, listInfo } = this.props;
    const interfaceIds = obj.intfcIds;
    if (!utils.isNil(interfaceIds) && !utils.isArray(interfaceIds)){
      obj.intfcIds = [interfaceIds];
    }
    const keyValue = new Date().getTime();
    const newObj = {
      ...obj,
      capacityPropertyParams: this.state.capacityProperty,
      key: keyValue
    };
    let intfcNames;
    if (!utils.isEmpty(newObj) && !utils.isEmpty(newObj.intfcIds)){
      intfcNames = newObj.intfcIds.map((item) => {
        return interfaceMap[parseInt(item.split('-')[0])];
      });
    }
    const interfaceProList = [{
      ...newObj,
      intfcDisplayName: intfcNames
    }];
    const { deviceId } = this.props;
    if (utils.isNil(deviceId)) {
      //更新device对象
      this.props.addDeviceCapacity(newObj);
      //更新card
      this.props.autoCardCalculate(interfaceProList);
      this.props.form.resetFields();
      this.props.callBack();
    } else {
      //编辑数据
      const editObj = listInfo.id ? { ...newObj, id: listInfo.id } : newObj;
      //保存到数据库
      this.saveDeviceCapacity(editObj);
    }
  }

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

  /**
   * 添加能力属性信息
   *
   * @memberof AddEditDeviceCapacity
   */
  addCapacityProperty = (value) => {
    let capacityProperty = this.state.capacityProperty;
    capacityProperty = [ ...capacityProperty,value ];
    this.setState({ capacityProperty });
  }

  deleteCellCapacityProperty = (id) =>{
    //更新保存用的数据
    let capacity = this.state.capacityProperty;
    let filterList = [];
    for (let value of capacity) {
      if (value.key !== id) {
        filterList.push(value);
      }
    }
    this.setState({ capacityProperty: filterList });
  }

  /**
   * 保存设备能力
   *
   * @memberof saveDeviceCapacity
   */
  saveDeviceCapacity = (obj) => {
    Object.assign(obj,{ equipmentId: this.props.deviceId });
    AmosFetch.post(OltSerUrl.deviceCapacityAdd,{ 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(this.props.deviceId);
      this.props.form.resetFields();
      this.props.callBack();
    });
  }

  changeMonitorType = (value) => {
    if (value === 1) {
      this.monitorDevice = true;
    } else {
      this.monitorDevice = false;
    }
  }

  render() {
    let { getFieldProps } = this.props.form;
    let { protocolOption,interfaceOption,deviceId,listInfo,protocolId,selectedInterfaceList } = this.props;
    let { name,type,descr,monitorType,monitorPeriod, mongodb } = listInfo;
    if (!protocolId){
      protocolId = '';
    }
    //名称
    const nameProps = getFieldProps('name', {
      initialValue: name,
      rules: [
          { required: true,min: 1,max: 20, message: '支持1-20位非空格字符！' },
          {validator:noSpaceLengthValidate(20,true,'名称不能为空！')}
      ]
    });
    //分类
    const classifyProps = getFieldProps('type', {
      initialValue: `${type}`,
      rules: [
          { required: true, message: '分类不能为空！' }
      ]
    });
    //接口
    const interfaceProps = getFieldProps('intfcIds', {
      initialValue: selectedInterfaceList,
      rules: [
          { required: true, message: '设备接口不能为空！' }
      ]
    });
    //协议
    const protocolProps = getFieldProps('protocolId', {
      initialValue: `${protocolId}`,
      rules: [
          { required: true, message: '通讯协议不能为空！' }
      ]
    });
    //描述
    const descriptionProps = getFieldProps('descr', {
      initialValue: descr,
      rules: [
          { required: false, message: '描述不能为空！' }
      ]
    });
    //描述
    const mongodbProps = getFieldProps('mongodb', {
      initialValue: mongodb
    });
    //监测方式
    const monitorTypeProps = getFieldProps('monitortype', {
      initialValue: monitorType,
      rules: [
          { required: true, message: '监测方式不能为空！' }
      ]
    });
    //采集周期
    const periodProps = getFieldProps('period', {
      initialValue: monitorPeriod,
      rules: [
          { required: true, message: '采集周期不能为空！' }
      ]
    });
    let formItems = [];
    //新增设备时时有属性，设备详情编辑中的新增没有
    if (deviceId === undefined) {
      formItems.push(
        <FormItem label='属性' {...formItemLayout} >
          <AddCapacityPropertyCard repuestType='addProperty' addCapacityProperty={this.addCapacityProperty} deleteCellCapacityProperty={this.deleteCellCapacityProperty} />
        </FormItem>
      );
    }
    const capacityClassifyOption = enums2array(capacityClassifyEnum).map((item)=> <Radio key={item.key} value={`${item.key}`}>{item.label}</Radio>);
    return (
      <div className='device-capacity-add-modal'>
        <Form horizontal onSubmit={this.handleSubmit}>
          <FormItem {...formItemLayout} hasFeedback label='名称: '>
            <Input {...nameProps} placeholder='名称（支持1-20位非空格字符）' />
          </FormItem>
          <FormItem {...formItemLayout} hasFeedback label='分类: '>
            <RadioGroup
              placeholder='分类'
              {...classifyProps}
            >
              {capacityClassifyOption}
            </RadioGroup>
          </FormItem>
          <FormItem {...formItemLayout} hasFeedback label='设备接口: '>
            <Select style={{ width: '100%',height: '32px' }}
              // mode="multiple"
              placeholder='设备接口'
              {...interfaceProps}
            >
              {interfaceOption}
            </Select>
          </FormItem>
          <FormItem {...formItemLayout} hasFeedback label='协议: '>
            <Select style={{ width: '100%',height: '32px' }}
              placeholder='协议'
              {...protocolProps}
            >
              {protocolOption}
            </Select>
          </FormItem>
          <FormItem {...formItemLayout} hasFeedback label='描述: '  >
            <Input {...descriptionProps}  />
          </FormItem>
          <FormItem {...formItemLayout} hasFeedback label='监测方式: '>
            <Select style={{ width: '100%',height: '32px' }}
              onSelect={this.changeMonitorType}
              placeholder='监测方式'
              {...monitorTypeProps}
            >
              {
                monitorTypeArr.map(data => <Option key={data.value} value={data.value}>{data.title}</Option>)
              }
            </Select>
          </FormItem>
          {this.monitorDevice ? <FormItem {...formItemLayout} hasFeedback label='采集周期: '>
            <Select style={{ width: '100%',height: '32px' }}
              placeholder='采集周期'
              {...periodProps}
            >
              {
                periodArr.map(data => <Option key={data.value} value={data.value}>{data.title}</Option>)
              }
            </Select>
          </FormItem> : ''}
          {formItems}
          <FormItem {...formItemLayout} hasFeedback label='MongoDB: '  >
            <Input {...mongodbProps}  />
          </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>
    );
  }
}

AddEditDeviceCapacity.propTypes = {
  form: PropTypes.any,
  callBack: PropTypes.func,
  addDeviceCapacity: PropTypes.func,//设备新增
  autoCardCalculate: PropTypes.func,//设备新增
  protocolOption: PropTypes.array,
  interfaceOption: PropTypes.array,
  interfaceMap: PropTypes.object,
  deviceId: PropTypes.number,
  getDeviceInfoById: PropTypes.func,//详情新增
  listInfo: PropTypes.any,
  protocolId: PropTypes.number,
  selectedInterfaceList: PropTypes.array,
  capacityId: PropTypes.number,
  updateNewInfo: PropTypes.func //编辑成功后更新页面数据
};

AddEditDeviceCapacity.defaultProps = {
  listInfo: { name: '',type: '1',descr: '' }
};

export default AddEditDeviceCapacity;
