import React, { Component } from 'react';
import _amosTool from 'amos-tool';
import SysConsts from 'amos-processor/lib/config/consts';
import formatUrl from 'amos-processor/lib/utils/urlFormat';
import { FasSerUrl } from '../../../../consts/urlConsts';
import { Form, Upload, Input, Select, Radio, Modal, AmosAlert, Icon } from 'amos-framework';
import PropTypes from 'amos-react-router/lib/PropTypes';
import { getEquipmentDataAction, getFireStationDataAction, getPrePlanPictureAction } from '../../../../services/ledgerService';
import { queryDeptByOrgCodeAction, getUsersByDepartmentIdAction } from '../../../../services/preControlService';
import { convertImgUrlToFile, getBase64 } from './../../../../utils/FileUtils';
import { baseURI, FscSerUrl } from '../../../../consts/urlConsts';


const ls = _amosTool.Store.lsTool;
const apiKey = SysConsts.api_key;
const token = SysConsts.token;
const url = FscSerUrl.loadPackagesUrl;

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup  = Radio.Group;
const TextArea = Input.TextArea;
const param = '/风险管控' ;
const floorData = [{ id: '1', name: '1层' }, { id: '2', name: '2层' }, { id: '3', name: '3层' }, { id: '4', name: '4层' }, { id: '5', name: '5层' }];

/**
 * 重点设备新增及编辑
 */
