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 = pathMapping.editRoute;
const routePointUrl = pathMapping.routePoint;
const newRoute = pathMapping.newRoute;
const editRouteUrlxq = pathMapping.editRoutexq;

  const dropnavs1 ={ key: '1', text: '新增', icon: 'add', href: newRoute, 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 dropnavs4 ={ key: '4', text: '路线巡检点', icon: 'ccgl-chukucaozuo-13' , href: 'jacascript::void(0)', permissionCode: 'route', isWriteable: false };
  const dropnavs5 ={ key: '5', text: '明细', icon: 'edit' , href: 'jacascript::void(0)', permissionCode: 'route', 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: 'boss',
    //   key: 'boss',
    //   width: 100,
    //   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;

    dropnavs.push(dropnavs4);
     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 }
    };
    browserHistory.push(path);
  }

  onClickBootBar = type => {
    if (type === '2') {
      this.editRoute();
    } else if (type === '3') {
      this.deleteRoute();
    } else if (type === '4') {
      this.handleRoute();
    }else if(type === '1'){
      let curNavs = dropnavs.filter(item => item.key == type);
      browserHistory.push(curNavs[0].href);
    }else if (type === '5') {
      this.editRoutexq();
    }
  };

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

  /**
   * 获取表格所选则的行数据
   */
  getSelectedRows = (selectedRows, selectedRowKeys) => {
    selectedRowKeys = [];
    selectedRows.forEach(element => {
      selectedRowKeys.push(element.id);
    });
    this.setState({ selectedRows, selectedRowKeys });
  }

  /**
   *根据条件查询检查项
   */
  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 => {
    //   if (data) {
    //     this.setState({ data: data.content, count: data.totalElements });
    //   }
    // });
  }

  /**
   * 删除已经选择的检查项
   */
  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==='FAILURE'){

              AmosAlert.error('提示', "路线上已设置巡检点或计划线路在使用！");
            }else{
              AmosAlert.success('提示', '删除成功', {
                callback: () => {
                  // this.reloadRoute(this.pageConfig);
                  this.state.reload();
                }
              });

            }

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

  /**
   * 跳转到跟新检查项页面
   */
  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 }
    };
    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 }
    };
    browserHistory.push(path);
  }











  /**
   * 路线巡检点
   */
  handleRoute = () => {
    let { selectedRowKeys, selectedRows } = this.state;
    if (selectedRowKeys === undefined ||  selectedRowKeys.length <= 0 ) {
      AmosAlert.warning('提示', '请先点击选择需要查看的路线');
      return;
    }
    if (selectedRows.length > 1) {
      AmosAlert.warning('提示', '至多选择一个需要查看的路线');
      return;
    }
    let id = selectedRowKeys[0];
    const path = {
      pathname: routePointUrl,
      state: { routeId: id }
    };
    browserHistory.push(path);
  }

  /**
   * 获取表格刷新方法
   */
  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;
