import React, { Component } from 'react';
import PropTypes from 'prop-types';
import GridButton from './../../common/btns/GridButton';
import SimpleModal from './../../common/modal/SimpleModal';
import CompanyAddEdit from './CompanyAddEdit';
import {objOfStrPropTrim} from './../../common/utils/validate';
import {Modal,Form} from 'amos-antd';

const createForm = Form.create();
const dataToTree = (dataList = []) => {
  dataList.map((data)=>{
    data.label = data.text;
    data.key = data.id;
    data.value = data.id;
    if(data.children){
      dataToTree(data.children);
    }
  });
};
/**
 * 单位信息编辑
 * @class EditCompany
 * @extends {Component}
 */
class EditCompany extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      company: {},
      selectId: -1
    };
  }

  onClick = () => {
    let {selectRows} = this.props;
    console.log('selectRows',selectRows);
    if(selectRows.length == 0){
      Modal.warning({title: '提示', content: '请先选中要编辑的单位。'});
    } else {
      if(selectRows.length > 1){
        Modal.warning({title: '提示', content: '一次只能编辑一个单位'});
      } else {
        this.props.superiorUnitEditAction(selectRows[0].id);
        this.props.companyInfoAction(selectRows[0].id);
        this.setState({visible: true,selectId: selectRows[0].id});
      }
    }
  }

  handleSave = (obj) => {
    obj.id = this.state.selectId;
    this.props.companyEditAction(obj);
    this.handCancel();
  }

  handCancel = () => {
    this.props.form.resetFields();
    this.setState({visible: false,company: {}, selectId: ''});
  }

  /**
   * 保存按钮事件
   */
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((errors, values) => {
      if(errors) {
        return;
      }
      values = objOfStrPropTrim(values);
      this.handleSave(values);
    });
  }

  render() {
    let {text,form,editSuperiorCompanyList,companyInfo} = this.props;
    return (
      <span>
        <GridButton text={text} color='#FFF' icon='edit' onClick={this.onClick} />
        <SimpleModal title='编辑单位' visible={this.state.visible}  onOk={this.handleSubmit} onCancel={this.handCancel}  width={685} >
          <CompanyAddEdit company={companyInfo} superiorUnitData={editSuperiorCompanyList} parentform={form} submit={this.handleSubmit} {...this.props} />
        </SimpleModal>
      </span>
    );
  }
}

EditCompany.propTypes = {
  text: PropTypes.string,
  reload: PropTypes.func,
  selectRows: PropTypes.array,
  companyInfoAction: PropTypes.func,
  superiorUnitEditAction: PropTypes.func,
  companyEditAction: PropTypes.func,
  editSuperiorCompanyList: PropTypes.any,
  companyInfo: PropTypes.any,
  form: PropTypes.any
};

EditCompany.defaultProps = {
  selectRows: []
};

export default createForm(EditCompany);
