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 } from 'amos-framework';
import PropTypes from 'prop-types';
import { browserHistory } from 'amos-react-router';
import { pathMapping } from './../../../routes/customRoutes';
import AmosGridTable from '../../component/table/table/AmosGridTable';
import { patrolUrls } from './../../../consts/urlConsts';
import ToolBar from './../../component/toolbar';
import { batchDeCheckAction, queryCheckDetailAction, btnAuthAction } from '../../../services/checkService';

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

const checkDetail = pathMapping.checkDetail;

const okStatusEnum = { '1': '正常', '2': '异常', '3': '漏检' };
const statusDataEnum = { '0': '计划外完成', '1': '按时完成', '2': '未执行' };

const dropnavs1 = { key: '1', text: '查看明细', icon: 'jiancha', href: 'jacascript::void(0)', permissionCode: 'check', isWriteable: false };
const dropnavs2 = { key: '2', text: '删除记录', icon: 'delete', href: 'jacascript::void(0)', permissionCode: 'check', isWriteable: true };
const dropnavs3 = {
  key: '3',
  text: '导出记录',
  icon: 'user',
  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 dropnavs4 = { key: '4', text: '业务报表', icon: 'file', href: 'jacascript::void(0)', permissionCode: 'check', isWriteable: true };

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: 95,
      className: 'uant-table-thead'
    },
    {
      title: '巡检路线',
      dataIndex: 'routeName',
      key: 'routeName',
      width: 160,
      className: 'uant-table-thead'
    },
    {
      title: '巡检模式',
      dataIndex: 'checkMode',
      key: 'checkMode',
      width: 95,
      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'
    }
  ];
};

const getHeaders = () => {
  return {
    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),
    token: ls.read(token),
    appKey: 'YH-PATROL',
    product: 'YH-PATROL_WEB'
  };
};

/**
 * 计划执行
 *
 * @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: [],
      dropnavs: [],
      showType: ''
    };
  }

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

  /****按钮权限 */

  reloadButtonAuth = () => {
    // const _path = this.calcRoutes();
    btnAuthAction('/main/patrol/check').then(data => {
      let { dropnavs } = this.state;
      if (data) {
        if ('jiancha' in data && data.jiancha.hasPermission) {
          dropnavs.push(dropnavs1);
        }
        if ('delete' in data && data.delete.hasPermission) {
          dropnavs.push(dropnavs2);
        }
        if ('user' in data && data.user.hasPermission) {
          dropnavs.push(dropnavs3);
        }
        if ('ureport' in data && data.ureport.hasPermission) {
          dropnavs.push(dropnavs4);
        }
      }

      this.setState({ dropnavs });
    });
  };

  /**
   * 分页设置参数
   */
  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();
    } else if (type === '4') {
      this.onClickIcon('check');
    }
    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: getHeaders()
    })
      .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: getHeaders()
    })
      .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: getHeaders(),
      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: getHeaders(),
      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);
    // });
  };

  onClickIcon = value => {
    const { showType } = this.state;
    if (showType === value) {
      value = '';
    }
    this.props.setShowType(value);
    this.setState({ showType: value });
  };

  render() {
    let { pagination, dropnavs, isChecked, selectedRowKeys } = this.state;

    let { dataList, fetchData, count } = this.props;
    let defaultPageConfig = this.pageConfig;
    return (
      <div className="patrol-page-table">
        <ToolBar dropnavs={dropnavs} callBack={this.onClickBootBar} />
        <div className="right-btn">
          {/* <div className="row-btn">
            <img src="/src/assets/fsc/check/export.png" onClick={() => this.onClickIcon('check')} />
            <span>&nbsp;&nbsp;业务报表</span>
          </div> */}
          <div className="row-btn">
            <img src="/src/assets/fsc/check/export.png" onClick={() => this.onClickIcon('export')} />
            <span>&nbsp;&nbsp;报表生成</span>
          </div>
          <div className="row-btn">
            <img src="/src/assets/fsc/check/filter.png" onClick={() => this.onClickIcon('search')} />
            <span>&nbsp;&nbsp;筛选条件</span>
          </div>
        </div>
        <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 = {
  setShowType: PropTypes.func
};

export default CheckTable;
