import React, { Component } from 'react';
import formatUrl from 'amos-processor/lib/utils/urlFormat';
import _amosTool from 'amos-tool';
import SysConsts from 'amos-processor/lib/config/consts';
import { Button } from 'amos-framework';
import AmosGridTable from './../../common/tableComponent/table/AmosGridTable';
import { DangerListHeader } from './conf';
import DangerListSearch from './DangerListSearch';
import SplitterLayout from './../../../common/side/SideQueryLayout';
import BizIcon from './../../../common/icon/BizIcon';
import { getDangerListDataAction, exportDangerListDataAction } from './../../../../services/bizService';
import { SpcSerUrl } from './../../../../consts/urlConsts';

const ls = _amosTool.Store.lsTool;
const apiKey = SysConsts.api_key;
const token = SysConsts.token;

const buttonMap = [
  { key: 'export', icon: 'daochu', label: '导出' },
  { key: 'filter', icon: 'shaixuan', label: '筛选' }
];

class DangerList extends Component {
  constructor(props) {
    super(props);
    this.pageConfig = {
      current: 1,
      pageSize: 10
    };
    this.state = {
      pagination: true,
      isChecked: false,
      selectedRows: [],
      selectedRowKeys: [],
      dataList: [],
      searchParam: [],
      totalCount: 0,
      showQuery: false
    };
  }

  componentDidMount() {
  }

  componentWillReceiveProps(nextProps) {

  }

  onToolBarClick = (btnType) => {
    if (btnType === 'filter') {
      this.loopChangeStatus();
    }
    if (btnType === 'export') {
      let { searchParam } = this.state;
      if (Array.isArray(searchParam)) {
        let temp = {};
        temp['pageSize'] = searchParam['pageSize'];
        temp['pageNumber'] = searchParam['pageNumber'];
        searchParam = temp;
      }
      this.exportDangerList(searchParam);
    }
  };

  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 });
  }

  getSearchView = () => {
    let { searchCommonData } = this.state;
    return <DangerListSearch searchCommonData={searchCommonData} search={this.setSearchAndSearch} ref={node => this.searchView = node} />;
  }

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

  setSearchAndSearch = (form) => {
    let { searchParam } = this.state;
    searchParam = {};
    for (let k in form) {
      searchParam[k] = form[k];
    }
    this.setState({ searchParam }, () => this.questStatistiscData(this.pageConfig));
  }

  exportDangerList = (searchParam) => {
    let url = formatUrl(SpcSerUrl.exportDangerListUrl);
    debugger
    fetch(url, {
      method: 'post',
      headers: {
        Accept: 'application/vnd.ms-excel',
        'Content-Type': 'application/json; charset=utf-8',
        'X-Api-Key': _amosTool.Store.getCookieByName(apiKey),
        'X-Access-Token': ls.read(token)
      },
      body: JSON.stringify(searchParam)
    }).then(e => {
      debugger
      e.blob().then(blob => {
        const a = window.document.createElement('a');
        const downUrl = window.URL.createObjectURL(blob);
        let currDate = new Date();
        const filename = [currDate.getTime(), 'xls'];
        a.href = downUrl;
        a.download = `${decodeURI(filename[0])}.${filename[1]}`;
        a.click();
        window.URL.revokeObjectURL(downUrl);
      });
    }).catch(e => {
      _amosTool.Log.error(e.message);
    });
  }

  questStatistiscData = (param) => {
    let { searchParam } = this.state;
    if (param.current != null) {
      //前端的current 即后端的pageNumber
      param.pageNumber = param.current;
    }
    let { pageNumber, pageSize } = param;
    searchParam.pageNumber = pageNumber;
    searchParam.pageSize = pageSize;
    let search = {};
    for (let k in searchParam) {
      search[k] = searchParam[k];
    }
    getDangerListDataAction(search).then(data => {
      this.setState({ dataList: data.content, totalNum: data.totalElements });
    });
  }

  reload = r => {
    this.setState(
      {
        reload: () => {
          r();
          this.setState({ selectedRows: [], selectedRowKeys: [] });
        }
      },
      r()
    );
  }

  changeStatus = (open) => {
    this.setState({ showQuery: open });
  }

  loopChangeStatus = (open) => {
    const { showQuery } = this.state;
    showQuery ? this.setState({ showQuery: false }) : this.setState({ showQuery: true });
    this.searchView.initFormValues();
  }

  renderButton =()=>{
    return (<div className='risk-list-operate-button'>
      {buttonMap.map(item => { return <Button title={item.label} icon={<BizIcon icon={item.icon} />} transparent onClick={() => this.onToolBarClick(item.key)} />;})}
      <Button className="risk-list-search-button" onClick={this.handleReset} >重置</Button>
    </div>);
  }

  handleReset = () => {
    let { searchParam } = this.state;
    searchParam = {};
    this.setState({ searchParam }, () => this.questStatistiscData(this.pageConfig));
  }

  render() {
    let { pagination, isChecked, selectedRowKeys, dataList, totalNum, showQuery } = this.state;
    const defaultPageConfig = this.pageConfig;
    return (
      <div className="execute-danger-list">
        {this.renderButton()}
        <SplitterLayout open={showQuery} callback={this.changeStatus}>
          {this.getSearchView()}
        </SplitterLayout>
        <div className="danger-list-table">
          <AmosGridTable
            columns={DangerListHeader}
            callBack={this.reload}
            isPageable={pagination}
            dataList={dataList}
            totals={totalNum}
            getTableDataAction={param => this.questStatistiscData(param)}
            selectedRowKeys={selectedRowKeys}
            getSelectedRows={this.getSelectedRows}
            rowClassName={this.getRowClassName}
            setPageConfig={this.setPageConfig}
            defaultPageConfig={defaultPageConfig}
            onRowClick={this.onRowClick}
            isChecked={isChecked}
          />
        </div>
      </div>
    );
  }
}

DangerList.propTypes = {

};

export default DangerList;
