import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { AmosAlert, Button } from 'amos-framework';
import { browserHistory } from 'amos-react-router';
import AmosGridTable from './../../../common/tableComponent/table/AmosGridTable';
import FireTruckToolBar from './fireTruckToolBar';
import { deleteFireTruckAction, addFireTruckAction } from './../../../../../services/ledgerService';
import { pathMapping } from './../../../../../routes/customRoutes';

const fireTruckInfoPath = pathMapping.firetruckinfo;

const fireTruckTableColumns = self => {
  return [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}`
    },
    {
      title: '所属部门',
      dataIndex: 'departmentName',
      key: 'departmentName',
      width: '12%'
    },
    {
      title: '车辆类型',
      dataIndex: 'type',
      key: 'type',
      width: '15%'
    },
    {
      title: '车辆名称',
      dataIndex: 'name',
      key: 'name',
      width: '10%'
    },
    {
      title: '车牌号',
      dataIndex: 'carNum',
      key: 'carNum',
      width: '10%'
    },
    {
      title: '发动机号',
      dataIndex: 'engineNum',
      key: 'engineNum',
      width: '10%'
    },
    {
      title: '厂牌型号',
      dataIndex: 'model',
      key: 'model',
      width: '10%'
    },
    {
      title: '国别',
      dataIndex: 'country',
      key: 'country',
      width: '10%'
    },
    {
      title: '车辆状态',
      dataIndex: 'state',
      key: 'state',
      width: '10%'
    },
    {
      title: '操作',
      dataIndex: '',
      key: 'operation',
      width: '5%',
      render: (text, record, index) => {
        return (
          <span>
            <a href="javascript:;" onClick={() => {self.onDetailClick(record);}}>查看</a>
          </span>
        );
      }
    }
  ];
};

const defaultHeight = 580;

/**
 * 消防车列表
 */
class FireTruckView extends Component {
  constructor(props) {
    super(props);

    this.pageConfig = {
      pageNumber: 0,
      pageSize: 10
    },
    this.state = {
      pagination: true,
      selectedRows: [],
      selectedRowKeys: [],
      dataList: [], //表格数据集合
      size: 'small', //表格大小
      searchParam: [],
      totals: 0, //所有数据总和
      requestParam: [],
      truckInfo: {},  //消防车id
      operateFlag: 0  //操作按钮0：新增，1：修改/查看
    };
  }

  onDetailClick = record => {
    let path = {
      pathname: fireTruckInfoPath,
      state: { fireCarId: record.id }
    };
    browserHistory.push(path);
  };

  onRowClick = record => {
    let { selectedRowKeys, selectedRows } = this.state;
    let exist = false;
    selectedRows.find(item => {
      if (item.id === record.id) {
        exist = true;
      }
    });
    if (exist) {
      selectedRows.splice(selectedRows.findIndex(item => item.id === record.id), 1);
      selectedRowKeys.splice(selectedRowKeys.findIndex(item => item === record.id), 1);
    } else {
      selectedRows.push(record);
      selectedRowKeys.push(record.id);
    }
    this.setState({
      selectedRows,
      selectedRowKeys
    });
  }

  getPanelHeight = () => {
    return defaultHeight;
  };

  setPageConfig = ({ pageSize, current }) => {
    if (pageSize !== undefined) {
      this.pageConfig.pageSize = pageSize;
    }
    if (current !== undefined) {
      this.pageConfig.current = current;
    }
  };

  getRowClassName = (record, index) => {
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys.findIndex(item => item === record.id) >= 0) {
      return 'highlight-row';
    } else {
      return 'normal-row';
    }
  };

  getSelectedRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };


  /**
   * 获取表格刷新方法
   */
  reload = r => {
    this.setState(
      {
        reload: () => {
          r();
          this.setState({ selectedRows: [], selectedRowKeys: [] });
        }
      },
      r()
    );
  };

  add() {
    let path = {
      pathname: fireTruckInfoPath,
      state: { toolbarFlag: 0 }
    };
    browserHistory.push(path);
  };

  edit() {
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys === undefined || selectedRowKeys.length <= 0) {
      AmosAlert.warning('提示', '请先选择需要编辑的设备');
      return;
    }

    let fireCarId = selectedRowKeys;
    if (selectedRowKeys.length > 1) {
      fireCarId = selectedRowKeys[selectedRowKeys.length - 1];
    }

    let path = {
      pathname: fireTruckInfoPath,
      state: {
        toolbarFlag: 1,
        fireCarId: fireCarId }
    };
    browserHistory.push(path);
  }

  delete() {
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys === undefined || selectedRowKeys.length <= 0) {
      AmosAlert.warning('提示', '请先选择需要删除的消防车');
      return;
    }
    AmosAlert.confirm('提示', '确定删除指定消防车?', {
      callback: flag => {
        if (flag) {
          // 确定删除
          let ids = selectedRowKeys.join(',');
          deleteFireTruckAction(ids).then(
            data => {
              AmosAlert.success('提示', '删除成功');
              this.state.reload();
            },
            err => {
              AmosAlert.error('错误', err);
            }
          );
        }
      }
    });
  }

  getToolButton = () => {
    let buttonArr = new Array();
    buttonArr.push(<Button onClick={() => this.add()} icon="add" />);
    buttonArr.push(<Button onClick={() => this.edit()} icon="edit" />);
    buttonArr.push(<Button onClick={() => this.delete()} icon="delete" />);
    return buttonArr;
  }


  render() {
    let { selectedRowKeys } = this.state;
    let { dataList, totalCount, getTableListData } = this.props;
    let _true_ = true;
    return (
      <div className="fire-resource-truck" style={{ background: '#33333', height: '100%' }}>
        <FireTruckToolBar add={() => this.add()} delete={() => this.delete()} edit={() => this.edit()} getTableListData={getTableListData} pageConfig={this.pageConfig} />
        <AmosGridTable
          rowKey="id"
          columns={fireTruckTableColumns(this)}
          callBack={this.reload}
          dataList={dataList}
          totals={totalCount}
          getTableDataAction={param => getTableListData(param, this)}
          getSelectedRows={this.getSelectedRows}
          rowClassName={this.getRowClassName}
          setPageConfig={this.setPageConfig}
          getPanelHeight={this.getPanelHeight}
          defaultPageConlHeight={this.getPanelHeight}
          isChecked={_true_}
          selectedRowKeys={selectedRowKeys}
          onRowClick={this.onRowClick}
        />
      </div>
    );
  }
}

FireTruckView.propTypes = {
  totalCount: PropTypes.number,
  dataList: PropTypes.array,
  getTableListData: PropTypes.func
};
export default FireTruckView;
