import React, { Component } from 'react';
import { Form, Input, Select, Radio, Upload, Modal, Icon, AmosAlert } from 'amos-framework';
import PropTypes from 'prop-types';
import { getBase64 } from './../../../../../utils/FileUtils';

const FormItem = Form.Item;
const RadioGroup  = Radio.Group;
const Option = Select.Option;
const floorData = [{ id: '1', name: '1层' }, { id: '2', name: '2层' }, { id: '3', name: '3层' }, { id: '4', name: '4层' }, { id: '5', name: '5层' }];

class FireFoamAdd extends Component {
  constructor(props) {
    super(props);
    this.state = {
      station: {
        type: 2,
        name: '',
        code: '',
        address: '',
        position3d: '',
        floor3d: '1',
        isIndoor: true,
        picture: []
      },
      previewVisible: false,
      previewImage: '',
      imgFiles: [],
      rules: {
        code: [
          { required: true, message: '请输入泡沫间编号' }
        ],
        name: [
          { required: true, message: '请输入泡沫间名称' }
        ],
        address: [
          { required: true, message: '请输入泡沫间地址' }
        ],
        position3d: [
          { validator: this.validPositon3d }
        ]
      }
    };
  }

  onChange = (key, e) => {
    const { station } = this.state;
    const value = e.target.value;
    station[key] = value;
    this.setState({ station });
    this.props.callback(station);
  };

  onInputChange = (key, value) => {
    const { station } = this.state;
    station[key] = value;
    this.setState({ station });
    this.props.callback(station);
  };

  validPositon3d = (rule, value, callback) => {
    let tempArry = value.split(',') || [];
    if ( tempArry && tempArry.length === 3 ){
      const patt = /(^([-]?)[1-9]([0-9]+)?(\.[0-9]+)?$)|(^([-]?)(0){1}$)|(^([-]?)[0-9]\.[0-9]+?$)/;
      let i = 0;
      for (let key of tempArry){
        if (!patt.test(key)){
          i = i + 1;
          callback('非法格式');
          break;
        }
      }
      i === 0 ? callback() : '';
    } else if (!value) {
      callback();
    } else {
      callback('非法格式');
    }
  }

  handleCancel = () => this.setState({ previewVisible: false });

  beforeUpload = file => {
    //1.格式校验
    const pattern = /image\/(gif|jpeg|png|jpg|bmp)$/;
    const isImg = pattern.test(file.type);
    if (!isImg) {
      AmosAlert.warning('请选择符合格式的图片！（gif|jpeg|png|jpg|bmp）');
      return false;
    }
    //2.url转文件对象
    this.changeData(file);
    return false;
  };

  changeData = async file => {
    file.url = await getBase64(file);
    let { imgFiles, station } = this.state;
    station.picture = [...imgFiles, file];
    this.setState({
      imgFiles: [...imgFiles, file]
    });
  };

  handlePreview = file => {
    this.setState({
      previewImage: file.url,
      previewVisible: true
    });
  };

  fileRemove = file => {
    this.setState(({ imgFiles, station }) => {
      let index = imgFiles.indexOf(file);
      let newFileList = imgFiles.slice();
      newFileList.splice(index, 1);
      station.picture = newFileList;
      return {
        imgFiles: newFileList,
        station
      };
    });
  };

  render() {
    const { station, rules, previewImage, previewVisible, imgFiles } = this.state;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
        className: 'colspanlab'
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
        className: 'colspan'
      }
    };

    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="amos-upload-text">选择图片</div>
      </div>
    );

    return (
      <Form className="basic-demo" model={station} rules={rules} ref={component => this.form = component}>
        <FormItem label={<span>泡沫间名称</span>} field="name" {...formItemLayout}>
          <Input className="risk_factor_input" value={station.name} onChange={e => this.onChange('name', e)} />
        </FormItem>
        <FormItem label={<span>泡沫间编号</span>} field="code" {...formItemLayout}>
          <Input className="risk_factor_input" value={station.code} onChange={e => this.onChange('code', e)} />
        </FormItem>
        <FormItem label="泡沫间地址" field="address" {...formItemLayout}>
          <Input className="risk_factor_input" value={station.address} onChange={e => this.onChange('address', e)} />
        </FormItem>
        <FormItem label={<span>3维坐标</span>} field="position3d" {...formItemLayout}>
          <Input className="risk_factor_input" required value={station.position3d} onChange={e => this.onInputChange('position3d', e.target.value)} />
        </FormItem>
        <FormItem label={<span>3维楼层</span>} field="floor3d" {...formItemLayout}>
          <Select
            className="fire-equip-select"
            data={floorData}
            defaultValue='1'
            value={station.floor3d}
            renderOption={item => <Option value={item.id}>{item.name}</Option>}
            onChange={e => this.onInputChange('floor3d', e)}
          />
        </FormItem>
        <FormItem label={<span>是否室内</span>} field="isIndoor" {...formItemLayout}>
          <RadioGroup defaultValue={station.isIndoor} value={station.isIndoor} onChange={e => this.onInputChange('isIndoor', e)}>
            <Radio value={false}>否</Radio>
            <Radio value={true}>是</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label={<span>图片上传</span>} field={station.imageUrl1} {...formItemLayout}>
          <div>
            <Upload
              fileList={imgFiles}
              listType="picture-card"
              beforeUpload={this.beforeUpload}
              onPreview={this.handlePreview}
              onRemove={this.fileRemove}
            >
              {uploadButton}
            </Upload>
            <Modal className='preview-photo-modal' content={<img alt='' style={{ width: '100%' }} src={previewImage} />} visible={previewVisible} noDefaultFooter onCancel={this.handleCancel} />
          </div>
        </FormItem>
      </Form>
    );
  }
}

FireFoamAdd.propTypes = {
  callback: PropTypes.func
};

export default FireFoamAdd;
