import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Modal, Button, AmosAlert } from 'amos-framework';
import { browserHistory } from 'amos-react-router';
import _amosTool from 'amos-tool';
import SysConsts from 'amos-processor/lib/config/consts';
import AmosGridTable from './../../../common/tableComponent/table/AmosGridTable';
import FireReourceDetail from './FireFoamDetail';
import FireReourceEdit from './FireFoamEdit';
import FireReourceAdd from './FireFoamAdd';
import { deleteFireStationDataAction, getFireStationAction } from '../../../../../services/ledgerService';
import FireFoamToolBar from './fireFoamToolBar';
import { pathMapping } from './../../../../../routes/customRoutes';
import { FasSerUrl } from '../../../../../consts/urlConsts';

const fireFoamPath = pathMapping.stationMatches;
const ls = _amosTool.Store.lsTool;
const apiKey = SysConsts.api_key;
const token = SysConsts.token;
const url = FasSerUrl.getFireStationInfoUrl;

const fireFoamTableColumns = self => {
  return [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}`
    },
    {
      title: '编号',
      dataIndex: 'code',
      key: 'code',
      width: '17%'
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: '25%'
    },
    {
      title: '位置',
      dataIndex: 'address',
      key: 'address',
      width: '30%'
    },
    {
      title: '配套设备',
      dataIndex: '',
      key: '',
      width: '20%',
      render: (text, record, index) => {
        return (
          <span>
            <a href="javascript:;" onClick={() => {self.matchEquipments(record);}}>查看</a>
          </span>
        );
      }
    }
  ];
};


const defaultHeight = 580;

/**
 * 消防泡沫间
 */
class FireFoamable extends Component {
  constructor(props) {
    super(props);

    this.pageConfig = {
      type: 1,
      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: {},
      fireStationSearchParam: [{
        name: 'type',
        value: 2
      }],
      dataList: [],
      totalCount: 0
    };
  }

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

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

  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 } = this.state;
    if (showDetail) {
      return (<FireReourceDetail stationId={stationInfo.id} />);
    } else if (showAdd) {
      return (<FireReourceAdd callback={this.callbackAdd} ref={component => this.addModel = component} />);
    } else if (showEdit) {
      return (<FireReourceEdit stationId={stationInfo.id} callback={this.callbackEdit} ref={component => this.editModel = component} />);
    }
  }

  getHead = () => {
    const { showDetail, showAdd, showEdit } = this.state;
    if (showDetail) {
      return '消防泡沫间详情';
    } else if (showAdd) {
      return '新增消防泡沫间';
    } else if (showEdit) {
      return '编辑消防泡沫间';
    }
  }

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

  getFireStationData = (param) => {
    let { fireStationSearchParam } = this.state;
    if (param.current != null) {
      //前端的current 即后端的pageNumber
      param.pageNumber = param.current;
    }
    Object.assign(fireStationSearchParam, { ...param });
    let exits = false;
    for (let i = 0; i < fireStationSearchParam.length; i++) {
      if (fireStationSearchParam[i].name === 'type') {
        exits = true;
      }
    }
    if (!exits) {
      fireStationSearchParam.push({ name: 'type', value: 2 });
    }

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

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

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

  showEditMoal = () => {
    let { selectedRows } = this.state;
    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){
          // 确定删除
          deleteFireStationDataAction(ids).then(data => {
            AmosAlert.success('提示', '删除成功');
            // this.getFireStationData(this.pageConfig);
            this.state.reload();
          }, err => {
            AmosAlert.error('错误', err);
          });
        }
      }
    });
  }

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

  submitData = () => {
    const { showAdd, showEdit } = this.state;
    if (showAdd) {
      let { form } = this.addModel;
      form.validate((valid, dataValues) => {
        if (valid) {
          this.saveFireStation(dataValues);
        }
      });
    } else if (showEdit) {
      let { form } = this.editModel;
      form.validate((valid, dataValues) => {
        if (valid) {
          this.saveFireStation(dataValues);
        }
      });
    }
  }

  saveFireStation(station) {
    let formData = new FormData();
    let imgFiles = station.picture;
    imgFiles && imgFiles.forEach(file => {
      formData.append('file', file);
    });
    Object.keys(station).map(item => {
      if (item !== 'picture') {
        formData.append(item, station[item]);
      }
    });
    fetch(url, {
      method: 'post',
      headers: {
        Accept: 'application/json;charset=UTF-8',
        'X-Api-Key': _amosTool.Store.getCookieByName(apiKey),
        'X-Access-Token': ls.read(token)
      },
      body: formData
    })
      .then(e => {
        AmosAlert.success('提示', '保存成功');
        this.cancel();
        // this.getFireStationData(this.pageConfig);
        this.state.reload();
      })
      .catch(e => {
        AmosAlert.error('错误', '保存失败');
      });
  }

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

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

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

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

  matchEquipments(record) {
    let fireStation = record;
    let path = {
      pathname: fireFoamPath,
      state: { fireStation, key: '3' }
    };
    browserHistory.push(path);
  }

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

FireFoamable.propTypes = {
  oprType: PropTypes.number
};
export default FireFoamable;
