import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Modal, Button, AmosAlert } from 'amos-framework';
import AmosGridTable from './../../../common/tableComponent/table/AmosGridTable';
import FireWaterDetail from './FireWaterDetail';
import FireWaterEdit from './FireWaterEdit';
import FireWaterAdd from './FireWaterAdd';
import FireWaterToolBar from './FireWaterToolBar';

import { deleteFireWaterDataAction, newFireWaterDataAction, editFireWaterDataAction, getFireWaterAction } from '../../../../../services/ledgerService';

const fireWaterTableColumns = self => {
  return [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}`
    },
    {
      title: '编号',
      dataIndex: 'code',
      key: 'code',
      width: '10%'
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'type',
      width: '10%'
    },
    {
      title: '区域',
      dataIndex: 'productionArea',
      key: 'productionArea',
      width: '15%'
    },
    {
      title: '楼层',
      dataIndex: 'floor3d',
      key: 'floor3d',
      width: '10%'
    },
    {
      title: '房间',
      dataIndex: 'room',
      key: 'room',
      width: '10%'
    },
    {
      title: '位置',
      dataIndex: 'address',
      key: 'address',
      width: '35%'
    }
  ];
};

const defaultHeight = 580;

/**
 * 消防车列表
 */
class WaterView extends Component {
  constructor(props) {
    super(props);

    this.pageConfig = {
      pageNumber: 0,
      pageSize: 10
    },
    this.state = {
      pagination: true,
      selectedRows: [],
      selectedRowKeys: [],
      size: 'small', //表格大小
      searchParam: [],
      totals: 0, //所有数据总和
      showDetail: false, //是否显示详情
      showAdd: false, //是否显示详情
      showEdit: false, //是否显示详情
      show: false,
      stationInfo: {},  //消防泡沫间
      fireStationEditData: {},
      fireStationAddData: {},
      fireWaterSearchParam: [],
      dataList: [],
      totalCount: 0,
      type: ''
    };
  }

  componentWillMount() {
    let type = this.props.type;
    this.setState({ type });
  }

  componentWillReceiveProps = (nextProps) => {
    const { oprType, type } = nextProps;
    if (oprType === 1) {
      this.setState({ show: true, showAdd: true });
    } else if (oprType === 2) {
      this.showEditMoal();
    } else if (oprType === 3) {
      this.deleteFireStation();
    }
    this.setState({ type });
  }

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

  getFireWaterData = (param) => {
    let { fireWaterSearchParam, type } = this.state;

    let resourceType = new Object();
    resourceType.name = 'type';
    resourceType.value = type;

    if (param.current != null) {
      //前端的current 即后端的pageNumber
      param.pageNumber = param.current;
    }
    fireWaterSearchParam = fireWaterSearchParam.filter(item => item.name !== 'type');
    Object.assign(fireWaterSearchParam, { ...param });
    fireWaterSearchParam.push(resourceType);

    getFireWaterAction(fireWaterSearchParam, param.pageNumber, param.pageSize).then(data => {
      this.setState({
        dataList: data.content,
        totalCount: data.totalElements,
        selectedRowKeys: [],
        selectedRows: []
      });
    });
  }

  getPanelHeight = () => {
    return defaultHeight;
  };

  setPageConfig = ({ pageSize, current }) => {
    if (pageSize !== undefined) {
      this.pageConfig.pageSize = pageSize;
    }
    if (current !== undefined) {
      this.pageConfig.current = current;
    }
  };

  getRowClassName = (record, index) => {
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys.findIndex(item => item === record.id) >= 0) {
      return 'highlight-row';
    } else {
      return 'normal-row';
    }
  };

  getSelectedRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  getContext = () => {
    const { stationInfo, showDetail, showAdd, showEdit, type } = this.state;
    if (showDetail) {
      return (<FireWaterDetail stationId={stationInfo.id} type={type} />);
    } else if (showAdd) {
      return (<FireWaterAdd callback={this.callbackAdd} type={type} ref={component => this.addModel = component} />);
    } else if (showEdit) {
      return (<FireWaterEdit stationId={stationInfo.id} callback={this.callbackEdit} type={type} ref={component => this.editModel = component} />);
    }
  }

  getHead = () => {
    const { showDetail, showAdd, showEdit, type } = this.state;
    if (showDetail) {
      return type === '1' ? '消防栓详情' : '消防水池详情';
    } else if (showAdd) {
      return type === '1' ? '新增消防栓' : '新增消防水池';
    } else if (showEdit) {
      return type === '1' ? '编辑消防栓' : '新增消防水池';
    }
  }

  getFooter = () => {
    const { showDetail } = this.state;
    if (!showDetail) {
      return (<div><Button type="minor" onClick={() => this.cancel()}>取消</Button><Button  onClick={() => this.submitData()}>确定</Button></div> );
    } else {
      return (<Button onClick={() => this.cancel()}>取消</Button>);
    }
  }

  callbackAdd = (fireStationAddData) => {
    this.setState({ fireStationAddData });
  }

  callbackEdit = (fireStationEditData) => {
    this.setState({ fireStationEditData });
  }

  showEditMoal = () => {
    let { selectedRows , type } = this.state;
    let str = type === '1' ? '消防栓' : '消防水池';
    if (selectedRows.length <= 0) {
      AmosAlert.warning('提示', '请先点击选择需要编辑的行');
      return;
    }
    this.setState({ show: true, showEdit: true, stationInfo: selectedRows[0] });
  }

  deleteFireStation = () => {
    let { selectedRowKeys } = this.state;

    if (selectedRowKeys === undefined ||  selectedRowKeys.length <= 0 ) {
      AmosAlert.warning('提示', '请先点击选择需要删除的行');
      return;
    }
    let ids = selectedRowKeys.join(',');

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

  cancel() {
    this.setState({
      show: false,
      showAdd: false,
      showEdit: false,
      showDetail: false
    });
  }

  submitData = () => {
    const { showAdd, showEdit, fireStationAddData, fireStationEditData, type } = this.state;
    if (showAdd) {
      let { form } = this.addModel;
      form.validate((valid, dataValues) => {
        if (valid) {
          fireStationAddData.type = type;
          newFireWaterDataAction(fireStationAddData).then(
            data => {
              AmosAlert.success('提示', '创建成功');
              this.cancel();
              // this.getFireWaterData(this.pageConfig);
              this.state.reload();
            },
            err => {
              AmosAlert.error('错误', err);
            }
          );
        }});
    } else if (showEdit) {
      let { form } = this.editModel;
      form.validate((valid, dataValues) => {
        if (valid) {
          editFireWaterDataAction(fireStationEditData.id, fireStationEditData).then(
            data => {
              AmosAlert.success('提示', '编辑成功');
              this.cancel();
              this.getFireWaterData(this.pageConfig);
            },
            err => {
              AmosAlert.error('错误', err);
            }
          );
        }});
    }
  }

  add = () => {
    this.setState({ show: true, showAdd: true });
  }

  edit = () => {
    this.showEditMoal();
  }

  delete = () => {
    this.deleteFireStation();
  }

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

  render() {
    let { show, selectedRowKeys, dataList, totalCount } = this.state;
    return (
      <div className="fire-resource-truck" style={{ background: '#33333', height: '100%' }}>
        <Modal
          header={this.getHead()}
          footer={this.getFooter()}
          width='45%'
          visible={show}
          destroyContent
          onCancel={() => this.cancel()}
          onOk={() => {}}
          content={this.getContext()}
          outterClosable={false}
        />
        <FireWaterToolBar add={() => this.add()} delete={() => this.delete()} edit={() => this.edit()} getTableListData={this.getFireWaterData} pageConfig={this.pageConfig} />
        <AmosGridTable
          rowKey="id"
          columns={fireWaterTableColumns(this)}
          callBack={this.reload}
          dataList={dataList}
          totals={totalCount}
          getTableDataAction={this.getFireWaterData}
          getSelectedRows={this.getSelectedRows}
          rowClassName={this.getRowClassName}
          setPageConfig={this.setPageConfig}
          getPanelHeight={this.getPanelHeight}
          defaultPageConlHeight={this.getPanelHeight}
          onRowClick={this.onRowClick}
          isChecked={true}
          selectedRowKeys={selectedRowKeys}
        />
      </div>
    );
  }
}

WaterView.propTypes = {
  oprType: PropTypes.number,
  type: PropTypes.string
};
export default WaterView;
