import React, { Component } from 'react';
import { TreeSelect } from 'amos-antd';
import { Form, AmosAlert, Input, Button } from 'amos-framework';
import { browserHistory } from 'amos-react-router';
import { queryCatalogTreeAction, queryCatalogTreeByIdAction, addCatalogTreeAction } from '../../../services/checkService';
import { pathMapping } from './../../../routes/customRoutes';
import HasPermission from './../../component/toolbar/hasPermission';

const FormItem = Form.Item;
const catalogTreeUrl = () => pathMapping.catalogTree;

class CatalogTreeInput extends Component {
  constructor(props) {
    super(props);
    this.state = {
      form: {
        name: '',
        parentId: ''
      },
      treeData: [],
      rules: {
        name: [{ required: true, message: '请输入分类名称' }]
      }
    };
  }

  componentWillMount = () => {
    this.queryCatalogTree();
    const { id } = (this.props.location || {}).state || {};
    id && this.onInit(id);
  };

  onInit = id => {
    queryCatalogTreeByIdAction(id).then(data => {
      this.setState({ form: data });
    });
  };

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

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

  queryCatalogTree = () => {
    queryCatalogTreeAction().then(data => {
      let treeData = data;
      data.push({ key: '0', value: '0', label: '', children: [] });
      console.log('queryCatalogTree', data);
      this.setState({ treeData });
    });
  };

  handleSubmit = e => {
    this.form.validate((valid, dataValues) => {
      if (valid) {
        let { form } = this.state;
        addCatalogTreeAction(form).then(
          data => {
            if (data === null) {
              AmosAlert.success('提示', '保存成功');
            } else {
              AmosAlert.error('提示', '添加分类失败：目录名称已存在');
            }
            browserHistory.goBack(catalogTreeUrl());
          },
          err => {
            AmosAlert.error('错误', err);
          }
        );
      } else {
        return false;
      }
    });
  };

  handleCancel = e => {
    browserHistory.goBack(catalogTreeUrl());
  };

  render() {
    const { form, treeData, rules } = this.state;
    console.log('form', form);
    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 }
      }
    };

    return (
      <div className="plan_edit_div">
        <Form model={form} rules={rules} ref={component => (this.form = component)}>
          <FormItem label={<span>上级目录</span>} field="parentId" {...formItemLayout}>
            <TreeSelect
              value={form.parentId == 0 ? '' : form.parentId}
              className="plan_info_input"
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeData={treeData}
              placeholder="请选择"
              allowClear
              treeDefaultExpandAll
              onChange={e => this.onSelectChange('parentId', e)}
            />
          </FormItem>
          <FormItem label={<span>目录名称</span>} field="name" {...formItemLayout}>
            <Input value={form.name} className="plan_info_input" onChange={e => this.onChange('name', e)} />
          </FormItem>
          <FormItem {...wrapperCol}>
            <HasPermission permissionCode="catalogtree">
              <Button onClick={this.handleSubmit}>提交</Button>
            </HasPermission>
            <Button onClick={this.handleCancel}>返回</Button>
          </FormItem>
        </Form>
      </div>
    );
  }
}

export default CatalogTreeInput;
