import React, { Component } from 'react';
import { Form,Input,Row,Col,Modal,Collapse } from 'amos-antd';
import { Select } from 'amos-framework';
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 AddDeviceProperty from './deviceAddEdit/AddDeviceProperty';
import { deviceCategoryEnum,dataTypeEnum,classifyEnum } from  './../common/DeviceEnum';
import {objOfStrPropTrim,noSpaceLengthValidate} from './../../common/utils/validate';
import { enums2array,stringUtil } from './../common/DeviceLang';
import UpLoadImg from './../common/UpLoadImg';
import AddDeviceInterfaceCard from './deviceAddEdit/AddDeviceInterfaceCard';
import AddDeviceCapacityCard from './deviceAddEdit/AddDeviceCapacityCard';
import CommonCell from './../common/CommonCell';
import AddBtn from './../common/AddBtn';
import './add-device.scss';
import './../common/common.scss';

const createForm = Form.create();
const FormItem = Form.Item;
const Option = Select.Option;
const { TextArea } = Input;
const Panel = Collapse.Panel;
const maxDescLength = 500;

const dataTypeOption = enums2array(deviceCategoryEnum).map((item)=>
  <Option key={item.key} value={`${item.key}`}>{item.label}</Option>) ;


/**
 * 新建设备
 */
class AddDevice extends Component {
  constructor(props) {
    super(props);
    this.state = {
      activeKey: '1', //默认打开新建接口面板
      interfaceProList: [], //新建属性数据集合
      itemInfo: {}, //新建接口输入需要向后台提交保存的数据
      device: {
        equipmentPropertyParams: [],
        equipmentInterfaceParams: [],
        equipmentCapacityParams: []
      },//设备对象
      imgFile: {},//图片名称
      waiting: false//防止多次重复点击
    };
  }

