import React, { Component } from 'react';
import PropTypes from 'prop-types';
import _amosTool from 'amos-tool';
import SysConsts from 'amos-processor/lib/config/consts';
import formatUrl from 'amos-processor/lib/utils/urlFormat';
import { AmosAlert } from 'amos-framework';
import { browserHistory } from 'amos-react-router';
import BootBar from './../../component/toolbar';
import AmosGridTable from './../../component/table/table/AmosGridTable';
import { pathMapping } from './../../../routes/customRoutes';
import { getPointListAction, saveAsPointAction, deletePointAction } from '../../../services/pointService';
import { patrolUrls } from './../../../consts/urlConsts';
import {btnAuthAction} from '../../../services/checkService';
const ls = _amosTool.Store.lsTool;
const apiKey = SysConsts.api_key;
const token = SysConsts.token;

const pointInfoEdit = () => pathMapping.pointInfoEdit;
const pointInfoEditxq = () => pathMapping.pointInfoEditxq;
const checkUrl = () =>  pathMapping.check;
const importPoint = () => pathMapping.importPoint;
// const pointInfo = () => pathMapping.pointInfo;
const isFixedEnum = { 1: '是', 0: '否' };

  const dropnavs1 ={ key: '1', text: '新增', icon: 'add', href: '/main/patrol/pointInfo',  permissionCode: 'point', isWriteable: true };
  const dropnavs2 ={ key: '2', text: '修改', icon: 'edit', href: 'jacascript::void(0)', permissionCode: 'point', isWriteable: true };
  const dropnavs3 ={ key: '3', text: '另存', icon: 'save', href: 'jacascript::void(0)', permissionCode: 'point', isWriteable: true };
  const dropnavs4 ={ key: '4', text: '删除', icon: 'delete', href: 'jacascript::void(0)', permissionCode: 'point', isWriteable: true };
  const dropnavs5 ={ key: '5', text: '巡检记录', icon: 'history', href: 'jacascript::void(0)', permissionCode: 'point', isWriteable: false };
  const dropnavs6 ={ key: '6', text: '导入', icon: 'fat-menu-fold', href: 'jacascript::void(0)', permissionCode: 'point', isWriteable: true };
  const dropnavs7 ={
    key: '7',
    text: '导出',
    icon: 'history',
    href: 'jacascript::void(0)',
    subSys: [
      { key: '7-1', text: '选中数据', href: 'jacascript::void(0)', permissionCode: 'point', isWriteable: false },
      { key: '7-2', text: '全部数据', href: 'jacascript::void(0)', permissionCode: 'point', isWriteable: false },
      { key: '7-3', text: '选中卫士码', href: 'jacascript::void(0)', permissionCode: 'point', isWriteable: false },
      { key: '7-4', text: '全部卫士码', href: 'jacascript::void(0)', permissionCode: 'point', isWriteable: false }
    ]
  };
  const dropnavs8 ={ key: '8', text: '明细', icon: 'edit', href: 'jacascript::void(0)', permissionCode: 'point', isWriteable: true };

  

const pointColumns = () => {
  return [
    {
      title: '点编号',
      dataIndex: 'pointNo',
      key: 'pointNo',
      width: 100,
      query: true,
      required: true, //是否是默认显示的
      primary: true, //是否出现在模糊搜索文本框中
      st: 'text' //搜索的类型
    },
    {
      title: '点名称',
      dataIndex: 'name',
      key: 'name',
      width: 180,
      query: true,
      required: true, //是否是默认显示的
      primary: true, //是否出现在模糊搜索文本框中
      st: 'text' //搜索的类型
    },
    {
      title: '固定点',
      dataIndex: 'isFixed',
      key: 'isFixed',
      query: true,
      required: true, //是否是默认显示的
      primary: true, //是否出现在模糊搜索文本框中
      st: 'text', //搜索的类型
      width: 80,
      render: text => isFixedEnum[text] ? isFixedEnum[text] : text
    },
    {
      title: '拍照数量',
      dataIndex: 'shotNumber',
      key: 'shotNumber',
      width: 80
    },
    // {
    //   title: '巡检路线',
    //   dataIndex: 'routeName',
    //   key: 'routeName',
    //   width: '20%'
    // },
    // {
    //   title: '检查项目',
    //   dataIndex: 'inputItemName',
    //   key: 'inputItemName',
    //   width: 250
    // },
    {
      title: '扩展分类',
      dataIndex: 'classifyName',
      key: 'classifyName',
      width: 180
    },
    {
      title: '分类目录',
      dataIndex: 'catalogName',
      key: 'catalogName',
      width: 100
    }
  ];
};

