import React, { Component } from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import { Modal, AmosAlert, Button } from 'amos-framework';
import AmosGridTable from './../../../common/tableComponent/table/AmosGridTable';
import MonitorPointConfig from './MonitorPointConfig';
import { deleteFireEquipmentAction, addFireEquipmentAction } from './../../../../../services/ledgerService';
import FireEquipmentModel from './FireEquipmentModel';
import FireEquipmentToolBar from './FireEquipmentToolBar';
import BizIcon from './../../../../common/icon/BizIcon';

const EquipClassifyEnum = { 0: '设备类', 1: '耗材类', 2: '视频监控', 3: '灭火器材' };
const fireEquipmentTableColumns = self => {
  return [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}`
    },
    {
      title: '编号',
      dataIndex: 'code',
      key: 'code',
      width: '6%'
    },
    {
      title: '装备编码',
      dataIndex: 'equip_code',
      key: 'equip_code',
      width: '6%'
    },
    {
      title: '装备名称',
      dataIndex: 'name',
      key: 'name',
      width: '9%'
    },
    {
      title: '分类',
      dataIndex: 'equip_classify',
      key: 'equip_classify',
      width: '5%',
      render: (text) => EquipClassifyEnum[text]
    },
    {
      title: '类型',
      dataIndex: 'equip_type',
      key: 'equip_type',
      width: '5%'
    },
    {
      title: '规格型号',
      dataIndex: 'model',
      key: 'model',
      width: '5%'
    },
    {
      title: '保养周期(月)',
      dataIndex: 'maintenance_cycle',
      key: 'maintenance_cycle',
      width: '4%'
    },
    {
      title: '厂商',
      dataIndex: 'manufacturer',
      key: 'manufacturer',
      width: '10%'
    },
    {
      title: '品牌',
      dataIndex: 'brand',
      key: 'brand',
      width: '5%'
    },
    {
      title: '生产日期',
      dataIndex: 'production_date',
      key: 'production_date',
      width: '7%',
      render: (text) => {return moment(text).format('YYYY-MM-DD');}
    },
    {
      title: '有效时间',
      dataIndex: 'effective_date',
      key: 'effective_date',
      width: '7%',
      render: (text) => {return moment(text).format('YYYY-MM-DD');}
    },
    {
      title: '数量',
      dataIndex: 'number',
      key: 'number',
      width: '3%'
    },
    {
      title: '单位',
      dataIndex: 'unit',
      key: 'unit',
      width: '3%'
    },
    {
      title: '建/构筑物',
      dataIndex: 'production_area',
      key: 'production_area',
      width: '6%'
    },
    {
      title: '楼层',
      dataIndex: 'floor3d',
      key: 'floor3d',
      width: '3%'
    },
    {
      title: '房间',
      dataIndex: 'room',
      key: 'room',
      width: '4%'
    },
    {
      title: '配置监测点',
      dataIndex: '',
      key: '',
      width: '6%',
      render: (text, record, index) => {
        let showOp = false;
        if (text.equip_classify === 0) {
          showOp = true;
        }
        return !showOp ? '' : (
          <Button icon={<BizIcon icon="peizhijiancedian" />} transparent onClick={() => self.onMonitorPointConfigClick(record)} style={{ paddingLeft: '40%' }} />
        );
      }
    }
  ];
};

const defaultHeight = 580;

/**
 * 消防设备
 */
class FireEquipmentView extends Component {
  constructor(props) {
    super(props);

    this.pageConfig = {
      pageNumber: 0,
      pageSize: 10
    },
    this.state = {
      pagination: true,
      selectedRows: [],
      selectedRowKeys: [],
      dataList: [], //表格数据集合
      size: 'small', //表格大小
      searchParam: [],
      totals: 0, //所有数据总和
      requestParam: [],
      showDetail: false, //是否显示详情
      showAdd: false, //是否显示添加页面
      showEdit: false, //是否显示编辑页面
      enableConfig: false,   //是否打开配置监测点页面
      show: false, //是否打开
      fireEquipmentId: 0,  //设备ID
      operateFlag: 0  //操作按钮0：新增，1：修改/查看
    };
  }

  onMonitorPointConfigClick = record => {
    this.setState({
      enableConfig: true,
      fireEquipmentId: record.id
    });
  };

  onDetailClick = record => {
    // this.setState({
    //   showDetail: true,
    //   show: true,
    //   fireEquipmentId: record.id,
    //   operateFlag: 1
    // });
  };

  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 highlight = this.highlight;
    // if (highlight && record.id === highlight) {
    //   return 'highlight-row';
    // } else {
    //   return 'normal-row';
    // }
    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 });
  };

  getConfigContext = () => {
    const { fireEquipmentId } = this.state;
    return (<MonitorPointConfig fireEquipmentId={fireEquipmentId} />);
  }

  cancel = (key) => {
    const { enableConfig } = this.state;
    if (enableConfig && 'config' === key) {
      this.setState({ enableConfig: false });
    }
  }

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

  add() {
    this.setState({
      show: true,
      showAdd: true,
      toolbarFlag: 0
    });
  }

  edit() {
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys === undefined || selectedRowKeys.length <= 0) {
      AmosAlert.warning('提示', '请先选择需要编辑的设备');
      return;
    }

    let fireEquipId = selectedRowKeys;
    if (selectedRowKeys.length > 1) {
      fireEquipId = selectedRowKeys[selectedRowKeys.length - 1];
    }

    this.setState({
      show: true,
      toolbarFlag: 1,
      showEdit: true,
      fireEquipmentId: fireEquipId
    });
  }

  delete() {
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys === undefined || selectedRowKeys.length <= 0) {
      AmosAlert.warning('提示', '请先选择需要删除的消防设备');
      return;
    }
    AmosAlert.confirm('提示', '确定删除指定消防设备?', {
      callback: flag => {
        if (flag) {
          // 确定删除
          let ids = selectedRowKeys.join(',');
          deleteFireEquipmentAction(ids).then(
            data => {
              AmosAlert.success('提示', '删除成功');
              this.state.reload();
            },
            err => {
              AmosAlert.error('错误', err);
            }
          );
        }
      }
    });
  }

  getToolButton = () => {
    let buttonArr = new Array();
    buttonArr.push(<Button onClick={() => this.add()} icon="add" />);
    buttonArr.push(<Button onClick={() => this.edit()} icon="edit" />);
    buttonArr.push(<Button onClick={() => this.delete()} icon="delete" />);
    return buttonArr;
  }

  editCancel = (key) => {
    this.setState({
      show: false,
      showAdd: false,
      showEdit: false,
      showDetail: false
    });
  }

  submitData = (e) => {
    let { form } = this.model;
    form.validate((valid, dataValues) => {
      if (valid) {
        let fireEquipment = dataValues;
        addFireEquipmentAction(fireEquipment).then(
          data => {
            AmosAlert.success('提示', '保存成功');
            this.state.reload();
            this.editCancel();
          },
          error => {
            AmosAlert.error('错误', '保存失败');
          }
        );
      } else {
        console.log('error submit!!');
        return false;
      }
    });
  }

  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.editCancel()}>取消</Button><Button  onClick={() => this.submitData()}>确定</Button></div> );
    } else {
      return (<Button onClick={() => this.editCancel()}>取消</Button>);
    }
  }

  getContext = () => {
    let { showAdd, fireEquipmentId, operateFlag } = this.state;
    if (showAdd) {
      operateFlag = 0;
    } else {
      operateFlag = 1;
    }
    return (<FireEquipmentModel operateFlag={operateFlag} fireEquipmentId={fireEquipmentId} ref={component => this.model = component} />);
  }

  render() {
    let { show, enableConfig, selectedRowKeys } = this.state;
    let { dataList, totalCount, getTableListData } = this.props;
    let _true_ = true;
    return (
      <div className="fire-resource-equipment" style={{ background: '#33333', height: '100%' }}>
        <Modal
          className='monitor-point-config'
          header="配置监测点"
          width='65%'
          visible={enableConfig}
          destroyContent
          noDefaultFooter
          onCancel={() => this.cancel('config')}
          content={this.getConfigContext()}
          outterClosable={!_true_}
        />
        <Modal
          className='match-equipment-bind'
          header={this.getHead()}
          footer={this.getFooter()}
          width='50%'
          visible={show}
          destroyContent
          onCancel={() => this.editCancel('add')}
          content={this.getContext()}
          onOk={(e) => this.submitData(e)}
          outterClosable={!_true_}
        />
        <FireEquipmentToolBar add={() => this.add()} delete={() => this.delete()} edit={() => this.edit()} getTableListData={getTableListData} pageConfig={this.pageConfig} />
        <AmosGridTable
          rowKey="id"
          columns={fireEquipmentTableColumns(this)}
          callBack={this.reload}
          dataList={dataList}
          totals={totalCount}
          getTableDataAction={param => getTableListData(param, this)}
          getSelectedRows={this.getSelectedRows}
          rowClassName={this.getRowClassName}
          setPageConfig={this.setPageConfig}
          getPanelHeight={this.getPanelHeight}
          defaultPageConlHeight={this.getPanelHeight}
          isChecked={_true_}
          selectedRowKeys={selectedRowKeys}
          // onRowDoubleClick={this.onDetailClick}
          onRowClick={this.onRowClick}
        />
      </div>
    );
  }
}

FireEquipmentView.propTypes = {
  fireEquipmentId: PropTypes.number,
  totalCount: PropTypes.number,
  dataList: PropTypes.array,
  getTableListData: PropTypes.func
};
export default FireEquipmentView;
