import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { TreeSelect } from 'amos-antd';
import { Form, Input, Select, Radio } from 'amos-framework';
import { parseDepartmentTreeData } from '../../treeDataProcessor';
import { getEvaluateModelListAction, queryRiskLevelListByEvModelAction,queryRiskSourceDetailAction } 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层' }];
/**
 * 添加风险层级，编辑及维护
 */

class RiskSourceModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchParam: [],
      riskLevelData: [],
      userData: [],
      methodData: [],
      riskTypeData: [],
      evaluateModelData: [],
      form: {
        name: '',
        code: '',
        riskLevel: '',
        parentId: this.props.parentId,
        floor3d: '1',
        isIndoor: 1,
        position3d: '',
        identificationMethodId: 0,
        userId: 0,
        riskType: '',
        belongDepartmentId: '',
        evaluateModelId: ''
      },
      rules: {
        name: [{ required: true, message: '风险名称不能为空' }],
        code: [{ required: true, message: '参考编号不能为空' }],
        isRegion: [{ required: true, message: '是否区域不能为空' }],
        isIndoor: [{ required: true, message: '是否室内不能为空' }],
        riskType: [{ required: true, message: '层级不能为空' }],
        position3d: [{ validator: this.validPositon3d }],
        belongDepartmentId: [{ required: true, message: '存在部门/车间不能为空' }]
      }
    };
  }

  componentWillMount = () => {
    let { selectedRowId, userData } = this.props;
    selectedRowId && this.queryRiskSourceDetailById(selectedRowId);
    this.getBelongDepartmentData(userData);
    this.getAllEvaluateModel();
  };

  onSelectChange = (key, value, t, obj) => {
    const { form } = this.state;
    if (obj && obj.triggerNode && obj.triggerNode.props && obj.triggerNode.props.type === 'department' && key === 'userId') {
      return;
    } else if (key === 'evaluateModelId') {
      this.getRiskLevelData(value);
    }
    form[key] = value;
    this.setState({ form });
  }

  getBelongDepartmentData = (userData) => {
    if (userData) {
      let { belongDepartmentData } = this.state;
      belongDepartmentData = parseDepartmentTreeData(userData);
      this.setState({ belongDepartmentData });
    }
  }

  getAllEvaluateModel = () => {
    getEvaluateModelListAction([], 0, -1).then(data => {
      this.setState({ evaluateModelData: data });
    });
  };

  getRiskLevelData = (evModelId) => {
    queryRiskLevelListByEvModelAction(evModelId).then(data => {
      this.setState({ riskLevelData: data });
    });
  }

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

  queryRiskSourceDetailById = (riskSourceId) =>{
    let { form } = this.state;
    queryRiskSourceDetailAction(riskSourceId).then(data =>{
      Object.assign(form,data);
      form.isIndoor = data.isIndoor ? 1 : 0;
      form.evaluateModelId && this.getRiskLevelData(form.evaluateModelId);
      this.setState({ form });
    });
  }

  render() {
    const { form, rules, belongDepartmentData = [], riskLevelData, evaluateModelData } = this.state;
    const { userData, methodData, riskTypeData } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
        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="riskType" {...formItemLayout}>
          <Select
            className="risk-model-select"
            data={riskTypeData}
            value={form.riskType}
            renderOption={item => <Option value={item.code}>{item.name}</Option>}
            onChange={e => this.onSelectChange('riskType', e)}
          />
        </FormItem>
        <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="evaluateModelId" {...formItemLayout}>
          <Select
            className="risk-model-select"
            data={evaluateModelData}
            value={form.evaluateModelId}
            renderOption={item => <Option value={item.id}>{item.name}</Option>}
            onChange={e => this.onSelectChange('evaluateModelId', e)}
          />
        </FormItem>
        <FormItem label={<span>风险等级</span>} field="riskLevel" {...formItemLayout}>
          <Select
            className="risk-model-select"
            data={riskLevelData}
            value={form.riskLevel ? parseInt(form.riskLevel) : form.riskLevel}
            renderOption={item => <Option value={item.id}>{item.level}</Option>}
            onChange={e => this.onSelectChange('riskLevel', e)}
          />
        </FormItem>
        <FormItem label={<span>辨识人</span>} field="userId" {...formItemLayout}>
          <TreeSelect
            value={form.userId === 0 ? undefined : form.userId}
            className="risk-model-select"
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={userData}
            placeholder="请选择"
            allowClear
            treeDefaultExpandAll
            onChange={(e, t, obj) => this.onSelectChange('userId', e, t, obj)}
          />
        </FormItem>
        <FormItem label={<span>辨识方法</span>} field="identificationMethodId" {...formItemLayout}>
          <Select
            className="risk-model-select"
            data={methodData}
            renderOption={item => <Option value={parseInt(item.id)}>{item.name}</Option>}
            value={form.identificationMethodId}
            onChange={value => this.onSelectChange('identificationMethodId', value)}
          />
        </FormItem>
        <FormItem label={<span>存在部门/车间</span>} field="belongDepartmentId" {...formItemLayout}>
          <TreeSelect
            value={form.belongDepartmentId === 0 ? undefined : form.belongDepartmentId}
            className="risk-model-select"
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={belongDepartmentData}
            placeholder="请选择"
            allowClear
            treeDefaultExpandAll
            onChange={(e, t, obj) => this.onSelectChange('belongDepartmentId', e, t, obj)}
          />
        </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={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>
    );
  }
}

RiskSourceModal.propTypes = {
  selectedRowId: PropTypes.array,
  userData: PropTypes.array,
  methodData: PropTypes.array,
  riskLevelData: PropTypes.array,
  riskTypeData: PropTypes.array,
  parentId: PropTypes.number
};

export default RiskSourceModal;