  //下一步
  onClickDown = (e) => {
    let { activeKey } = this.state;
    //key加一
    activeKey = `${parseInt(activeKey) + 1}`;
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        values= objOfStrPropTrim(values);
        this.setState({
          itemInfo: values,
          activeKey
        });
      }
    });
  }

  //上一步
  onClickUp = () => {
    let { activeKey } = this.state;
    //key减一
    activeKey = `${parseInt(activeKey) - 1}`;
    this.setState({
      activeKey
    });
  }

  //确定提交事件，向后台发送创建数据方法
  onSaveDevice = (imgInfo) => {
    this.setState({waiting: true});
    let name = this.props.form.getFieldValue('name');
    let model = this.props.form.getFieldValue('model');
    let type = this.props.form.getFieldValue('type');
    let desc = this.props.form.getFieldValue('desc');
    let viewPath = this.props.form.getFieldValue('viewPath');
    let industryId = this.props.form.getFieldValue('industryId');
    Object.assign(this.state.device,{ name,model,type,viewPath,desc,visibility: 1,industryId },imgInfo);
    AmosFetch.post(OltSerUrl.addDevice,{ data: this.state.device }).then(res => {
      if (res.ok) {
        return res.text();
      }
      else
      {
        throw new Error('从服务端获取数据失败！');
      }
    }).then((data)=>{
      let result = JSON.parse(data);
      let resultStatus = result.result;
      if (resultStatus === 'SUCCESS') {
        if (result.dataList === 0) {
          this.setState({waiting: false});
          message.danger('设备原型名称重复');
        } else {
          message.success('保存成功');
          this.setState({ device: {},imgFile: {} });
          this.props.updateAddView('2');
          this.props.form.resetFields();
        }
      } else {
        this.setState({waiting: false});
        message.danger('保存失败');
      }
    });
  }

  /**
   * 设置图片
   *
   * @memberof AddDevice
   */
  setImgFile = (imgFile) => {
    this.setState({ imgFile });
  }

  autoCardCalculate= (newDevice) => {
    let interfaceProList = this.state.interfaceProList;
    if (newDevice !== undefined) {
      interfaceProList = [ ...interfaceProList, ...newDevice ];
      this.setState({ interfaceProList });
    }
    this.autoProView();
  }

  //根据属性数据自动生成对应的所需要展示的card
  autoProView = (newDevice) => {
    let interfaceProList = newDevice === undefined ? this.state.interfaceProList : newDevice;
    let antoView = [];
    antoView.push(<div key={0}>
      <AddDeviceProperty repuestType='addProperty' addDeviceProperty={this.addDeviceProperty} autoCardCalculate={this.autoCardCalculate} />
    </div>);
    if ( interfaceProList.length > 0 ){
      for (let interfacePro of interfaceProList) {
        let contentHtml = [];
        contentHtml.push(<p>分&emsp;&emsp;类：{stringUtil(classifyEnum,parseInt(interfacePro.type))}</p>);
        contentHtml.push(<p>数据类型：{stringUtil(dataTypeEnum,parseInt(interfacePro.dataType))}</p>);
        antoView.push(
          <CommonCell contentHtml={contentHtml} cardKey={interfacePro.key} value={interfacePro} deleteCellProperty={this.deleteCellProperty} />);
      }
    }
    return antoView;
  }



  /**
   * 添加设备属性信息
   *
   * @memberof AddDevice
   */
  addDeviceProperty = (property) => {
    let device = this.state.device;
    device.equipmentPropertyParams = [ ...device.equipmentPropertyParams,property ];
    this.setState({ device });
  }

  /**
   *
   *保存图片
   * @memberof UpLoadImg
   */
  saveImg = () => {
    const reader = new FileReader();
    reader.addEventListener('load', () => this.upLoadImgToSave(reader.result));
    let imgFile = this.state.imgFile;
    if (JSON.stringify(imgFile) === '{}') {
      let imgInfo = { 'binaryImg': null,'imgName': 'default.png' };
      this.onSaveDevice(imgInfo);
    } else {
      reader.readAsBinaryString(this.state.imgFile);
    }
  };

  /**
   * 添加设备接口信息
   *
   * @memberof AddDevice
   */
  addDeviceInterface = (interfaceInfo) => {
    let device = this.state.device;
    device.equipmentInterfaceParams = [ ...device.equipmentInterfaceParams,interfaceInfo ];
    this.setState({ device });
  }

  /**
   * 添加数据采集模型信息
   *
   * @memberof AddDevice
   */
  addDeviceCapacity = (capacityInfo) => {
    let device = this.state.device;
    device.equipmentCapacityParams = [ ...device.equipmentCapacityParams,capacityInfo ];
    this.setState({ device });
  }

  /**
   * 提交
   *
   * @memberof AddDevice
   */
  saveDeviceData = () => {
    this.saveImg();
  }

  /**
   *
   *提交图片至后台
   * @memberof UpLoadImg
   */
  upLoadImgToSave = (binaryImg) => {
    let name = this.state.imgFile.name;
    let imgInfo = { 'binaryImg': binaryImg,'imgName': name };
    this.onSaveDevice(imgInfo);
  };

  /**
   * 删除Card
   *
   * @memberof AddDevice
   */
  deleteCellProperty = (id) =>{
    //更新card用的数据
    let interfaceList = this.state.interfaceProList;
    let removedList = [];
    for (let value of interfaceList) {
      if (value.key !== id) {
        removedList.push(value);
      }
    }
    this.setState({ interfaceProList: removedList });
    //更新保存用的数据
    let device = this.state.device;
    let deviceProperty = device.equipmentPropertyParams;
    let filterList = [];
    for (let value of deviceProperty) {
      if (value.key !== id) {
        filterList.push(value);
      }
    }
    device.equipmentPropertyParams = filterList;
    this.setState({ device });
    //更新页面
    this.autoProView();
  }

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

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

  render() {
    let { device } = this.state;
    let equiptemplateIndustryOptions = this.props.equiptemplateIndustryOptions?this.props.equiptemplateIndustryOptions:[];
    const { getFieldProps } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 18 }
    };
    const imgItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 10 }
    };
    //名称
    const nameProps = getFieldProps('name', {
      rules: [
        { required: true,min: 1,max: 20, message: '支持1-20位字符！' },
        { validator:noSpaceLengthValidate(null,true,'名称不能为空！')}
      ]
    });
    //型号
    const modelProps = getFieldProps('model', {
      rules: [
          { required: true, message: '型号不能为空！' },
          { validator:noSpaceLengthValidate(null,true,'型号不能为空！')}
      ]
    });
    //类别
    const typeProps = getFieldProps('type', {
      rules: [
        { required: true, message: '类别不能为空！' }
      ]
    });
     //行业
    const industryProps = getFieldProps('industryId', {
      rules: [
          { required: true, message: '所属行业不能为空！' }
      ]
    });
    //视图路径
    const viewPathProps = getFieldProps('viewPath', {
      rules: [
      ]
    });
    //说明
    const descProps = getFieldProps('desc', {
      rules: [
        { validator: noSpaceLengthValidate(maxDescLength,false,null) }
      ]
    });
    return (
      <div className='add-device'>
        <Collapse activeKey={this.state.activeKey} accordion>
          <Panel className='device-info' header='设备信息' key='1' showArrow={false} >
            <div style={{ textAlign: 'center' }} >
              <Row>
                <Col span={9} offset={4} >
                  <FormItem hasFeedback label='名称' {...formItemLayout} >
                    <Input className='amos-grid-form-input' {...nameProps} placeholder='支持1-20位字符' />
                  </FormItem>
                  <FormItem hasFeedback label='型号' {...formItemLayout} >
                    <Input className='amos-grid-form-input' {...modelProps} placeholder='请输入型号' />
                  </FormItem>
                  <FormItem hasFeedback label='类别' {...formItemLayout} >
                    <Select style={{ width: '100%',textAlign: 'left',height: '32px' }} {...typeProps} placeholder="请选择类别">
                      {dataTypeOption}
                    </Select>
                  </FormItem>
                  <FormItem hasFeedback label='所属行业: ' {...formItemLayout} >
                    <Select style={{ width: '100%',textAlign: 'left',height: '32px' }}
                      {...industryProps} placeholder="请选择所属行业">
                      {
                        equiptemplateIndustryOptions.map(comm => {
                          return (<Option key={`${comm.value}Option`} value={comm.value}>{comm.label}</Option>);
                        })
                      }
                    </Select>
                  </FormItem>
                  {/* <FormItem hasFeedback label='视图路径' {...formItemLayout} >
                    <Input className='amos-grid-form-input' {...viewPathProps} placeholder='请输入视图路径' />
                  </FormItem> */}
                  <FormItem hasFeedback label='说明' {...formItemLayout} >
                    <TextArea className='amos-grid-form-input text-area-put' {...descProps} placeholder='请输入说明'/>
                  </FormItem>
                </Col>
                <Col span={10} offset={1} >
                  <FormItem label='设备示意图' {...imgItemLayout} >
                    <UpLoadImg setImgFile={this.setImgFile} />
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <AddBtn text={'下一步'} onClick={this.onClickDown} />
              </Row>
            </div>
          </Panel>
          <Panel className='device-property' header='新建设备属性' key='2' showArrow={false} >
            <Row>
              {
                  this.autoProView()
                }
            </Row>
            <div style={{ height: '3rem' }} />
            <Row  type='flex' justify='center' >
              <AddBtn text={'上一步'} onClick={this.onClickUp} />
              <div style={{ width: '1.5rem' }} />
              <AddBtn text={'下一步'} onClick={this.onClickDown} />
            </Row>
          </Panel>

          <Panel className='device-interface' header='新建设备接口' key='3' showArrow={false} >
            <Row>
              <AddDeviceInterfaceCard repuestType='addProperty' deleteCellInterface={this.deleteCellInterface} addDeviceInterface={this.addDeviceInterface} />
            </Row>
            <div style={{ height: '3rem' }} />
            <Row  type='flex' justify='center' >
              <AddBtn text={'上一步'} onClick={this.onClickUp} />
              <div style={{ width: '1.5rem' }} />
              <AddBtn text={'下一步'} onClick={this.onClickDown} />
            </Row>
          </Panel>

          <Panel className='device-capacity' header='新建数据采集模型' key='4' showArrow={false} >
            <Row>
              <AddDeviceCapacityCard
                deviceInterfaces={device.equipmentInterfaceParams}
                repuestType='addProperty'
                deleteCellCapacity={this.deleteCellCapacity}
                addDeviceCapacity={this.addDeviceCapacity}
              />
            </Row>
            <div style={{ height: '3rem' }} />
            <Row  type='flex' justify='center' >
              <AddBtn text={'上一步'} onClick={this.onClickUp} />
              <div style={{ width: '1.5rem' }} />
              <AddBtn text={'确定'} onClick={this.saveDeviceData} disabled={this.state.waiting}/>
            </Row>
          </Panel>
        </Collapse>
      </div>
    );
  }
}

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

export default createForm(AddDevice);
