import React, { Component } from 'react';
import { AmosAlert } from 'amos-framework';
import { browserHistory } from 'amos-react-router';
import PropTypes from 'prop-types';
import BootBar from '../../component/toolbar';
import AmosGridTable from '../../component/table/table/AmosGridTable';
import { pathMapping } from './../../../routes/customRoutes';
import { queryRouteAction, batchDelRouteAction,btnAuthAction } from '../../../services/checkService';
const editRouteUrl = ()=>{
  return pathMapping.editRoute;
};

const editRouteUrlxq = ()=>{
  return pathMapping.editRoutexq;
};



  const dropnavs1 = { key: '1', text: '新增', icon: 'add', href: '/main/patrol/editRoute', permissionCode: 'route', isWriteable: true };
  const dropnavs2 = { key: '2', text: '修改', icon: 'edit' , href: 'jacascript::void(0)', permissionCode: 'route', isWriteable: true };
  const dropnavs3 = { key: '3', text: '删除', icon: 'delete', href: 'jacascript::void(0)', permissionCode: 'route', isWriteable: true };
  const dropnavs5 ={ key: '5', text: '明细', icon: 'edit' , href: 'jacascript::void(0)', permissionCode: 'route', isWriteable: true };

// { key: '1', text: '新增', icon: 'add', href: '/main/patrol/pointInfo',  permissionCode: 'point', isWriteable: true },
const getColumns = () =>{
  return [
    {
      title: '路线编号',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      className: 'uant-table-thead'
    },{
      title: '路线名称',
      dataIndex: 'name',
      key: 'name',
      width: 180,
      className: 'uant-table-thead'
    },{
      title: '责任部门',
      dataIndex: 'deptName',
      key: 'deptName',
      width: 130,
      className: 'uant-table-thead'
    },{
      title: '责任人',
      dataIndex: 'boss',
      key: 'boss',
      width: 100,
      className: 'uant-table-thead'
    },{
      title: '联系电话',
      dataIndex: 'tel',
      key: 'tel',
      width: 130,
      className: 'uant-table-thead'
    },{
      title: '备注说明',
      dataIndex: 'remark',
      key: 'remark',
      width: 300,
      className: 'uant-table-thead'
    }
  ];
};

/**
 * 路线列表
 *
 * @class RouteTable
 * @extends {Component}
 */
class RouteTable extends Component{
  constructor(props) {
    super(props);
    this.pageConfig = {
      pageNumber: 0,
      pageSize: 10
    },
    this.state = {
      pagination: true,
      isChecked: true,
      selectedRows: [],
      selectedRowKeys: [],
      data: [],
      count: 0,
      pageConfig: {
        pageNumber: 0,
        pageSize: 10
      },
      requestParam: [],
      dropnavs:[]
    };
  }
  /**
   * 组件初始化调用
   */
  componentWillMount = () => {
    this.reloadButtonAuth();
  }

  reloadButtonAuth = () => {
    // const _path = this.calcRoutes();
    btnAuthAction('/main/patrol/route').then(data => {
      
      let { dropnavs } = this.state;
     if(data){
  
       if("xz" in data&&data.xz.hasPermission){
        
        dropnavs.push( dropnavs1);
       }
       if("xg" in data&&data.xg.hasPermission){
        dropnavs.push( dropnavs2);
  
      }
      if("sc" in data&&data.sc.hasPermission){
        dropnavs.push( dropnavs3);
  
      }
      if("mx" in data&&data.mx.hasPermission){
        dropnavs.push( dropnavs5);
  
      }
      
     }
  
      this.setState({ dropnavs});
    });
  }
  /**
   * 接受新的属性时回调
   */
  componentWillReceiveProps = (nextProps) => {
    let { changeType, queryParam } = nextProps;
    if ('query' === changeType) {
      let request = new Array();
      if (queryParam) {
        for (let key in queryParam) {
          let obj = new Object();
          obj.name = queryParam[key].name;
          obj.type = queryParam[key].type;
          obj.value = queryParam[key].value;
          request.push(obj);
        }
      }
      this.setState({ requestParam: request }, () => this.reloadRoute(this.pageConfig));
    }
  }

  onRowDoubleClick =(record, index, event) => {
    let path = {
      pathname: editRouteUrl(),
      state: { routeId: record.id, forword: 'edit' }
    };
    browserHistory.push(path);
  }

