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 { saveRouteAction, 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 NewRoute extends Component {
  constructor(props) {
    super(props);
    this.state = {
      form: {
        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 = () => {
    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 });
  };

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

  queryDeptByOrgCode = () => {

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

  queryUserByDept = deptId => {

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

  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="title"
          //     treeNodeLabelProp="title"
          //     treeDefaultExpandAll
          //   />
          // </FormItem>
        }
          <FormItem label={<span>责任部门1</span>} field="deptId" {...formItemLayout}>
            <Select
              className="input_item_Input"
              searchable
              data={deptData}
              renderOption={item => <Option value={item.id}>{item.name}</Option>}
              defaultValue={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={item.id}>{item.name}</Option>}
              defaultValue={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" 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>
    );
  }
}

NewRoute.propTypes = {};

export default NewRoute;
