import React, { Component } from 'react';
import { AmosAlert } from 'amos-framework';
import { browserHistory } from 'amos-react-router';
import PropTypes from 'prop-types';
import dt2react from 'dt2react';
import BootBar from '../../component/toolbar';
import AmosGridTable from '../../component/table/table/AmosGridTable';
import { pathMapping } from './../../../routes/customRoutes';
import { queryInputItemAction, batchDelInputItemAction, saveAsInputItemAction ,btnAuthAction} from '../../../services/checkService';

const textInputItemPath = pathMapping.textInputItem;
const numberInputItem = pathMapping.numberInputItem;
const choiceInputItemPath = pathMapping.choiceInputItem;

const textInputItemPathxq = pathMapping.textInputItemxq;
const numberInputItemxq = pathMapping.numberInputItemxq;
const choiceInputItemPathxq = pathMapping.choiceInputItemxq;





  const dropnavs1 = { key: '1', text: '新增', icon: 'add', href: 'jacascript::void(0)',
    subSys: [
      { key: '1-1', text: '文本检查项' ,  href: textInputItemPath , permissionCode: 'inputitem', isWriteable: true},
      { key: '1-2', text: '选择检查项' ,  href: choiceInputItemPath , permissionCode: 'inputitem', isWriteable: true},
      { key: '1-3', text: '数字检查项' ,  href: numberInputItem , permissionCode: 'inputitem', isWriteable: true}
    ]
  };
  const dropnavs2 ={ key: '2', text: '修改', icon: 'edit' , href: 'jacascript::void(0)' , permissionCode: 'inputitem', isWriteable: true };
  const dropnavs3 ={ key: '3', text: '另存', icon: 'ccgl-chukucaozuo-13' , href: 'jacascript::void(0)' , permissionCode: 'inputitem', isWriteable: true };
  const dropnavs4 ={ key: '4', text: '删除', icon: 'delete', href: 'jacascript::void(0)' , permissionCode: 'inputitem', isWriteable: true };
  const dropnavs5 ={ key: '5', text: '明细', icon: 'edit' , href: 'jacascript::void(0)' , permissionCode: 'inputitem', isWriteable: true };



  const levelEum = { 1: '1级',2: '2级', 3: '3级', 4: '4级', 5: '5级' };
const getColumns = () => {
  return [
    {
      title: '检查项名称',
      dataIndex: 'name',
      key: 'name',
      width: '11%',
      className: 'uant-table-thead'
    },
    {
      title: '编号',
      dataIndex: 'itemNo',
      key: 'itemNo',
      width: '10%',
      className: 'uant-table-thead'
    },
    {
      title: '等级',
      dataIndex: 'level',
      key: 'level',
      width: 100,
      render: text => levelEum[text]
    },
    {
      title: '检查项类型',
      dataIndex: 'itemType',
      key: 'itemType',
      width: '11%',
      className: 'uant-table-thead'
    },
    {
      title: '是否必填',
      dataIndex: 'isMust',
      key: 'isMust',
      width: '11%',
      className: 'uant-table-thead'
    },
    {
      title: '默认值',
      dataIndex: 'defaultValue',
      key: 'defaultValue',
      width: '11%',
      className: 'uant-table-thead'
    },
    {
      title: '是否评分',
      dataIndex: 'isScore',
      key: 'isScore',
      width: '11%',
      className: 'uant-table-thead'
    },
    {
      title: '分类目录',
      dataIndex: 'catalogName',
      key: 'catalogName',
      width: '11%',
      className: 'uant-table-thead',
      render: (text, record) => {
        return !text || text === 0 ? '' : text;
      }
    },
    {
      title: '备注说明',
      dataIndex: 'remark',
      key: 'remark',
      width: '11%',
      className: 'uant-table-thead'
    }
  ];
};

//偏移110px
const offsetHeight = 50;
const defaultHeight = 550;

/**
 * 巡检项
 *
 * @class InputItemTable
 * @extends {Component}
 */
class InputItemTable extends Component {
  constructor(props) {
    super(props);
    this.pageConfig = {
      pageNumber: 0,
      pageSize: 10
    },
      this.state = {
        pagination: true,
        isChecked: true,
        selectedRows: [],
        selectedRowKeys: [],
        request: [],
        count: 0,
        data: [],
        pageConfig: {
          pageNumber: 0,
          pageSize: 10
        },
        requestParam: [],
        dropnavs:[]
      };
  }
  /**
   * 组件初始化调用
   */
  componentWillMount = () => {
    this.reloadButtonAuth();

  };
  reloadButtonAuth = () => {
    // const _path = this.calcRoutes();
    btnAuthAction('/main/patrol/inputitem').then(data => {
     
      let { dropnavs } = this.state;
     if(data){
  
       if("xz" in data&&data.xz.hasPermission){
        dropnavs.push( dropnavs1);
       }
       if("lc" in data&&data.lc.hasPermission){
        dropnavs.push( dropnavs2);
  
      }
      if("xg" in data&&data.xg.hasPermission){
        dropnavs.push( dropnavs3);
  
      }
      if("sc" in data&&data.sc.hasPermission){
        dropnavs.push( dropnavs4);
  
      }
      if("mx" in data&&data.mx.hasPermission){
        dropnavs.push( dropnavs5);
  
      }
      
     }
  
      this.setState({ dropnavs});
    });
  }
  /**
   * 接受新的属性时回调
   */
  componentWillReceiveProps = nextProps => {
    let { changeType, queryParam } = nextProps;
    if ('query' === changeType) {
      let request = new Array();
      if (queryParam) {
        for (let key in queryParam) {
          let obj = queryParam[key];
          request.push(obj);
        }
      }
      this.setState({ requestParam: request }, () => this.reloadInputItem(this.pageConfig));
    }
  };

