import React, { Component } from 'react';
import { browserHistory } from 'amos-react-router';
import _amosTool from 'amos-tool';
import SysConsts from 'amos-processor/lib/config/consts';
import { Input, AmosAlert, Modal, Button } from 'amos-framework';
import AmosGridTable from './../../common/tableComponent/table/AmosGridTable';
import { getEquipmentListAction, deleteEquipmentAction } from './../../../../services/ledgerService';
import { pathMapping } from './../../../../routes/customRoutes';
import EquipmentModel from './EquipmentModel';
import BizIcon from './../../../common/icon/BizIcon';
import { FasSerUrl } from '../../../../consts/urlConsts';

const matchEquipmentPath = pathMapping.matchEquipment;
const ls = _amosTool.Store.lsTool;
const apiKey = SysConsts.api_key;
const token = SysConsts.token;
const updateEquipmentUrl = FasSerUrl.equipmentUpdateUrl;

const equipmentTableColumns = self => {
  return [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}`
    },
    {
      title: '编号',
      dataIndex: 'code',
      key: 'code',
      width: '15%'
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: '25%'
    },
    {
      title: '建/构筑物',
      dataIndex: 'building',
      key: 'building',
      width: '25%'
    },
    {
      title: '位置',
      dataIndex: 'address',
      key: 'address',
      width: '15%'
    },
    {
      title: '配套设备',
      dataIndex: '',
      key: '',
      width: '10%',
      render: (text, record, index) => {
        return (
          <span>
            <a href="javascript:;" onClick={() => {self.onDetailClick(record);}}>查看</a>
          </span>
        );
      }
    }
  ];
};

const defaultHeight = 580;

/**
 * 重点设备
 */
class Equipment extends Component {
  constructor(props) {
    super(props);

    this.pageConfig = {
      pageNumber: 0,
      pageSize: 10
    },
    this.state = {
      name: '',
      equipClassify: '',
      toolbarFlag: 0, //操作按钮flag 0新增，1编辑
      enableEditOp: false,
      pagination: true,
      selectedRows: [],
      selectedRowKeys: [],
      dataList: [], //表格数据集合
      size: 'small', //表格大小
      searchParam: [],
      totals: 0, //所有数据总和
      requestParam: [],
      equipmentId: 0 //重点设备ID
    };
  }

  onDetailClick(record) {
    let path = {
      pathname: matchEquipmentPath,
      state: { equipmentId: record.id }
    };
    browserHistory.push(path);
    browserHistory.go();
  }

  onChange(type, value) {
    if (type === 'name') {
      this.setState({ name: value });
    } else {
      this.setState({ equipClassify: value });
    }
    let searchParam = [{ name: type, value, type: 'LIKE' }];
    this.getEquipmentListData(searchParam);
  }

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

  getEquipmentListData = param => {
    let { searchParam } = this.state;
    if (param.current != null) {
      //前端的current 即后端的pageNumber
      param.pageNumber = param.current;
    }
    Object.assign(searchParam, { ...param });
    getEquipmentListAction(searchParam, searchParam.pageNumber, searchParam.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 });
  };

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

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

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

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

    this.setState({
      enableEditOp: true,
      toolbarFlag: 1,
      equipmentId: equipId
    });
  }

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

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

  getEquipmentFormContext = () => {
    const { equipmentId, toolbarFlag } = this.state;
    return (<EquipmentModel equipmentId={equipmentId} toolbarFlag={toolbarFlag} ref={component => this.model = component} />);
  }

  submit = (e) => {
    let { form } = this.model;
    form.validate((valid, dataValues) => {
      if (valid) {
        delete dataValues.createDate;
        let formData = new FormData();

        dataValues.imageUrl1 && formData.append('img1', dataValues.imageUrl1[0]);
        dataValues.imageUrl2 && formData.append('img2', dataValues.imageUrl2[0]);
        dataValues.imageUrl3 && formData.append('img3', dataValues.imageUrl3[0]);
        dataValues.imageUrl4 && formData.append('img4', dataValues.imageUrl4[0]);

        Object.keys(dataValues).map(item => {
          if (item === 'chargeDeptId' && dataValues[item] === null) {
            formData.append(item, -1);
          } else if (item === 'chargeUserId' && dataValues[item] === null) {
            formData.append(item, -1);
          } else if (item === 'fireStationId' && dataValues[item] === null) {
            formData.append(item, -1);
          } else {
            formData.append(item, dataValues[item]);
          }
        });

        fetch(updateEquipmentUrl, {
          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.state.reload();
          this.setState({
            enableEditOp: false
          });
        })
        .catch(e => {
          AmosAlert.error('错误', '保存失败');
        });
      } else {
        console.log('error submit!!');
        return false;
      }
    });
  }

  render() {
    let { name, dataList, totalCount, selectedRowKeys, enableEditOp } = this.state;
    let _true_ = true;
    return (
      <div className="important-equipment" style={{ background: '#33333', height: '100%' }}>
        <div className="important-equipment-toolbar">
          <div className='important-equipment-title'>
            <span>重点设备</span>
          </div>
          <div className='important-equipment-tools'>
            <span>重点设备名称：</span>
            <Input value={name} onChange={e => this.onChange('name', e.target.value)} />
            <Button icon={<BizIcon icon="tianjia" />} transparent onClick={() => this.add()} />
            <Button icon={<BizIcon icon="xiugai" />} transparent onClick={() => this.edit()} />
            <Button icon={<BizIcon icon="shanchu" />} transparent onClick={() => this.delete()} />
          </div>
        </div>
        <Modal
          className='match-equipment-bind'
          header="添加重点设备"
          width='50%'
          visible={enableEditOp}
          destroyContent
          onCancel={() => this.cancel('add')}
          content={this.getEquipmentFormContext()}
          onOk={(e) => this.submit(e)}
          outterClosable={!_true_}
        />
        <AmosGridTable
          rowKey="id"
          columns={equipmentTableColumns(this)}
          callBack={this.reload}
          dataList={dataList}
          totals={totalCount}
          getTableDataAction={this.getEquipmentListData}
          getSelectedRows={this.getSelectedRows}
          rowClassName={this.getRowClassName}
          setPageConfig={this.setPageConfig}
          getPanelHeight={this.getPanelHeight}
          defaultPageConlHeight={this.getPanelHeight}
          isChecked={_true_}
          selectedRowKeys={selectedRowKeys}
          onRowClick={this.onRowClick}
        />
      </div>
    );
  }
}

Equipment.propTypes = {
};
export default Equipment;
