import React, { Component } from 'react';
import { Form, Input, Select, Radio, InputNumber } from 'amos-framework';
import PropTypes from 'amos-react-router/lib/PropTypes';
import { TreeSelect } from 'amos-antd';
import { getEquipmentDataAction, getRegionDepartmentTreeAction, getDepatUserListAction, getRiskSourceByTypeAction, getCompanyUserTreeAction,getCompanyUserWithDepartmentTreeAction } from '../../../../services/bizService';
import { parseTreeData, returnUsers } from './../../preControl/treeDataProcessor';
const Option = Select.Option;
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const floorData = [{ id: '1', name: '1层' }, { id: '2', name: '2层' }, { id: '3', name: '3层' }, { id: '4', name: '4层' }, { id: '5', name: '5层' }];

/**
 * 设备设施新增及编辑
 *
 * @class EquipFacilitiesModel
 * @extends {Component}
 */
class EquipFacilitiesModel extends Component {
  constructor(props) {
    super(props);
    this.state = {
      form: {
        id: '',
        name: '',
        code: '',
        regionId: '',
        departmentId: '',
        workshopSection: '',
        type: '',
        position3d: '',
        floor3d: '1',
        isIndoor: 1,
        leaderUserId: '',
        leaderDepartmentId: '',
        height: 0,
        companyLeaderUserId: [],
        companyLeaderUserRealName: [],
        deptLeaderUserId: [],
        deptLeaderUserRealName: [],
        shopLeaderUserId: [],
        shopLeaderUserRealName: [],
        classLeaderUserId: [],
        classLeaderUserRealName: [],
        isSpecial: 0,
        mainMedium: '',
        runParameter: '',
      },
      regionData: [],
      deptData: [],
      chargerDeptData: [],
      chargerPersonData: [],
      regionDepartmentTree: [],
      userData: [],
      userListData: [],
      rules: {
        regionId: [{ required: true, message: '所在分区不能为空' }],
        departmentId: [{ required: true, message: '部门/车间不能为空' }],
        workshopSection: [{ required: true, message: '所属工段不能为空' }],
        name: [{ required: true, message: '设备名称不能为空' }],
        code: [{ required: true, message: '设备位号不能为空' }],
        type: [{ required: true, message: '设备类型不能为空' }],
        position3d: [{ validator: this.validPositon3d }]
      }
    };
  }

  componentWillMount = () => {
    const { equipmentId, toolbarFlag } = this.props || {};
    if (toolbarFlag === 1) {
      //编辑
      this.getEquipmentData(equipmentId);
    }
    this.getCommonInfo();
    this.getRiskSource('02');//风险区域
  };

  componentDidMount() {
    this.queryUserData();
  }


  queryUserData = () => {
    getCompanyUserWithDepartmentTreeAction().then(data => {
      this.parseTreeData(data);
    });
    // const testData = [{ id: 1,label: 'user01' }, { id: 2,label: 'user02' }];
    // this.setState({ userData: testData });
  }

  // 解析返回的部门人员树，供TreeSelect使用
  parseTreeData = (treeList) => {
    let { userData,userListData } = this.state;
    userData = parseTreeData(treeList);
    userListData = returnUsers(treeList,userListData);
    this.setState({ userData, userListData });
  }

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

  onSelectChange = (key, e, obj) => {
    let { form, methodData } = this.state;
    form[key] = e;
    if(key === 'companyLeaderUserId'){
      form.companyLeaderUserRealName = obj;
    }else if(key === 'deptLeaderUserId'){
      form.deptLeaderUserRealName = obj;
    }else if(key === 'shopLeaderUserId'){
      form.shopLeaderUserRealName = obj;
    }else if(key === 'classLeaderUserId'){
      form.classLeaderUserRealName = obj;
    }
    this.setState({ form });
  }


  // onSelectChange(key, value) {
  //   const { form } = this.state;
  //   form[key] = value;
  //   if (key === 'leaderDepartmentId') {
  //     getDepatUserListAction(value).then(data => {
  //       let { chargerPersonData } = this.state;
  //       data.map(item => {
  //         let user = {};
  //         user.name = item.realName;
  //         user.id = item.userId;
  //         chargerPersonData.push(user);
  //       });
  //       this.setState({ chargerPersonData });
  //     });
  //   }
  //   this.setState({ form });
  // }

  getCommonInfo() {
    getRegionDepartmentTreeAction().then(data => {
      this.setState({ regionDepartmentTree: data },()=>this.getDeptData());
    });
  }

  getRiskSource = type => {
    getRiskSourceByTypeAction(type).then(data => {
      this.setState({ regionData: data });
    });
  }

  getEquipmentData = equipmentId => {
    getEquipmentDataAction(equipmentId).then(data => {
      let { form } = this.state;
      form.isIndoor = data.isIndoor ? 1 : 0;
      delete data.isIndoor;
      
      Object.assign(form,data);
      data.leaderDepartmentId && data.leaderUserId && this.onSelectChange('leaderDepartmentId',data.leaderDepartmentId);
      form.companyLeaderUserId = data.companyLeaderUserId ? data.companyLeaderUserId.split(',') : [];
      form.deptLeaderUserId = data.deptLeaderUserId ? data.deptLeaderUserId.split(',') : [];
      form.shopLeaderUserId = data.shopLeaderUserId ? data.shopLeaderUserId.split(',') : [];
      form.classLeaderUserId = data.classLeaderUserId ? data.classLeaderUserId.split(',') : [];
      this.setState({ form });
    });
  };