const getHeaders = () => {
  return {
    'Accept': 'application/json;charset=UTF-8',
    'Content-Type': 'application/json; charset=utf-8',
    'X-Api-Key': _amosTool.Store.getCookieByName(apiKey),
    'X-Access-Token': ls.read(token),
    'token': ls.read(token),
    'appKey': 'YH-PATROL',
    'product': 'YH-PATROL_WEB'
  }
}

/**
 * 巡检点列表视图组件
 */
class PointTable extends Component {
  constructor(props) {
    super(props);

    this.pageConfig = {
      pageNumber: 0,
      pageSize: 10
    },
    this.state = {
      pagination: true,
      isChecked: true,
      selectedRows: [],
      selectedRowKeys: [],
      dataList: [], //表格数据集合
      size: 'small', //表格大小
      searchParam: [],
      totals: 1, //所有数据总和
      requestParam: [],
      dropnavs:[]
    };
    this.reloadPointList = this.reloadPointList.bind(this);
  }

  componentWillMount() {
    this.reloadButtonAuth();
  }
  reloadButtonAuth = () => {
    // const _path = this.calcRoutes();
    btnAuthAction('/main/patrol/point').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("lc" in data&&data.lc.hasPermission){
        dropnavs.push( dropnavs3);
  
      }
      if("sc" in data&&data.sc.hasPermission){
        dropnavs.push( dropnavs4);
  
      }
      if("xjjl" in data&&data.xjjl.hasPermission){
        dropnavs.push( dropnavs5);
  
      }
      if("dr" in data&&data.dr.hasPermission){
        dropnavs.push( dropnavs6);
  
      }
      if("dc" in data&&data.dc.hasPermission){
        dropnavs.push( dropnavs7);
  
      }
      if("mx" in data&&data.mx.hasPermission){
        dropnavs.push( dropnavs8);
  
      }
      
     }
  
