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 FireStrengthDetail from './FireStrengthDetail';
import FireStrengthEdit from './FireStrengthEdit';
import FireStrengthAdd from './FireStrengthAdd';
import {
  deleteFireStrengthDataAction,
  newFireStrengthDataAction,
  editFireStrengthDataAction,
  getFireStrengthAction
} from '../../../../../services/ledgerService';


const fireStrengthTableColumns = self => {
  return [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}`
    },
    {
      title: '编号',
      dataIndex: 'code',
      key: 'code',
      width: '10%'
    },
    {
      title: '名称',
      dataIndex: 'username',
      key: 'username',
      width: '10%'
    },
    {
      title: '职位',
      dataIndex: 'position',
      key: 'position',
      width: '10%'
    },
    {
      title: '固话',
      dataIndex: 'tel',
      key: 'tel',
      width: '10%'
    },
    {
      title: '移动号码',
      dataIndex: 'phone_num',
      key: 'phone_num',
      width: '10%'
    },
    {
      title: '工作描述',
      dataIndex: 'job_des',
      key: 'job_des',
      width: '20%'
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      width: '20%'
    }
  ];
};


const defaultHeight = 580;

/**
 * 消防车列表
 */
class FireStrengthTableView 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,
      strengthInfo: {},  //消防力量
      fireStrengthEditData: {},
      fireStrengthAddData: {},
      fireStrengthSearchParam: [{
        name: 'type',
        value: 1
      }],
      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.deleteFireStrength();
    }
  }

  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 { strengthInfo, showDetail, showAdd, showEdit } = this.state;
    if (showDetail) {
      return (<FireStrengthDetail strengthId={strengthInfo.id} />);
    } else if (showAdd) {
      return (<FireStrengthAdd callback={this.callbackAdd} ref={component => this.addModel = component} />);
    } else if (showEdit) {
      return (<FireStrengthEdit strengthId={strengthInfo.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>);
    }
  }

  getFireStrengthData = (param) => {
    let { fireStrengthSearchParam } = this.state;
    if (param.current != null) {
      //前端的current 即后端的pageNumber
      param.pageNumber = param.current;
    }
    Object.assign(fireStrengthSearchParam, { ...param });

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

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

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

  showEditMoal = () => {
    let { selectedRows } = this.state;
    if (selectedRows.length <= 0) {
      AmosAlert.warning('请选择需要编辑的消防力量', 0);
      return;
    }
    if (selectedRows.length > 1) {
      AmosAlert.warning('至多选择一条需要编辑的消防力量', 0);
      return;
    }
    this.setState({ show: true, showEdit: true, strengthInfo: selectedRows[0] });
  }

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

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

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

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

  submitData = () => {
    const { showAdd, showEdit, fireStrengthAddData, fireStrengthEditData } = this.state;
    fireStrengthAddData.phoneNum = fireStrengthAddData.phone_num;
    fireStrengthEditData.phoneNum = fireStrengthEditData.phone_num;
    if (showAdd) {
      let { form } = this.addModel;
      form.validate((valid, dataValues) => {
        if (valid) {
          newFireStrengthDataAction(fireStrengthAddData).then(
            data => {
              AmosAlert.success('提示', '创建成功');
              this.cancel();
              this.getFireStrengthData(this.pageConfig);
            },
            err => {
              AmosAlert.error('错误', err);
            }
          );
        }});
    } else if (showEdit) {
      let { form } = this.editModel;
      form.validate((valid, dataValues) => {
        if (valid) {
          editFireStrengthDataAction(fireStrengthEditData.id, fireStrengthEditData).then(
            data => {
              AmosAlert.success('提示', '编辑成功');
              this.cancel();
              this.getFireStrengthData(this.pageConfig);
            },
            err => {
              AmosAlert.error('错误', err);
            }
          );
        }});
    }
  }

  /**
   * 获取表格刷新方法
   */
  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}
        />
        <AmosGridTable
          rowKey="id"
          columns={fireStrengthTableColumns(this)}
          callBack={this.reload}
          dataList={dataList}
          totals={totalCount}
          getTableDataAction={this.getFireStrengthData}
          getSelectedRows={this.getSelectedRows}
          rowClassName={this.getRowClassName}
          setPageConfig={this.setPageConfig}
          getPanelHeight={this.getPanelHeight}
          defaultPageConlHeight={this.getPanelHeight}
          onRowClick={this.onRowClick}
          isChecked={true}
          selectedRowKeys={selectedRowKeys}
        />
      </div>
    );
  }
}

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