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

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

  const dropnavs1 = { key: '1', text: '返回', icon: 'fanhui', href: 'jacascript::void(0)', permissionCode: 'plan', isWriteable: false };
  const dropnavs2 = { key: '2', text: '巡检记录', icon: 'history', href: 'jacascript::void(0)', permissionCode: 'plan', isWriteable: false };
  const dropnavs3 = { key: '3', text: '重做', icon: 'save', href: 'jacascript::void(0)', permissionCode: 'plan', isWriteable: true };
  const dropnavs4 = { key: '4', text: '删除', icon: 'delete', href: 'jacascript::void(0)', permissionCode: 'plan', isWriteable: true };
  const dropnavs5 = {
    key: '5',
    text: '导出',
    icon: 'user',
    href: 'jacascript::void(0)',
    subSys: [
      { key: '5-1', text: '导出选中计划', href: 'jacascript::void(0)', permissionCode: 'plan', isWriteable: false },
      { key: '5-2', text: '导出全部计划', href: 'jacascript::void(0)', permissionCode: 'plan', isWriteable: false },
    ]
  };


const checkUrl = () => pathMapping.check;
const statusEnum = { 0: '尚未巡检',1: '按时完成',2: '超时漏检' };
const getColumns = () => {
  return [
    {
      title: '计划批号',
      dataIndex: 'batchNo',
      key: 'batchNo',
      width: '8%',
      className: 'uant-table-thead'
    },
    {
      title: '计划名称',
      dataIndex: 'planName',
      key: 'planName',
      width: '11%',
      className: 'uant-table-thead'
    },
    {
      title: '巡检路线',
      dataIndex: 'routeName',
      key: 'routeName',
      width: '10%',
      className: 'uant-table-thead'
    },
    {
      title: '点编号',
      dataIndex: 'pointNo',
      key: 'pointNo',
      width: '9%',
      className: 'uant-table-thead'
    },
    {
      title: '点名称',
      dataIndex: 'pointName',
      key: 'pointName',
      width: '11%',
      className: 'uant-table-thead'
    },
    {
      title: '开始时间',
      dataIndex: 'beginTime',
      key: 'beginTime',
      width: '13%',
      className: 'uant-table-thead'
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
      width: '13%',
      className: 'uant-table-thead'
    },
    {
      title: '执行情况',
      dataIndex: 'status',
      key: 'status',
      width: '9%',
      render: text =>statusEnum[text],
      className: 'uant-table-thead'
    },
    {
      title: '巡检部门',
      dataIndex: 'deptName',
      key: 'deptName',
      width: '9%',
      className: 'uant-table-thead'
    },
    {
      title: '巡检人员',
      dataIndex: 'userName',
      key: 'userName',
      width: '9%',
      className: 'uant-table-thead'
    }
  ];
};

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

  /**
   * 组件初始化调用
   */
  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/plan').then(data => {
      
      let { dropnavs } = this.state;
     if(data){
  
       if("z_fh" in data&&data.z_fh.hasPermission){
        dropnavs.push( dropnavs1);
       }
       if("z_xjjl" in data&&data.z_xjjl.hasPermission){
        dropnavs.push( dropnavs2);
  
      }
      if("z_cz" in data&&data.z_cz.hasPermission){
        dropnavs.push( dropnavs3);
  
      }
      if("z_sc" in data&&data.z_sc.hasPermission){
        dropnavs.push( dropnavs4);
  
      }
      if("z_dc" in data&&data.z_dc.hasPermission){
        dropnavs.push( dropnavs5);
  
      }
      
     }
  
      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();
  };

  repGenPlan = () => {
    const { form } = this.state;
    if (!form.planId) {
      AmosAlert.error('提示', '请点击选择要重做及计划');
      return;
    }
    if (!form.beginDate) {
      form.beginDate = moment().format('YYYY-MM-DD');
    }
    if (!form.endDate) {
      form.endDate = moment().format('YYYY-MM-DD');
    }
    window.setLoading && window.setLoading(true);
    reGenPlanTaskAction(form).then(
      data => {
        window.setLoading && window.setLoading(false);
        AmosAlert.success('提示', '重做成功');
        this.cancel();
        this.reloadPage();
      },
      err => {
        window.setLoading && window.setLoading(false);
        AmosAlert.error('提示', err);
      }
    );
  };

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

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

  onClickBootBar = type => {
    if (type === '1') {
      browserHistory.goBack('/main/patrol/plan');
    } else if (type === '2') {
      this.checkInfoForward();
    } else if (type === '3') {
      this.open();
    } else if (type === '4') {
      this.deleteGenData();
    } else if (type === '5-1') {
      this.exportSelectData();
     //导出选中计划
    } else if (type === '5-2') {
     //导出全部计划
      this.exportAllData();
    }
  };

  exportSelectData = () => {
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys === undefined ||  selectedRowKeys.length <= 0 ) {
      AmosAlert.warning('提示', '请先点击选择需要导出的行');
      return;
    }
    let ids = selectedRowKeys.join(',');
    let url = formatUrl(patrolUrls.exportSelectPlanTaskUrl, { 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),
        'token': ls.read(token),
        'appKey': 'YH-PATROL',
        'product': 'YH-PATROL_WEB'
      }
    }).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);
    });
  }

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

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

  setGenPlanTaskParam = param => {
    this.setState({ form: param });
  };

  getContext = () => {
    let { form } = this.state;
    return <PlanTaskReGenTable callBack={this.setGenPlanTaskParam} planId={form.planId} />;
  };

  open = () => {
    this.setState({ modal: true });
  };

  cancel = () => {
    this.setState({ modal: false });
  };

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

  render() {
    let { pagination, isChecked, modal, selectedRowKeys,dropnavs } = this.state;
    let { dataList, fetchData, count } = this.props;
    let defaultPageConfig = this.pageConfig;
    return (
      <div className="patrol-page-table">
        <ToolBar dropnavs={dropnavs} callBack={this.onClickBootBar} />
        <Modal
          header="重做计划执行"
          visible={modal}
          content={this.getContext()}
          onCancel={() => this.cancel()}
          onOk={() => this.repGenPlan()}
          okText="确定"
          cancelText="关闭"
          destroyContent
        />
        <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>
    );
  }
}

PlanTaskTable.propTypes = {
  changeType: PropTypes.string,
  queryParam: PropTypes.object,
  planId: PropTypes.number,
  dataList: PropTypes.array,
  fetchData: PropTypes.func,
  count: PropTypes.number,
  searchParam: PropTypes.array
};

export default PlanTaskTable;
