import formatUrl from 'amos-processor/lib/utils/urlFormat';
import _amosTool from 'amos-tool';
import SysConsts from 'amos-processor/lib/config/consts';
import React, { Component } from 'react';
import { AmosAlert,Button } from 'amos-framework';
import PropTypes from 'prop-types';
import { browserHistory } from 'amos-react-router';
import { pathMapping } from './../../../routes/customRoutes';
import AmosGridTable from './../common/tableComponent/table/AmosGridTable';
import { patrolUrls } from './../../../consts/urlConsts';
import ToolBar from './../../component/toolbar';
import { batchDeCheckAction } from '../../../services/patrolService';
import BizIcon from './../../common/icon/BizIcon';

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

const checkDetail = pathMapping.checkDetailInfo;

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

const okStatusEnum = { '1': '合格', '2': '不合格', '3': '漏检' };
const statusDataEnum = { '0': '计划外完成', '1': '按时完成', '2': '未执行' };
const dropnavs = [
  { key: '1', text: '查看明细', icon: 'mingxi', href: 'jacascript::void(0)', permissionCode: 'check', isWriteable: false },
  { key: '2', text: '删除记录', icon: 'shanchu', href: 'jacascript::void(0)', permissionCode: 'check', isWriteable: true },
  {
    key: '3',
    text: '导出记录',
    icon: 'daochu',
    href: 'jacascript::void(0)',
    subSys: [
      { key: '3-1', text: '导出选中数据', href: 'jacascript::void(0)', permissionCode: 'check', isWriteable: false },
      { key: '3-2', text: '导出全部数据', href: 'jacascript::void(0)', permissionCode: 'check', isWriteable: false },
      { key: '3-3', text: '导出选中图片', href: 'jacascript::void(0)', permissionCode: 'check', isWriteable: false },
      { key: '3-4', text: '导出全部图片', href: 'jacascript::void(0)', permissionCode: 'check', isWriteable: false }
    ]
  }
];

const getColumns = () => {
  return [
    {
      title: '危险源名称',
      dataIndex: 'pointName',
      key: 'pointName',
      width: 160,
      className: 'uant-table-thead'
    },
    {
      title: '危险源编号',
      dataIndex: 'pointNo',
      key: 'pointNo',
      width: 100,
      className: 'uant-table-thead'
    },
    {
      title: '检查人员',
      dataIndex: 'userName',
      key: 'userName',
      width: 92,
      className: 'uant-table-thead'
    },
    {
      title: '检查部门',
      dataIndex: 'departmentName',
      key: 'departmentName',
      width: 92,
      className: 'uant-table-thead'
    },
    {
      title: '检查时间',
      dataIndex: 'checkTime',
      key: 'checkTime',
      width: 144,
      className: 'uant-table-thead'
    },
    {
      title: '上报时间',
      dataIndex: 'uploadTime',
      key: 'uploadTime',
      width: 144,
      className: 'uant-table-thead'
    },
    {
      title: '执行情况',
      dataIndex: 'finishStatus',
      key: 'finishStatus',
      width: 95,
      render: text => statusDataEnum[text],
      className: 'uant-table-thead'
    },
    {
      title: '状态',
      dataIndex: 'isOk',
      key: 'isOk',
      width: 95,
      render: text => okStatusEnum[text],
      className: 'uant-table-thead'
    },
    {
      title: '评分',
      dataIndex: 'score',
      key: 'score',
      width: 90,
      className: 'uant-table-thead'
    },
    {
      title: '安全检查表',
      dataIndex: 'routeName',
      key: 'routeName',
      width: 160,
      className: 'uant-table-thead'
    },
    {
      title: '安全检查计划',
      dataIndex: 'planName',
      key: 'planName',
      width: 160,
      className: 'uant-table-thead'
    },
    {
      title: '任务编号',
      dataIndex: 'planTaskId',
      key: 'planTaskId',
      width: 95,
      className: 'uant-table-thead'
    },
    {
      title: '不合格项目',
      dataIndex: 'error',
      key: 'error',
      width: 190,
      className: 'uant-table-thead'
    },
    {
      title: '备注说明',
      dataIndex: 'remark',
      key: 'remark',
      width: 190,
      className: 'uant-table-thead'
    }
  ];
};

/**
 * 计划执行
 *
 * @class CheckTable
 * @extends {Component}
 */
class CheckTable extends Component {
  constructor(props) {
    super(props);
    this.pageConfig = {
      current: 1,
      pageSize: 10
    };
    this.state = {
      form: {
        planId: '',
        changeFlag: '0',
        beginDate: '',
        endDate: ''
      },
      pagination: true,
      isChecked: true,
      selectedRows: [],
      selectedRowKeys: [],
      data: []
    };
  }

  /**
   * 组件初始化调用
   */
  componentWillMount = () => {
    let { planId } = this.props;
    let { form } = this.state;
    form.planId = planId;
    this.setState({ form });
  };

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

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

