import React, { Component } from 'react';
import { Checkbox, Button, AmosAlert } from 'amos-framework';
import PropTypes from 'prop-types';
import { queryPointInputItemAction } from '../../../services/checkService';
import { getRoutePointInputItemAction, updateRoutePointInputItemAction } from '../../../services/routeService';
import HasPermission from '../../component/toolbar/hasPermission';

const CheckboxGroup = Checkbox.Group;

/**
 * 巡检项
 *
 * @class RoutePoint
 * @extends {Component}
 */
class PointInputItem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      treeData: [],
      defaultSelects: [],
      selects: []
    };

    this.handleSubmit = this.handleSubmit.bind(this);
  }

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

  componentWillReceiveProps = nextProps => {
    const { pointId } = nextProps;
    pointId && this.onInit(pointId);
  };

  onInit = pointId => {
    const { routeId } = this.props;
    queryPointInputItemAction(pointId).then(data => {
      this.setState({ treeData: data });
      let defaultSelects = [];
      data.map(item => {
        defaultSelects.push(item.id);
      });
      this.setState({ defaultSelects });
    });

    routeId &&
      getRoutePointInputItemAction(routeId, pointId).then(data => {
        let selects = [];
        data.map(item => {
          selects.push(item.id);
        });
        this.setState({ selects });
      });
  };

  onSelectChange(selects) {
    this.setState({
      selects
    });
  }

  handleSubmit() {
    let { selects } = this.state;
    const { routeId, pointId } = this.props;
    if (pointId === undefined) {
      return;
    }
    updateRoutePointInputItemAction(routeId, pointId, selects).then(
      data => {
        AmosAlert.success('提示', '保存成功');
      },
      error => {
        AmosAlert.error('错误', '保存失败');
      }
    );
  }

  renderTreeNodes = data => {
    return data.map(item => {
      return <Checkbox key={Math.random()} value={item.id}>{item.name}</Checkbox>;
    });
  };

  render() {
    let { selects, treeData, defaultSelects } = this.state;
    return (
      <div>
        <CheckboxGroup vertical defaultSelects={defaultSelects} isCheckall selects={selects} onChange={selects => this.onSelectChange(selects)}>
          {this.renderTreeNodes(treeData)}
        </CheckboxGroup>
        <div>
          <HasPermission permissionCode="route">
            <Button onClick={this.handleSubmit}>保存</Button>
          </HasPermission>
        </div>
      </div>
    );
  }
}

PointInputItem.propTypes = {
  pointId: PropTypes.number,
  routeId: PropTypes.number
};

export default PointInputItem;