class EquipmentModel extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchParam: [],
      form: {
        name: '',
        code: '',
        address: '',
        building: '',
        chargeDeptId: null,
        chargeUserId: null,
        fireStationId: null,
        floor3d: '',
        position3d: '',
        room: '',
        remark: '',
        isIndoor: true,
        imageUrl1: [],
        imageUrl2: [],
        imageUrl3: [],
        imageUrl4: [],
        reservePlan: ''
      },
      chargeDeptData: [],
      chargeUserData: [],
      fireStationData: [],
      rules: {
        code: [{ required: true, message: '编码不能为空' }],
        name: [{ required: true, message: '名称不能为空' }],
        position3d: [{ validator: this.validPositon3d }]
      },
      previewVisible: false,
      previewImage: '',
      project: []
    };
  }

  componentWillMount = () => {
    const { equipmentId, toolbarFlag } = this.props || {};
    if (toolbarFlag === 1) {
      //编辑
      this.getEquipmentData(equipmentId);
    }
    this.getCommonInfo();
    this.queryLoadPackages(param);
  };

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

  onPeservePlanChange = (key, item) => {
    const { form } = this.state;
    let value = item.project ? item.project.substring(1) + '/' + item.id : '' ;
    form[key] = value;
    this.setState({ form });
  };

  onSelectChange(key, value) {
    const { form } = this.state;
    form[key] = value;
    if (key === 'chargeDeptId') {
      let deptId = value;
      getUsersByDepartmentIdAction(deptId).then(data => {
        this.setState({ chargeUserData: data, form });
      });
    }
    this.setState({ form });
  }

  getCommonInfo() {
    //1.获取部门
    queryDeptByOrgCodeAction().then(data => {
      this.setState({ chargeDeptData: data });
    });
    //2.获取消防小室
    getFireStationDataAction().then(data => {
      let filterData = data.filter(item => item.type === '1');
      this.setState({ fireStationData: filterData });
    });
  }

  getEquipmentData = equipmentId => {
    getEquipmentDataAction(equipmentId).then(data => {
      let deptId = data.chargeDeptId;
      deptId &&
        getUsersByDepartmentIdAction(deptId).then(data => {
          this.setState({ chargeUserData: data });
        });
      this.setState({ form: data });
    });
    this.getPrePlanPictureData(equipmentId);
  };

  getPrePlanPictureData = equipmentId => {
    getPrePlanPictureAction(equipmentId, '').then(data => {
      let pMap = new Map();
      data.forEach(ele => {
        let type = ele.type;
        if (type >= 1 && type <= 4) {
          pMap.set(type, ele.picture);
        }
      });

      this.setHavingFileToState(pMap);
    });
  };

  setHavingFileToState = pictureMap => {
    pictureMap.forEach((value, key) => {
      let pictureUrl = value;
      let pictureType = key;
      let fileName = value.substring(value.lastIndexOf('\\') + 1);
      convertImgUrlToFile(baseURI + pictureUrl, fileName, (file) => this.callBack(file, pictureType));
    });
  };

  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('非法格式');
    }
  }

  callBack = (file, key) => {
    let _form = this.state.form;
    switch (key) {
      case 1:
        _form.imageUrl1 = [file];
        break;
      case 2:
        _form.imageUrl2 = [file];
        break;
      case 3:
        _form.imageUrl3 = [file];
        break;
      case 4:
        _form.imageUrl4 = [file];
        break;
    }
    this.setState({ form: _form });
  };

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

  beforeUpload = (file, type) => {
    let _file = 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 _form = this.state.form;
    let { imageUrl1 = [], imageUrl2 = [], imageUrl3 = [], imageUrl4 = [] } = this.state.form;
    switch (file.mylist) {
      case 'imageUrl1':
        _form.imageUrl1 = [...imageUrl1, file];
        break;
      case 'imageUrl2':
        _form.imageUrl2 = [...imageUrl2, file];
        break;
      case 'imageUrl3':
        _form.imageUrl3 = [...imageUrl3, file];
        break;
      case 'imageUrl4':
        _form.imageUrl4 = [...imageUrl4, file];
        break;
    }
    this.setState({ form: _form });
  };

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

  fileRemove = file => {
    let { form } = this.state;
    switch (file.mylist) {
      case 'imageUrl1': {
        let index = form.imageUrl1.indexOf(file);
        let newFileList = form.imageUrl1.slice();
        newFileList.splice(index, 1);
        form.imageUrl1 = newFileList;
        this.setState({ form });
        break;
      }
      case 'imageUrl2': {
        let index = form.imageUrl2.indexOf(file);
        let newFileList = form.imageUrl2.slice();
        newFileList.splice(index, 1);
        form.imageUrl2 = newFileList;
        this.setState({ form });
        break;
      }
      case 'imageUrl3': {
        let index = form.imageUrl3.indexOf(file);
        let newFileList = form.imageUrl3.slice();
        newFileList.splice(index, 1);
        form.imageUrl3 = newFileList;
        this.setState({ form });
        break;
      }
      case 'imageUrl4': {
        let index = form.imageUrl4.indexOf(file);
        let newFileList = form.imageUrl4.slice();
        newFileList.splice(index, 1);
        form.imageUrl4 = newFileList;
        this.setState({ form });
        break;
      }
    }
  };

  queryLoadPackages =(project)=> {
    fetch(formatUrl(url, { project }), {
      method: 'post',
      headers: {
        'Accept': 'application/json;charset=UTF-8',
        'X-Api-Key': _amosTool.Store.getCookieByName(apiKey),
        'Content-Type': 'application/json; charset=utf-8',
        'X-Access-Token': ls.read(token)
      }
    }).then(res => {
      return res.json();
    }).then(data => {
      this.setState({ project: data });
    }).catch(e => {
      AmosAlert.error('错误', e);
    });
  }

  render() {
    const { form, rules, chargeDeptData, chargeUserData, fireStationData, previewImage, previewVisible, project } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
        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 (
      <div>
        <Form model={form} rules={rules} ref={component => (this.form = component)}>
          <div className="important-equipment-edit-left">
            <FormItem label={<span>设备编号</span>} field="code" {...formItemLayout}>
              <Input className="risk_factor_input" required value={form.code} onChange={e => this.onInputChange('code', e.target.value)} />
            </FormItem>
            <FormItem label={<span>建筑物</span>} field="building" {...formItemLayout}>
              <Input className="risk_factor_input" required value={form.building} onChange={e => this.onInputChange('building', e.target.value)} />
            </FormItem>
            <FormItem label={<span>消防小室</span>} field="fireStationId" {...formItemLayout}>
              <Select
                className="risk_factor_select"
                data={fireStationData}
                renderOption={item => <Option value={parseInt(item.id)}>{item.name}</Option>}
                value={form.fireStationId}
                onChange={e => this.onSelectChange('fireStationId', e)}
              />
            </FormItem>
            <FormItem label={<span>责任部门</span>} field="chargeDeptId" {...formItemLayout}>
              <Select
                className="risk_factor_select"
                data={chargeDeptData}
                renderOption={item => <Option value={parseInt(item.id)}>{item.departmentName}</Option>}
                value={form.chargeDeptId}
                onChange={e => this.onSelectChange('chargeDeptId', e)}
              />
            </FormItem>
            <FormItem label={<span>责任人</span>} field="chargeUserId" {...formItemLayout}>
              <Select
                className="risk_factor_select"
                data={chargeUserData}
                renderOption={item => <Option value={parseInt(item.id)}>{item.name}</Option>}
                value={form.chargeUserId === undefined ? null : form.chargeUserId}
                onChange={e => this.onSelectChange('chargeUserId', e)}
                closeOnScroll
              />
            </FormItem>
            <FormItem label={<span>电源负荷图</span>} field={form.imageUrl1} {...formItemLayout}>
              <div>
                <Upload
                  fileList={form.imageUrl1}
                  listType="picture-card"
                  beforeUpload={file => {
                    file.mylist = 'imageUrl1';
                    this.beforeUpload(file, 1);
                  }}
                  onPreview={this.handlePreview}
                  onRemove={file => {
                    file.mylist = 'imageUrl1';
                    this.fileRemove(file);
                  }}
                >
                  {form.imageUrl1 ? (form.imageUrl1.length >= 1 ? null : uploadButton) : uploadButton}
                </Upload>
                <Modal content={<img style={{ width: '100%' }} src={previewImage} />} visible={previewVisible} noDefaultFooter onCancel={this.handleCancel} />
              </div>
            </FormItem>
            <FormItem label={<span>电缆沟封堵图</span>} field="picture2" {...formItemLayout}>
              <div>
                <Upload
                  fileList={form.imageUrl2}
                  listType="picture-card"
                  beforeUpload={file => {
                    file.mylist = 'imageUrl2';
                    this.beforeUpload(file);
                  }}
                  onPreview={this.handlePreview}
                  onRemove={file => {
                    file.mylist = 'imageUrl2';
                    this.fileRemove(file);
                  }}
                >
                  {form.imageUrl2 ? (form.imageUrl2.length >= 1 ? null : uploadButton) : uploadButton}
                </Upload>
                <Modal content={<img style={{ width: '100%' }} src={previewImage} />} visible={previewVisible} noDefaultFooter onCancel={this.handleCancel} />
              </div>
            </FormItem>
            <FormItem label={<span>消防车进站行车路线图</span>} field="picture3" {...formItemLayout}>
              <div>
                <Upload
                  fileList={form.imageUrl3}
                  listType="picture-card"
                  beforeUpload={file => {
                    file.mylist = 'imageUrl3';
                    this.beforeUpload(file);
                  }}
                  onPreview={this.handlePreview}
                  onRemove={file => {
                    file.mylist = 'imageUrl3';
                    this.fileRemove(file);
                  }}
                >
                  {form.imageUrl3 ? (form.imageUrl3.length >= 1 ? null : uploadButton) : uploadButton}
                </Upload>
                <Modal content={<img style={{ width: '100%' }} src={previewImage} />} visible={previewVisible} noDefaultFooter onCancel={this.handleCancel} />
              </div>
            </FormItem>
            <FormItem label={<span>消防取水图</span>} field="picture4" {...formItemLayout}>
              <div>
                <Upload
                  fileList={form.imageUrl4}
                  listType="picture-card"
                  beforeUpload={file => {
                    file.mylist = 'imageUrl4';
                    this.beforeUpload(file);
                  }}
                  onPreview={this.handlePreview}
                  onRemove={file => {
                    file.mylist = 'imageUrl4';
                    this.fileRemove(file);
                  }}
                >
                  {form.imageUrl4 ? (form.imageUrl4.length >= 1 ? null : uploadButton) : uploadButton}
                </Upload>
                <Modal className='preview-photo-modal' content={<img style={{ width: '100%' }} src={previewImage} />} visible={previewVisible} noDefaultFooter onCancel={this.handleCancel} />
              </div>
            </FormItem>
          </div>
          <div className="important-equipment-edit-right">
            <FormItem label={<span>设备名称</span>} field="name" {...formItemLayout}>
              <Input className="risk_factor_input" required value={form.name} onChange={e => this.onInputChange('name', e.target.value)} />
            </FormItem>
            <FormItem label={<span>位置</span>} field="address" {...formItemLayout}>
              <Input className="risk_factor_input" required value={form.address} onChange={e => this.onInputChange('address', e.target.value)} />
            </FormItem>
            <FormItem label={<span>房间号</span>} field="room" {...formItemLayout}>
              <Input className="risk_factor_input" required value={form.room} onChange={e => this.onInputChange('room', e.target.value)} />
            </FormItem>
            <FormItem label={<span>3维坐标</span>} field="position3d" {...formItemLayout}>
              <Input className="risk_factor_input" required value={form.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}
                value={form.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={form.isIndoor} value={form.isIndoor} onChange={e => this.onInputChange('isIndoor', e)}>
                <Radio value={false}>否</Radio>
                <Radio value={true}>是</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem label={<span>预案配置</span>} field="reservePlan" {...formItemLayout}>
              <Select
                className="fire-equip-select"
                data={project}
                value={form.reservePlan ? form.reservePlan.split('/')[1] : ''}
                renderOption={item => <Option value={item.id}>{item.name}</Option>}
                onChange={(e,item) => this.onPeservePlanChange('reservePlan', item)}
              />
            </FormItem>
            <FormItem label={<span>备注</span>} field="remark" {...formItemLayout}>
              <TextArea rows={4} className="risk_factor_input" required value={form.remark} onChange={e => this.onInputChange('remark', e.target.value)} />
            </FormItem>
          </div>
        </Form>
      </div>
    );
  }
}

EquipmentModel.propTypes = {
  equipmentId: PropTypes.number,
  toolbarFlag: PropTypes.number
};
export default EquipmentModel;