  getDeptData = () => {
    let { regionDepartmentTree, deptData } = this.state;
    let depatData = regionDepartmentTree.secondDepartments;
    deptData = [];
    for (let key in depatData ) {
      depatData[key].map(item =>{
        let deptObj = {};
        deptObj.id = item.sequenceNbr;
        deptObj.name = item.departmentName;
        deptData.push(deptObj);
      });
    }
    this.setState({ deptData, chargerDeptData: deptData });
  };

  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 });

  render() {
    const { form, rules, deptData, regionData, chargerDeptData, chargerPersonData, userData } = this.state;
    const { equipTypeData = [] } = this.props;
    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}>
        <div className="important-equipment-edit-left">
          <FormItem label={<span>所在风险区域</span>} field="regionId" {...formItemLayout}>
            <Select
              className="risk_factor_select"
              data={regionData}
              renderOption={item => <Option value={String(item.id)}>{item.name}</Option>}
              value={form.regionId}
              onChange={e => this.onSelectChange('regionId', e)}
            />
          </FormItem>
          
          <FormItem label={<span>部门/车间</span>} field="departmentId" {...formItemLayout}>
            <Select
              className="risk_factor_select"
              data={deptData}
              renderOption={item => <Option value={item.id}>{item.name}</Option>}
              value={form.departmentId}
              onChange={e => this.onSelectChange('departmentId', e)}
            />
          </FormItem>
          <FormItem label={<span>所属工段</span>} field="workshopSection" {...formItemLayout}>
            <Input className="risk_factor_input" required value={form.workshopSection} onChange={e => this.onInputChange('workshopSection', e.target.value)} />
          </FormItem>
          <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="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="type" {...formItemLayout}>
            <Select
              className="risk_factor_select"
              data={equipTypeData}
              value={form.type}
              renderOption={item => <Option value={item.code}>{item.name}</Option>}
              onChange={e => this.onSelectChange('type', e)}
            />
          </FormItem>
         
          <FormItem label={<span>公司责任人</span>} field="companyLeaderUserId" {...formItemLayout}>
            <TreeSelect
              value={form.companyLeaderUserId}
              className="risk-model-select"
              style={{ width: 240}}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto', top: 32 }}
              treeData={userData}
              placeholder="请选择"
              allowClear
              treeCheckable
              multiple
              showSearch
              treeNodeFilterProp={'title'}
              treeDefaultExpandAll
              onChange={(e, obj) => this.onSelectChange('companyLeaderUserId', e, obj)}
            />
          </FormItem>
          <FormItem label={<span>部门责任人</span>} field="deptLeaderUserId" {...formItemLayout}>
            <TreeSelect
              value={form.deptLeaderUserId}
              className="risk-model-select"
              style={{ width: 240}}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeData={userData}
              placeholder="请选择"
              allowClear
              treeCheckable
              multiple
              showSearch
              treeNodeFilterProp={'title'}
              treeDefaultExpandAll
              onChange={(e, obj) => this.onSelectChange('deptLeaderUserId', e, obj)}
            />
          </FormItem>
          <FormItem label={<span>车间责任人</span>} field="shopLeaderUserId" {...formItemLayout}>
            <TreeSelect
              value={form.shopLeaderUserId}
              className="risk-model-select"
              style={{ width: 240}}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto'}}
              treeData={userData}
              placeholder="请选择"
              allowClear
              treeCheckable
              multiple
              showSearch
              treeNodeFilterProp={'title'}
              treeDefaultExpandAll
              onChange={(e, obj) => this.onSelectChange('shopLeaderUserId', e, obj)}
            />
          </FormItem>
          <FormItem label={<span>班组责任人</span>} field="classLeaderUserId" {...formItemLayout}>
            <TreeSelect
              value={form.classLeaderUserId}
              className="risk-model-select"
              style={{ width: 240}}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto'}}
              treeData={userData}
              placeholder="请选择"
              allowClear
              treeCheckable
              multiple
              showSearch
              treeNodeFilterProp={'title'}
              treeDefaultExpandAll
              onChange={(e, obj) => this.onSelectChange('classLeaderUserId', e, obj)}
            />
          </FormItem>
          <FormItem label={<span>是否特种设备</span>} field="isSpecial" {...formItemLayout}>
            <RadioGroup defaultValue={form.isSpecial} value={form.isSpecial} onChange={e => this.onSelectChange('isSpecial', e)}>
              <Radio value={0}>否</Radio>
              <Radio value={1}>是</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label={<span>主要介质</span>} field="mainMedium" {...formItemLayout}>
            <Input className="risk_factor_input"  value={form.mainMedium} onChange={e => this.onInputChange('mainMedium', e.target.value)} />
          </FormItem>
          <FormItem label={<span>运行参数</span>} field="runParameter" {...formItemLayout}>
            <Input className="risk_factor_input"  value={form.runParameter} onChange={e => this.onInputChange('runParameter', e.target.value)} />
          </FormItem>
          <FormItem label={<span>高度（米）</span>} field="height" {...formItemLayout}>
            <InputNumber min={0} className="risk_factor_input" required value={form.height} onChange={value => this.onInputChange('height', value)} />
          </FormItem>
          <FormItem label={<span>3维坐标</span>} field="position3d" {...formItemLayout}>
            <Input className="risk_factor_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_factor_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>
        </div>
      </Form>
    );
  }
}

EquipFacilitiesModel.propTypes = {
  equipmentId: PropTypes.number,
  toolbarFlag: PropTypes.number,
  equipTypeData: PropTypes.arry
};
export default EquipFacilitiesModel;