  onRowDoubleClick = (record, index, event) => {
    let pathname = '';
    if (record.itemType === '文本') {
      pathname = textInputItemPath;
    } else if (record.itemType === '数字') {
      pathname = numberInputItem;
    } else if (record.itemType === '选择') {
      pathname = choiceInputItemPath;
    }
    let path = {
      pathname,
      state: { inputItemID: record.id }
    };
    browserHistory.push(path);
  };

  onClickBootBar = (type) => {
    if (type === '2') {
      this.updateInputItem();
    } else if (type === '3') {
      this.savaAs();
    } else if (type === '4') {
      this.deleteInputItem();
    }else if (type.startsWith('1-')){
      let { dropnavs } = this.state;
      if(dropnavs&&dropnavs.length>0){
        let curNavs = dropnavs[0].subSys.filter(item => item.key == type);
        browserHistory.push(curNavs[0].href);
      }
      
    }else if(type === '5'){

      this.updateInputItem1();
    }
  };

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

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

  /**
   *根据条件查询检查项
   */
  reloadInputItem = pageParam => {
    let { requestParam } = this.state;
    let { pageSize } = pageParam;
    let pageNumber = 0;
    this.setState({ selectedRows: [], selectedRowKeys: [] });
    if (pageParam.current !== null && !isNaN(pageParam.current)) {
      pageNumber = pageParam.current;
    }
    queryInputItemAction(requestParam, pageNumber, pageSize).then(data => {
      if (data) {
        this.setState({ data: data.content, count: data.totalElements });
      }
    });
  };

  /**
   * 删除已经选择的检查项
   */
  deleteInputItem = () => {
    let { selectedRowKeys } = this.state;

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

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






 /**
   * 明细新检查项页面
   */
  updateInputItem1 = () => {
    const { selectedRows } = this.state;
    if (selectedRows === undefined || selectedRows.length <= 0) {
      AmosAlert.warning('提示', '请选择检查项');
      return;
    }
    if (selectedRows.length > 1) {
      AmosAlert.warning('提示', '至多选择一条检查项');
      return;
    }
    let row = selectedRows[0];
    let path = null;
    if (row.itemType === '文本') {
      path = {
        pathname: textInputItemPathxq,
        state: { inputItemID: row.id }
      };
    } else if (row.itemType === '数字') {
      path = {
        pathname: numberInputItemxq,
        state: { inputItemID: row.id }
      };
    } else if (row.itemType === '选择') {
      path = {
        pathname: choiceInputItemPathxq,
        state: { inputItemID: row.id }
      };
    }
    path && browserHistory.push(path);
  };
























  /**
   * 跳转到跟新检查项页面
   */
  updateInputItem = () => {
    const { selectedRows } = this.state;
    if (selectedRows === undefined || selectedRows.length <= 0) {
      AmosAlert.warning('提示', '请选择要修改的检查项');
      return;
    }
    if (selectedRows.length > 1) {
      AmosAlert.warning('提示', '至多选择一条要修改的检查项');
      return;
    }
    let row = selectedRows[0];
    let path = null;
    if (row.itemType === '文本') {
      path = {
        pathname: textInputItemPath,
        state: { inputItemID: row.id }
      };
    } else if (row.itemType === '数字') {
      path = {
        pathname: numberInputItem,
        state: { inputItemID: row.id }
      };
    } else if (row.itemType === '选择') {
      path = {
        pathname: choiceInputItemPath,
        state: { inputItemID: row.id }
      };
    }
    path && browserHistory.push(path);
  };

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

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

  getPanelHeight = () => {
    let inputItemTable = this.inputItemTable;
    let tableLocation = dt2react.getOffset(inputItemTable) || {};
    return tableLocation !== undefined ? tableLocation.height - offsetHeight : defaultHeight;
  }

  render() {
    console.log("inputItemTable")
    let { pagination, isChecked, data, count, selectedRowKeys ,dropnavs} = this.state;
    let defaultPageConfig = this.pageConfig;
    return (
      <div ref={node => this.inputItemTable = node}  className="patrol-page-table">
        <BootBar dropnavs={dropnavs} callBack={this.onClickBootBar} />
        <AmosGridTable
          rowKey="id"
          columns={getColumns()}
          isPageable={pagination}
          isChecked={isChecked}
          dataList={data}
          totals={count}
          callBack={this.reload}
          selectedRowKeys={selectedRowKeys}
          getTableDataAction={this.reloadInputItem}
          getSelectedRows={this.getSelectedRows}
          setPageConfig={this.setPageConfig}
          defaultPageConfig={defaultPageConfig}
          onRowDoubleClick={this.onRowDoubleClick}
          getPanelHeight={this.getPanelHeight}
        />
      </div>
    );
  }
}

InputItemTable.propTypes = {
  changeType: PropTypes.string,
  queryParam: PropTypes.object
};

export default InputItemTable;