  getRowClassName = (record, index) => {
    let highlight = this.highlight;
    if (highlight && record.id === highlight) {
      return 'highlight-row';
    } else {
      return 'normal-row';
    }
  };

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

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

  reloadPage = () => {
    this.clearSelectedRows();
    this.state.reload();
  };

  deleteCheckData = () => {
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys === undefined || selectedRowKeys.length <= 0) {
      AmosAlert.warning('提示', '请先点击选择需要删除的行');
      return;
    }
    let ids = selectedRowKeys;
    AmosAlert.confirm('提示', '确定要删除指定的数据么?', {
      callback: flag => {
        if (flag) {
          // 确定删除
          batchDeCheckAction(ids).then(
            data => {
              AmosAlert.success('提示', '删除成功');
              this.reloadPage();
            },
            err => {
              AmosAlert.error('错误', err);
            }
          );
        }
      }
    });
  };

  onClickBootBar = type => {
    window.setLoading && window.setLoading(true);
    if (type === '1') {
      this.getDetCheckInfo();
    } else if (type === '2') {
      this.deleteCheckData();
    } else if (type === '3-1') {
      this.exportSelectRecord();
    } else if (type === '3-2') {
      this.exportAllData();
    } else if (type === '3-3') {
      this.exportSelectImgs();
    } else if (type === '3-4') {
      this.exportAllDataImgs();
    }
    window.setLoading && window.setLoading(false);
  };

  exportSelectRecord = () => {
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys === undefined || selectedRowKeys.length <= 0) {
      AmosAlert.warning('提示', '请先选择需要导出的行');
      return;
    }
    let ids = selectedRowKeys.join(',');
    let url = formatUrl(patrolUrls.exportSelectRecordUrl, { ids });
    fetch(url, {
      method: 'get',
      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)
      }
    })
      .then(e => {
        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);
      });
  };

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

  delRequest = (url, method) => {
    if (window.requests && window.requests.length > 0) {
      window.requests = window.requests.filter(e => e.url !== url && e.method !== method);
    }
  };

  exportAllData = () => {
    let { searchParam } = this.props;
    let url = patrolUrls.exportCheckRecordUrl;

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

  exportAllDataImgs = () => {
    let { searchParam } = this.props;
    let url = patrolUrls.exportCheckRecordImgsUrl;

    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 => {
        e.blob().then(blob => {
          const a = window.document.createElement('a');
          const downUrl = window.URL.createObjectURL(blob);
          let currDate = new Date();
          const filename = [currDate.getTime(), 'zip'];
          a.href = downUrl;
          a.download = `${decodeURI(filename[0])}.${filename[1]}`;
          a.click();
          window.URL.revokeObjectURL(downUrl);
        });
      })
      .catch(e => {
        _amosTool.Log.error(e.message);
      });
  };

  getDetCheckInfo = () => {
    let { selectedRows } = this.state;
    if (selectedRows === undefined || selectedRows.length <= 0) {
      AmosAlert.warning('提示', '请先点击选择需要查看的巡检记录');
      return;
    }
    if (selectedRows.length > 1) {
      AmosAlert.warning('提示', '至多可以选择一条巡检记录');
      return;
    }
//    for (let i = 0; i < selectedRows.length; i++) {
    let id = selectedRows[0].id;
    let path = {
      pathname: checkDetail,
      state: { checkID: id }
    };
    browserHistory.push(path);
      // queryCheckDetailAction(id).then(data => {
      //   this.showCheckDetail(data);
      // });
    // }
  };

  showCheckDetail = result => {
    let newWindow = window.open('巡检任务详情', '_blank');
    newWindow.document.write(result);
    newWindow.document.close();
  };

  onRowDoubleClick = (record, index, event) => {
    let id = record.id;
    let pointId = record.pointIds;
    let path = {
      pathname: checkDetail,
      state: { checkID: id, pointID: pointId }
    };
    browserHistory.push(path);
    // queryCheckDetailAction(id).then(data => {
    //   this.showCheckDetail(data);
    // });
  };

  onToolBarClick =()=>{
    const { changeStatus } = this.props;
    changeStatus && changeStatus();
  }

  renderButton =()=>{
    return (
      <div>
         <div className='patrol-list-operate-button'>
           <ToolBar dropnavs={dropnavs} callBack={this.onClickBootBar} style={{ display: 'inline-block' }} />
        </div>
        <div className='patrol-list-search-button'>
           {buttonMap.map(item=>{return <Button title={item.label} key={item.key} icon={<BizIcon icon={item.icon} />} transparent onClick={this.onToolBarClick} />;})}
           <Button className="risk-list-search-button" onClick={this.handleReset} >重置</Button>
        </div>
     </div>);
  }

  handleReset = () => {
    this.props.tableState.searchParam = [];
    this.props.fetchData(this.pageConfig);
  }

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

CheckTable.propTypes = {
  changeStatus: PropTypes.func,
  dataList: PropTypes.array,
  fetchData: PropTypes.func,
  count: PropTypes.number
};

export default CheckTable;
