import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { TreeSelect } from 'amos-antd';
import { Form, Input, Divider, Radio, MultiSelect, Button } from 'amos-framework';
import BizIcon from './../../../../common/icon/BizIcon';
import { getFactorDetailAction, getCompanyUserTreeAction, getMethodDataAction } from '../../../../../services/bizService';
import { parseTreeData, returnUserList, returnUsers } from './../../treeDataProcessor';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Option = MultiSelect .Option;
/**
 *
 * 模型危险因素弹出框
 * @class DangerFactorModal
 * @extends {Component}
 */
class DangerFactorModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      form: {
        id: '',
        type: '1',
        userIds: [],
        userNames: [],
        identificationMethodIds: [],
        identificationMethodNames: [],
        riskSourceId: this.props.riskSourceId,
        lastOne: ''
      },
      rules: {
        type: [
          { required: true,message: '请输入危险因素类型' }
        ],
        userId: [
          { required: true,message: '请输入辨识人' }
        ],
        identificationMethodId: [
          { required: true,message: '请输入辨识方法' }
        ]
      },
      names: [],
      userData: [],
      methodData: [],
      userListData:[],
      depList:[]
    };
  }

  componentWillMount() {
    let  { selectedRow } = this.props;
    if (selectedRow && Object.keys(selectedRow).length > 0) {
      this.queryFactorDetail(selectedRow.id);
    }
  }

  componentDidMount() {
    this.queryUserData();
    this.queryMethodData();
  }

  onSelectChange = (key, e, obj) => {
    let { form, methodData } = this.state;
    if (key === 'name') {
      form.lastOne = e;
    }
    if (key === 'userIds') {
      form['userNames'] = obj;
    }
    if (key === 'identificationMethodIds') {
      obj = [];
      methodData.map(item => {
        if (e.includes(item.id)) {
          obj.push(item.name);
        }
      });
      form['identificationMethodNames'] = obj;
    }
    form[key] = e;
    this.setState({ form });
  }

  onFactorNameEdit = (key,name) =>{
    let { names } =  this.state;
    names[key] = name;
    this.setState({ names });
  }

  onButtonClick =(bthType,key)=>{
    let { names,form } =  this.state;
    if (bthType === 'delete') {
      names.splice(names.findIndex(item=>item.key === key),1);
      names.forEach((item,index) => item.key = index);//修改key与index 相同
    } else {
      form.name ? names.push({ key: names.length , name: form.name }) : '';//设置key与index 相同
    }
    form.name ? form.name = '' : '';
    this.setState({ names,form });
  }
  queryUserData = () => {
    getCompanyUserTreeAction().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,depList } = this.state;
    userData = parseTreeData(treeList);
    // userListData = returnUserList(treeList);
    userListData = returnUsers(treeList,userListData);
    this.setState({ userData, userListData });
  }

  queryMethodData = () => {
    getMethodDataAction().then(data => {
      this.setState({ methodData: data });
    });
    // const testData = [{ id: 1,name: 'method01' }, { id: 2,name: 'method02' }];
    // this.setState({ methodData: testData });
  }

  queryFactorDetail =(id)=>{
    getFactorDetailAction(id).then(data=>{
      let { form } = this.state;
      Object.assign(form,data);
      form.userIds = data.userIds ? data.userIds.split(',') : [];
      form.identificationMethodIds = data.identificationMethodIds ? data.identificationMethodIds.split(',') : [];
      this.setState({ form });
    });
  }

  renderFactorNamesList =(names, formItemLayout, wrapperCol) => {
    return names.map(item=>{
      return (<FormItem label={<span>危险因素名称</span>} field={item.key} {...formItemLayout} wrapperCol={wrapperCol}>
        <Input placeholder="本体有异常声音" value={item.name}  className='danger-long-input' onChange={(e) => this.onFactorNameEdit(item.key, e.target.value)} />
        <Button icon={<BizIcon icon="shanchu" />} onClick={() => this.onButtonClick('delete', item.key)} value={item.key} transparent />
      </FormItem>);
    });
  }

  render() {
    const { form, rules, userData, methodData, names } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
        className: 'colspanlab'
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
        className: 'colspan'
      }
    };

    const wrapperCol =  {
      xs: { span: 24 },
      sm: { span: 19 },
      className: 'colspan'
    };

    return (
      <div>
        <Form model={form} className='danger-factor-form' rules={rules} ref={component =>this.form = component}>
          <FormItem label={<span>基本信息</span>}  className='danger-factor-weight' field="baseInfo" {...formItemLayout} />
          <Divider />
          <FormItem label={<span>危险因素类型</span>} field="type" {...formItemLayout}>
            <RadioGroup defaultValue="1" value={form.type} onChange={value => this.onSelectChange('type',value)}>
              <Radio value="1">设备设施危险因素</Radio>
              <Radio value="2">作业活动危险因素</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label={<span>辨识人</span>} field="userIds" {...formItemLayout}>
            <TreeSelect
              value={form.userIds}
              className="risk-model-select"
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeData={userData}
              placeholder="请选择"
              allowClear
              treeCheckable
              multiple
              showSearch
              treeNodeFilterProp={'title'}
              treeDefaultExpandAll
              onChange={(e, obj) => this.onSelectChange('userIds', e, obj)}
            />
          </FormItem>
          <FormItem label={<span>辨识方法</span>} field="identificationMethodIds" {...formItemLayout}>
            <MultiSelect
              className="risk-model-select"
              data={methodData}
              renderOption={item => <Option value={parseInt(item.id)}>{item.name}</Option>}
              values={form.identificationMethodIds}
              onChange={(value) => this.onSelectChange('identificationMethodIds', value)}
            />
          </FormItem>
          <FormItem label={<span>危险有害因素</span>}  className='danger-factor-weight' field="factor" {...formItemLayout} />
          <Divider />
          <FormItem label={<span>危险因素名称</span>} field="name" {...formItemLayout} wrapperCol={wrapperCol}>
            <Input placeholder="请输入" className='danger-long-input' value={form.name} onChange={(e) => this.onSelectChange('name', e.target.value)} />
            {form.id ? '' : <Button icon={<BizIcon icon="tianjia" />} onClick={() => this.onButtonClick('add')} transparent />}
          </FormItem>
          {form.id ? '' : this.renderFactorNamesList(names,formItemLayout,wrapperCol)}
        </Form>
      </div>
    );
  }
}

DangerFactorModal.propTypes = {
  selectedRow: PropTypes.object,
  id: PropTypes.number,
  riskSourceId: PropTypes.number
};

export default DangerFactorModal;