  onClickBootBar = type => {
    if (type === '2') {
      this.editRoute();
    } else if (type === '3') {
      this.deleteRoute();
    }else if (type === '5') {
      this.editRoutexq();
    }
  };
  /**
   * 获取表格所选则的行数据
   */
  getSelectedRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  /**
   * 分页设置参数
   */
  setPageConfig = ({ pageSize, current }) => {
    if (pageSize !== undefined) {
      this.pageConfig.pageSize = pageSize;
    }
    if (current !== undefined) {
      this.pageConfig.pageNumber = current;
    }
  }


  /**
   * 跳转到主页面（新增及编辑共用一个页面）
   */
  addRoute =() => {
    const path = {
      pathname: editRouteUrl(),
      state: { forword: 'add' }
    };
    browserHistory.push(path);
  }

  /**
   * 跳转到主页面（新增及编辑共用一个页面）
   */
  editRoute = () => {
    const { selectedRows } = this.state;
    if (selectedRows === undefined || selectedRows.length <= 0 ) {
      AmosAlert.warning('提示', '请先点击选择需要编辑的行');
      return;
    }
    if (selectedRows.length > 1) {
      AmosAlert.warning('提示', '至多选择一条需要编辑的行');
      return;
    }
    let row = selectedRows[0];
    const path = {
      pathname: editRouteUrl(),
      state: { routeId: row.id, forword: 'edit' }
    };
    browserHistory.push(path);
  }




  editRoutexq = () => {
    const { selectedRows } = this.state;
    if (selectedRows === undefined || selectedRows.length <= 0 ) {
      AmosAlert.warning('提示', '请先点击选择需要编辑的行');
      return;
    }
    if (selectedRows.length > 1) {
      AmosAlert.warning('提示', '至多选择一条需要编辑的行');
      return;
    }
    let row = selectedRows[0];
    const path = {
      pathname: editRouteUrlxq(),
      state: { routeId: row.id, forword: 'edit' }
    };
    browserHistory.push(path);
  }
    /**
   * 删除已经选择的路线
   */
  deleteRoute = () => {
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys === undefined ||  selectedRowKeys.length <= 0 ) {
      AmosAlert.warning('提示', '请先点击选择需要删除的行');
      return;
    }
    let ids = selectedRowKeys.join(',');

    AmosAlert.confirm('提示', '是否删除?', {
      callback: (flag) => {
        if (flag){
          // 确定删除
          batchDelRouteAction(ids).then(data => {
            if(data===null){

              AmosAlert.success('提示', '删除成功', {
                callback: () => {
                  // this.reloadRoute(this.pageConfig);
                  this.state.reload();
                }
              });
            }else{
              AmosAlert.error('提示', data.message);
             

            }
          }, err => {
            AmosAlert.error('错误', err);
          });
        }
      }
    });
  }


  /**
   *根据条件查询路线
   */
  reloadRoute = (pageParam) => {
    let { requestParam } = this.state;
    let { pageSize } = pageParam;
    let pageNumber = 0;
    this.setState({ selectedRows: [], selectedRowKeys: [] });
    if (pageParam.current !== null && !isNaN(pageParam.current)) {
      pageNumber = pageParam.current;
    }
    queryRouteAction(requestParam, pageNumber, pageSize).then(data => {
      this.setState({ data: data.content, count: data.totalElements });
    });
  }

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

  render() {
    let { pagination, isChecked, data, count, selectedRowKeys ,dropnavs} = this.state;
    let defaultPageConfig = this.pageConfig;
    return (
      <div className="patrol-page-table">
        <BootBar dropnavs={dropnavs} callBack={this.onClickBootBar} />
        <AmosGridTable
          rowKey="id"
          columns={getColumns()}
          isPageable={pagination}
          isChecked={isChecked}
          dataList={data}
          totals={count}
          callBack={this.reload}
          selectedRowKeys={selectedRowKeys}
          getTableDataAction={this.reloadRoute}
          getSelectedRows={this.getSelectedRows}
          setPageConfig={this.setPageConfig}
          defaultPageConfig={defaultPageConfig}
          onRowDoubleClick={this.onRowDoubleClick}
        />
      </div>
    );
  }
}

RouteTable.propTypes = {
  changeType: PropTypes.string,
  queryParam: PropTypes.object
};

export default RouteTable;
