import React, { Component } from 'react';
import { Form, Input, AmosAlert, Button, Select } from 'amos-framework';
import { browserHistory } from 'amos-react-router';
import { TreeSelect } from 'amos-antd';
import './../../../styles/view/patrol/inputItem.scss';
import {
  updateRouteAction,
  queryRouteDetailAction,
  queryDeptByOrgCodeAction,
  queryUserByDeptIdAction,
  queryDeptUserTree
} from '../../../services/checkService';
import HasPermission from './../../component/toolbar/hasPermission';

const TextArea = Input.TextArea;
const FormItem = Form.Item;
const Option = Select.Option;

class EditRoute extends Component {
  constructor(props) {
    super(props);
    this.state = {
      form: {
        id: '',
        name: '',
        remark: '',
        tel: '',
        boss: '',
        deptId: '',
        userId: ''
      },
      rules: {
        name: [{ required: true, message: '请输入检查项名称' }],
        tel: [
          {
            validator: (rule, value, callback) => {
              var reg = /^1[0|1|2|3|4|5|7|8|9][0-9]\d{4,8}$/;
              if (reg.test(value) || !value) {
                callback();
              } else {
                callback(new Error('正确的手机电话号码'));
              }
            }
          }
        ]
      },
      userData: [],
      deptData: [],
      executors: []
    };
  }

  /**
   * 组件初始化时调用
   */
  componentWillMount = () => {
    const { routeId } = (this.props.location || {}).state || {};
    routeId && this.onInit(routeId);
  };

  onInit = id => {
    
    queryRouteDetailAction(id).then(data => {
      let deptId = data.deptId;
      deptId && this.queryUserByDept(deptId);
      this.setState({ form: data });
    });
    this.loadexecutor();
    this.queryDeptByOrgCode();
  };

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

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

  queryDeptByOrgCode = () => {
    queryDeptByOrgCodeAction().then(data => {
      this.setState({ deptData: data });
    });
  };

  queryUserByDept = deptId => {
    queryUserByDeptIdAction(deptId).then(data => {
      this.setState({ userData: data });
    });
  };

  handleSubmit = e => {

    this.form.validate((valid, dataValues) => {
      if (valid) {
        const { form } = this.state;
        let requestBody = Object();
        Object.assign(requestBody, form);
        updateRouteAction(requestBody).then(
          data => {
            AmosAlert.success('提示', '保存成功');
            browserHistory.goBack('/main/patrol/route');
          },
          error => {
            AmosAlert.error('错误', '保存失败');
          }
        );
      } else {
        console.log('error submit!!');
        return false;
      }
    });
  };

  loadexecutor = () => {
    queryDeptUserTree().then(data => {
      let deptPersons = data.filter(item => item.children !== null);
      this.setState({ executors: deptPersons });
    });
  };

  // handleExecutorsChange_bak = (executorList, label, extra) => {
  //   let pro = label.props;
  //   const { form } = this.state;
  //   if (pro.children || pro.type === 'department') {
  //     form.boss = '';
  //   } else {
  //     form.boss = pro.id;
  //     form.tel = pro.name;
  //   }

  //   this.setState({ form });
  // };

  handleExecutorsChange = (id, user) => {
    const { form } = this.state;

    form.boss = user.id;
    form.tel = user.name;

    this.setState({ form });
  };

  handleCancel = e => {
    browserHistory.goBack('/main/patrol/route');
  };

  render() {
    const { form, rules, deptData, userData, executors } = this.state;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
        className: 'colspanlab'
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
        className: 'colspan'
      }
    };
    const wrapperCol = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 14, offset: 4 }
      }
    };
    const def = true;
    return (
      <div className="input_item_div">
        <Form model={form} rules={rules} ref={component => this.form = component}>
          <FormItem label={<span>路线名称</span>} field="name" {...formItemLayout}>
            <Input className="input_item_Input" value={form.name} maxLength = "50" onChange={e => this.onChange('name', e.target.value)} />
          </FormItem>
          {
          // <FormItem label={<span>负责人</span>} field="boss" {...formItemLayout}>
          //   <TreeSelect
          //     className="input_item_Input"
          //     showSearch
          //     treeData={executors}
          //     dropdownStyle={{ height: 150, overflow: 'auto' }}
          //     onSelect={this.handleExecutorsChange}
          //     // treeCheckable={def}
          //     treeIcon={def}
          //     // multiple={  }
          //     value={form.boss}
          //     treeLine={def}
          //     style={{ width: 286 }}
          //     showCheckedStrategy={TreeSelect.SHOW_CHILD}
          //     placeholder="请选择"
          //     treeNodeFilterProp="id"
          //     treeNodeLabelProp="title"
          //     treeDefaultExpandAll
          //   />
          // </FormItem>
          }
          <FormItem label={<span>责任部门</span>} field="deptId" {...formItemLayout}>
            <Select
              className="input_item_Input"
              searchable
              data={deptData ? deptData : []}
              renderOption={item => <Option value={parseInt(item.id)}>{item.name}</Option>}
              value={form.deptId}
              onChange={e => this.onDeptChange('deptId', e)}
            />
          </FormItem>
          <FormItem label={<span>责任人</span>} field="boss" {...formItemLayout}>
            <Select
              className="input_item_Input"
              searchable
              data={userData}
              renderOption={item => <Option value={parseInt(item.id)}>{item.name}</Option>}
              value={parseInt(form.boss)}
              onChange={this.handleExecutorsChange}
            />
          </FormItem>
          <FormItem label={<span>联系电话</span>} field="tel" {...formItemLayout}>
            <Input value={form.tel} className="input_item_Input" onChange={e => this.onChange('tel', e.target.value)} />
          </FormItem>
          <FormItem label={<span>备注说明</span>} field="remark" {...formItemLayout}>
            <TextArea className="input_item_Input" value={form.remark} rows={6} disableResize onChange={e => this.onChange('remark', e.target.value)} />
          </FormItem>
          <FormItem {...wrapperCol}>
            <HasPermission permissionCode="route">
              <Button onClick={this.handleSubmit}>提交</Button>
            </HasPermission>
            <Button onClick={this.handleCancel}>返回</Button>
          </FormItem>
        </Form>
      </div>
    );
  }
}

EditRoute.propTypes = {};

export default EditRoute;