      this.setState({ dropnavs});
    });
  }
  componentWillReceiveProps(nextProps) {
    let { operationType, queryParam } = nextProps;

    if ('query' === operationType) {
      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.reloadPointList(this.pageConfig));
    }
  }

  onRowClick = (record, index) => {
    // AmosAlert.info('提示', record);
  };

  onRowDoubleClick =(record, index, event) => {
    let path = {
      pathname: pointInfoEdit(),
      state: { pointId: record.id }
    };
    browserHistory.push(path);
  }

  onClickBootBar = type => {
    if (type === '2') {
      this.updatePoint();
    } else if (type === '3') {
      this.saveAs();
    } else if (type === '4') {
      this.deletePoint();
    } else if (type === '5') {
      this.checkInfoForward();
    } else if (type === '6') {
      let path = {
        pathname: importPoint()
      };
      browserHistory.push(path);
    } else if (type === '7') {
      AmosAlert.info('info', '选中数据');
    } else if (type === '7-2') {
      this.exportAllData(0);
    }  else if (type === '7-1') {
      this.exportSelectedData(0);
    } else if (type === '7-3') {
      this.exportSelectedData(1);
    } else if (type === '7-4') {
      this.exportAllData(1);
    }else if (type === '8') {
      this.updatePointxq();
    }
  };

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

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

  exportSelectedData = (exportType) => {
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys === undefined ||  selectedRowKeys.length <= 0 ) {
      AmosAlert.warning('提示', '请先选择需要导出的行');
      return;
    }
    let ids = selectedRowKeys.join(',');
    let url = formatUrl(patrolUrls.exportSelectedPointListUrl, { ids, exportType });
    fetch(url, {
      method: 'get',
      headers: getHeaders(),
    }).then((e) => {
      if (e.status === 200) {
        e.blob().then((blob) => {
          const a = window.document.createElement('a');
          const downUrl = window.URL.createObjectURL(blob);
          let currDate = new Date();
          let fileType = null;
          if (exportType === 0) {
            fileType = 'xls';
          } else {
            fileType = 'zip';
          }
          const filename = [currDate.getTime(), fileType];
          a.href = downUrl;
          a.download = `${decodeURI(filename[0])}.${filename[1]}`;
          a.click();
          window.URL.revokeObjectURL(downUrl);
        });
      } else {
        _amosTool.Log.error(e.message);
      }
    }).catch((e) => {
      _amosTool.Log.error(e.message);
    });
  }

  exportAllData = (exportType) => {
    let { requestParam } = this.state;
    let url = formatUrl(patrolUrls.exportListPointUrl, { exportType });
    let param = {};
    if (!requestParam) {
      param = new Array();param = new Array();
    } else {
      param = requestParam;
    }
    fetch(url, {
      method: 'post',
      headers: getHeaders(),
      body: JSON.stringify(param)
    }).then((e) => {
      if (e.status === 200) {
        e.blob().then((blob) => {
          const a = window.document.createElement('a');
          const downUrl = window.URL.createObjectURL(blob);
          let currDate = new Date();
          let fileType = null;
          if (exportType === 0) {
            fileType = 'xls';
          } else {
            fileType = 'zip';
          }
          const filename = [currDate.getTime(), fileType];
          a.href = downUrl;
          a.download = `${decodeURI(filename[0])}.${filename[1]}`;
          a.click();
          window.URL.revokeObjectURL(downUrl);
        });
      } else {
        _amosTool.Log.error(e.message);
      }
    }).catch((e) => {
      _amosTool.Log.error(e.message);
    });
  }

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

  /**
   * 另存为选中的点
   */
  saveAs = () => {
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys === undefined || selectedRowKeys.length <= 0) {
      AmosAlert.info('提示', '请选择要另存为的点');
      return;
    }
    let ids = selectedRowKeys.join(',');
    AmosAlert.confirm('提示', '是否另存该点?', {
      callback: flag => {
        if (flag) {
          // 确定
          saveAsPointAction(ids).then(data => {
            AmosAlert.success('提示', '保存成功');
            // this.reloadPointList(this.pageConfig);
            this.state.reload();
          }, err => {
            AmosAlert.error('错误', err);
          });
        }
      }
    });
  };

  /**
   * 根据条件查询点
   *
   * @memberof PointTable
   */
  reloadPointList(pageParam) {
    let { requestParam } = this.state;
    let { pageSize } = pageParam;
    let pageNumber = 0;
    if (pageParam.current !== null && !isNaN(pageParam.current)) {
      pageNumber = pageParam.current;
    }
    getPointListAction(requestParam, pageNumber, pageSize).then(data => {
      this.setState({
        dataList: data.content,
        totals: data.totalElements,
        selectedRows: [],
        selectedRowKeys: []
      });
    });
  }

  /**
   * 删除选择的点
   *
   * @memberof PointTable
   */
  deletePoint() {
    let { selectedRowKeys } = this.state;

    if (selectedRowKeys === undefined || selectedRowKeys.length <= 0) {
      AmosAlert.warning('提示', '请选择要删除的巡检点');
      return;
    }
    let ids = selectedRowKeys.join(',');

    AmosAlert.confirm('提示', '是否删除?', {
      callback: flag => {
        if (flag) {
          // 确定删除
          deletePointAction(ids).then(data => {
            AmosAlert.success('提示', '删除成功');
            // this.reloadPointList(this.pageConfig);
            this.state.reload();
          }, err => {
            AmosAlert.error('错误', err);
          });
        }
      }
    });
  }

  updatePoint() {
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys === undefined || selectedRowKeys.length <= 0) {
      AmosAlert.warning('提示', '请选择要修改的点');
      return;
    }
    let row = selectedRowKeys[0];
    let path = {
      pathname: pointInfoEdit(),
      state: { pointId: row }
    };
    browserHistory.push(path);
  }


  updatePointxq() {
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys === undefined || selectedRowKeys.length <= 0) {
      AmosAlert.warning('提示', '请选择点');
      return;
    }
    let row = selectedRowKeys[0];
    let path = {
      pathname: pointInfoEditxq(),
      state: { pointId: row }
    };
    browserHistory.push(path);
  }


  checkInfoForward =()=>{
    const { selectedRows } = this.state;
    if (selectedRows === undefined || selectedRows.length <= 0 ) {
      AmosAlert.warning('提示', '请先点击选择需要查看的巡检点');
      return;
    }
    let row = selectedRows[0];
    let path = {
      pathname: checkUrl(),
      state: { pointNo: row.pointNo }
    };
    browserHistory.push(path);
  }

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

PointTable.propTypes = {
  operationType: PropTypes.string,
  queryParam: PropTypes.any
};

export default PointTable;
