import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Modal, AmosAlert, Button } from 'amos-framework';
import AmosGridTable from './../../../common/tableComponent/table/AmosGridTable';
import { controlMeasureDeleteAction,getCatalogEumAction, getTypeEumAction } from '../../../../../services/bizService';
import ControlModel from './ControlModel';
import MeasuresView from './MeasuresView';

const getColumns = (self) => {
  return [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}`
    },
    {
      title: '控制措施名称',
      dataIndex: 'name',
      key: 'name',
      width: '30%',
      className: 'uant-table-thead'
    },
    {
      title: '控制措施类别',
      dataIndex: 'category',
      key: 'category',
      width: '30%',
      className: 'uant-table-thead'
    },
    {
      title: '所属类型',
      dataIndex: 'type',
      key: 'type',
      width: '20%',
      className: 'uant-table-thead'
    },
    {
      title: '控制措施数量',
      dataIndex: 'measureNum',
      key: 'measureNum',
      width: '10%',
      render: (text, record) => {
        return (
          <span>
            <a href="javascript:;" onClick={() => {self.onDetailClick(record);}}>{text}</a>
          </span>
        );
      },
      className: 'uant-table-thead'
    }
  ];
};


/**
 * 控制措施管理
 */
class ControlModelView extends Component {
  constructor(props) {
    super(props);
    this.pageConfig = {
      current: 1,
      pageSize: 10
    };
    this.state = {
      pagination: true,
      isChecked: true,
      modal: false,
      show: false,
      selectedRows: [],
      selectedRowKeys: [],
      data: [],
      searchParam: [],
      showRecord: {}
    };
  }

  componentWillMount() {

  }

  componentWillReceiveProps(newProps) {
    let { toolBarFlag, activeKey, initToolbarFlag } = newProps;
    if (activeKey && activeKey === '3' && toolBarFlag) {
      this.checkData(toolBarFlag);
      initToolbarFlag();
    }
  }

  onDetailClick = (record) => {
    this.setState({ show: true, showRecord: record });
  }

  checkData = toolBarFlag => {
    let { selectedRowKeys } = this.state;
    if (toolBarFlag === '1') {
      //新增
      this.setState({ modal: true, toolBarFlag });
    } else if (toolBarFlag === '2') {
      //编辑
      if (selectedRowKeys === undefined || selectedRowKeys.length <= 0) {
        AmosAlert.warning('提示', '请先点击选择编辑的行');
        return;
      } else {
        this.setState({ modal: true, toolBarFlag });
      }
    } else if (toolBarFlag === '3') {
      //删除
      if (selectedRowKeys === undefined || selectedRowKeys.length <= 0) {
        AmosAlert.warning('提示', '请先点击选择删除的行');
        return;
      } else {
        this.controlMeasureDelete(selectedRowKeys);
      }
    }
  };

  /**
   * 分页设置参数
   */
  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 { selectedRowKeys } = this.state;
    if (selectedRowKeys.findIndex(item => item === record.id) >= 0) {
      return 'highlight-row';
    } else {
      return 'normal-row';
    }
  };

  onRowClick = record => {
    let { selectedRowKeys, selectedRows } = this.state;
    let exist = false;
    selectedRows.find(item => {
      if (item.id === record.id) {
        exist = true;
      }
    });
    if (exist) {
      selectedRows.splice(selectedRows.findIndex(item => item.id === record.id), 1);
      selectedRowKeys.splice(selectedRowKeys.findIndex(item => item === record.id), 1);
    } else {
      selectedRows.push(record);
      selectedRowKeys.push(record.id);
    }
    this.setState({
      selectedRows,
      selectedRowKeys
    });
  };

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

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

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

  getContext = toolBarFlag => {
    if (toolBarFlag) {
      if (toolBarFlag === '1') {
        //新增
        return <ControlModel oprate='add' reloadPage={this.reloadPage} ref={component => this.model = component} />;
      } else {
        const { selectedRows } = this.state;
        return selectedRows.length > 0 ? <ControlModel oprate='edit' mesId={selectedRows[0].id} reloadPage={this.reloadPage} ref={component => this.model = component} /> : '';
      }
    }
  };

  getDetailContext = () => {
    let { showRecord } = this.state;
    if (showRecord) {
      return <MeasuresView mesId={showRecord.id} />;
    }
  }

  getFooterButton = () => {
    return <Button type="minor" onClick={() => this.cancel()}>关闭</Button>;
  }

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

  onOk = () => {
    this.model.handleSubmit();
  };

  controlMeasureDelete = body => {
    AmosAlert.confirm('提示', '确定要删除么?', {
      callback: flag => {
        if (flag) {
          // 确定
          controlMeasureDeleteAction(body).then(
            data => {
              AmosAlert.success('提示', '删除成功');
              this.reloadPage();
            },
            err => {
              AmosAlert.error('错误', err);
            }
          );
        }
      }
    });
  };

  render() {
    let { pagination, isChecked, selectedRowKeys, modal, toolBarFlag, show } = this.state;
    let { dataList, totalCount, fetchData } = this.props;
    let defaultPageConfig = this.pageConfig;
    return (
      <div className="patrol-page-table">
        <AmosGridTable
          columns={getColumns(this)}
          callBack={this.reload}
          isPageable={pagination}
          dataList={dataList}
          totals={totalCount}
          getTableDataAction={param => fetchData(param, this)}
          selectedRowKeys={selectedRowKeys}
          getSelectedRows={this.getSelectedRows}
          rowClassName={this.getRowClassName}
          setPageConfig={this.setPageConfig}
          defaultPageConfig={defaultPageConfig}
          onRowClick={this.onRowClick}
          isChecked={isChecked}
        />
        <Modal
          header={toolBarFlag === '1' ? '添加控制措施' : '编辑控制措施'}
          visible={modal}
          className="param-model"
          width='50%'
          destroyContent
          content={this.getContext(toolBarFlag)}
          onCancel={() => this.cancel()}
          onOk={() => this.onOk()}
          okText="确定"
          cancelText="取消"
          outterClosable={false}
        />
        <Modal
          header="控制措施查看"
          width='40%'
          visible={show}
          className="param-model"
          destroyContent
          content={this.getDetailContext()}
          onCancel={() => this.cancel()}
          footer={this.getFooterButton()}
        />
      </div>
    );
  }
}

ControlModelView.propTypes = {
  dataList: PropTypes.array,
  totalCount: PropTypes.number,
  fetchData: PropTypes.func,
  initToolbarFlag: PropTypes.func
};
export default ControlModelView;
