import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { TreeSelect } from 'amos-antd';
import { Form, Input, Select, Radio } from 'amos-framework';
import { getMajorHazardDetailAction, fetchRiskSourceListAction } from './../../../../../services/bizService';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const floorData = [{ id: '1', name: '1层' }, { id: '2', name: '2层' }, { id: '3', name: '3层' }, { id: '4', name: '4层' }, { id: '5', name: '5层' }];
const IntegerMax = -1 - (2 << 30);//后端Integer最大值

class MajorHazardModel extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchParam: [],
      riskLevelData: [],
      userData: [],
      methodData: [],
      form: {
        name: '',
        code: '',
        riskSourceId: '',
        riskLevel: '',
        floor3d: '1',
        isIndoor: 1,
        position3d: '',
        identificationMethodId: 0,
        identificationUserId: 0
      },
      rules: {
        name: [{ required: true, message: '名称不能为空' }],
        code: [{ required: true, message: '编号不能为空' }],
        riskSourceId: [{ required: true, message: '风险区域不能为空' }],
        isIndoor: [{ required: true, message: '是否室内不能为空' }],
        position3d: [{ validator: this.validPositon3d }]
      }
    };
  }

  componentWillMount = () => {
    let { majorHazardId, toolbarFlag } = this.props;
    toolbarFlag === 1 && majorHazardId && this.queryMajorHazardDetailById(majorHazardId);
    this.queryRiskSource();
  };

  onSelectChange = (key, value, t, obj) => {
    const { form } = this.state;
    if (obj && obj.triggerNode && obj.triggerNode.props && obj.triggerNode.props.type === 'department') {//辨识人，过滤部门
      return;
    }
    if (obj && obj.triggerNode && obj.triggerNode.props && obj.triggerNode.props.type === 'model') {//辨识人，过滤模型
      return;
    }
    form[key] = value;
    this.setState({ form });
  }

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

  queryMajorHazardDetailById = (majorHazardId) =>{
    let { form } = this.state;
    getMajorHazardDetailAction(majorHazardId).then(data => {
      Object.assign(form, data);
      form.isIndoor = data.isIndoor ? 1 : 0;
      this.setState({ form });
    });
  }

  queryRiskSource = () => {
    let searchParam = [{ name: 'riskType', type: 'EQUAL', value: '02' }];
    fetchRiskSourceListAction(searchParam, 0, IntegerMax).then(data => {
      this.setState({ riskSourceData: data.content });
    });
  }

  render() {
    const { form, rules, riskSourceData = [] } = this.state;
    const { methodData = [], userData = [], riskLevelData = [] } = this.props.searchCommonData;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
        className: 'colspanlab'
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
        className: 'colspan'
      }
    };

    return (
      <Form model={form} rules={rules} ref={component => this.form = component}>
        <FormItem label={<span>名称</span>} field="name" {...formItemLayout}>
          <Input className="risk-model-input"  value={form.name} onChange={e => this.onSelectChange('name', e.target.value)} />
        </FormItem>
        <FormItem label={<span>编号</span>} field="code" {...formItemLayout}>
          <Input className="risk-model-input"  value={form.code} onChange={e => this.onSelectChange('code', e.target.value)} />
        </FormItem>
        <FormItem label={<span>风险区域</span>} field="riskSourceId" {...formItemLayout}>
          <Select
            className="risk-model-select"
            data={riskSourceData}
            value={form.riskSourceId}
            renderOption={item => <Option value={item.id}>{item.name}</Option>}
            onChange={e => this.onSelectChange('riskSourceId', e)}
          />
        </FormItem>
        <FormItem label={<span>风险等级</span>} field="riskLevel" {...formItemLayout}>
          <TreeSelect
            value={form.riskLevel === 0 ? undefined : form.riskLevel}
            className="risk-list-select"
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={riskLevelData || []}
            placeholder="请选择"
            allowClear
            showSearch
            treeNodeFilterProp={'title'}
            treeDefaultExpandAll
            onChange={(e, t, obj) => this.onSelectChange('riskLevel', e, t, obj)}
          />
        </FormItem>
        <FormItem label={<span>辨识人</span>} field="identificationUserId" {...formItemLayout}>
          <TreeSelect
            value={form.identificationUserId === 0 ? undefined : form.identificationUserId}
            className="risk-model-select"
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={userData}
            placeholder="请选择"
            allowClear
            treeDefaultExpandAll
            onChange={(e, t, obj) => this.onSelectChange('identificationUserId', e, t, obj)}
          />
        </FormItem>
        <FormItem label={<span>辨识方法</span>} field="identificationMethodId" {...formItemLayout}>
          <Select
            className="risk-model-select"
            data={methodData}
            renderOption={item => <Option value={item.id}>{item.name}</Option>}
            value={parseInt(form.identificationMethodId)}
            onChange={value => this.onSelectChange('identificationMethodId', value)}
          />
        </FormItem>
        <FormItem label={<span>3维坐标</span>} field="position3d" {...formItemLayout}>
          <Input className="risk-model-input" placeholder="-23.01,45,36" value={form.position3d} onChange={e => this.onSelectChange('position3d', e.target.value)} />
        </FormItem>
        <FormItem label={<span>3维楼层</span>} field="floor3d" {...formItemLayout}>
          <Select
            className="risk-model-select"
            data={floorData}
            defaultValue='1'
            value={String(form.floor3d)}
            renderOption={item => <Option value={item.id}>{item.name}</Option>}
            onChange={e => this.onSelectChange('floor3d', e)}
          />
        </FormItem>
        <FormItem label={<span>是否室内</span>} field="isIndoor" {...formItemLayout}>
          <RadioGroup defaultValue={form.isIndoor} value={form.isIndoor} onChange={e => this.onSelectChange('isIndoor', e)}>
            <Radio value={0}>否</Radio>
            <Radio value={1}>是</Radio>
          </RadioGroup>
        </FormItem>
      </Form>
    );
  }
}

MajorHazardModel.propTypes = {
  majorHazardId: PropTypes.number,
  toolbarFlag: PropTypes.number,
  searchCommonData: PropTypes.obj
};

export default MajorHazardModel;
