import React, { Component } from 'react';
import { browserHistory } from 'amos-react-router';
import { AmosAlert, Modal } from 'amos-framework';
import AmosGridTable from './../../common/tableComponent/table/AmosGridTable';
import {
  equipmentFacilitiesDeleteAction,
  getEquipFacilitiesAction,
  equipmentFacilitiesSaveAction,
  getEquipTypeEumDataAction
} from './../../../../services/bizService';
import { pathMapping } from './../../../../routes/customRoutes';
import EquipFacilitiesModel from './EquipFacilitiesModel';
import EquipFacilitiesToolBar from './EquipFacilitiesToolBar';
import SplitterLayout from '../../../common/side/SideQueryLayout';
import EquipFacilitiesSearch from './EquipFacilitiesSearch';

const equipCameraPath = pathMapping.equipCamera;

const equipmentTableColumns = self => {
  return [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}`
    },
    {
      title: '编码',
      dataIndex: 'equipmentNumber',
      key: 'equipmentNumber',
      width: '10%'
    },
    {
      title: '设备名称',
      dataIndex: 'name',
      key: 'name',
      width: '10%'
    },
    {
      title: '设备位号',
      dataIndex: 'code',
      key: 'code',
      width: '5%'
    },
    {
      title: '设备类型',
      dataIndex: 'type',
      key: 'type',
      width: '10%'
    },
    {
      title: '所属工段',
      dataIndex: 'workshopSection',
      key: 'workshopSection',
      width: '10%'
    },
    {
      title: '部门/车间',
      dataIndex: 'departmentName',
      key: 'departmentName',
      width: '10%'
    },
    {
      title: '所在风险区域',
      dataIndex: 'regionDepartmentName',
      key: 'regionDepartmentName',
      width: '10%'
    },
    {
      title: '公司责任人',
      dataIndex: 'companyLeaderUserRealName',
      key: 'companyLeaderUserRealName',
      width: '5%'
    },
    {
      title: '部门责任人',
      dataIndex: 'deptLeaderUserRealName',
      key: 'deptLeaderUserRealName',
      width: '5%'
    },
    {
      title: '车间责任人',
      dataIndex: 'shopLeaderUserRealName',
      key: 'shopLeaderUserRealName',
      width: '5%'
    },
    {
      title: '班组责任人',
      dataIndex: 'classLeaderUserRealName',
      key: 'classLeaderUserRealName',
      width: '5%'
    },
    {
      title: '绑定摄像机',
      dataIndex: 'cameraCount',
      key: 'cameraCount',
      width: '5%',
      render: (text, record, index) => {
        return (
          <span>
            <a href="javascript:;" onClick={() => {self.onDetailClick(record);}}>{text}</a>
          </span>
        );
      }
    }
  ];
};

const defaultHeight = 580;

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

    this.pageConfig = {
      pageNumber: 0,
      pageSize: 10
    },
    this.state = {
      name: '',
      toolbarFlag: 0, //操作按钮flag 0新增，1编辑
      enableEditOp: false,
      pagination: true,
      selectedRows: [],
      selectedRowKeys: [],
      dataList: [], //表格数据集合
      searchParam: [],
      totals: 0, //所有数据总和
      requestParam: [],
      equipmentId: 0, //设备设施ID
      showQuery: false, //是否打开筛选
      equipTypeData: []
    };
  }

  componentDidMount() {
    this.getEquipTypeData();
  }

  onDetailClick(record) {
    let path = {
      pathname: equipCameraPath,
      state: { equipment: record }
    };
    browserHistory.push(path);
  }

  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;
    }
    const { pageNumber, pageSize } = param;
    getEquipFacilitiesAction(searchParam, pageNumber, 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 });
  };

  getEquipTypeData =()=>{
    getEquipTypeEumDataAction().then(data=>{
      this.setState({ equipTypeData: data });
    });
  }

  /**
   * 获取表格刷新方法
   */
  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(',');
          equipmentFacilitiesDeleteAction(ids).then(
            data => {
              AmosAlert.success('提示', '删除成功');
              this.reloadPage();
            },
            err => {
              AmosAlert.error('错误', err);
            }
          );
        }
      }
    });
  }

  filter = (searchParam) => {
    this.setState({ showQuery: true });
  }

  changeStatus = (open) => {
    this.setState({ showQuery: open });
  }

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

  getHead = () => {
    const { enableEditOp, toolbarFlag } = this.state;
    if (enableEditOp) {
      return toolbarFlag === 0 ? '添加设备' : '编辑设备';
    }
  }

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

  getNewUserRealName = (userRealName) =>{
      if(userRealName instanceof Array)
      {
        userRealName =  Array.from(userRealName).join();
      } 
      else
      {
        userRealName =  Array.from(userRealName.split(",")).join(); 
      }
      return userRealName;
  }

  submit = (e) => {
    let { form } = this.model;
    form.validate((valid, dataValues) => {
      if (valid) {
        dataValues.companyLeaderUserId.a
        let companyLeaderUserId = Array.from(new Set(dataValues.companyLeaderUserId)).join();
        //let companyLeaderUserRealName = Array.from(new Set(dataValues.companyLeaderUserRealName)).join();
        let companyLeaderUserRealName = this.getNewUserRealName(dataValues.companyLeaderUserRealName);
        let deptLeaderUserId = Array.from(new Set(dataValues.deptLeaderUserId)).join();
        //let deptLeaderUserRealName = Array.from(new Set(dataValues.deptLeaderUserRealName)).join();
        let deptLeaderUserRealName = this.getNewUserRealName(dataValues.deptLeaderUserRealName);
        let shopLeaderUserId = Array.from(new Set(dataValues.shopLeaderUserId)).join();
        //let shopLeaderUserRealName = Array.from(new Set(dataValues.shopLeaderUserRealName)).join();
        let shopLeaderUserRealName = this.getNewUserRealName(dataValues.shopLeaderUserRealName);
        let classLeaderUserId = Array.from(new Set(dataValues.classLeaderUserId)).join();
        //let classLeaderUserRealName = Array.from(new Set(dataValues.classLeaderUserRealName)).join();
        let classLeaderUserRealName = this.getNewUserRealName(dataValues.classLeaderUserRealName);
        const entry = { ...dataValues, companyLeaderUserId, deptLeaderUserId, shopLeaderUserId, classLeaderUserId, companyLeaderUserRealName
          ,deptLeaderUserRealName,shopLeaderUserRealName,classLeaderUserRealName};
        equipmentFacilitiesSaveAction(entry).then(
          data => {
            AmosAlert.success('提示', '保存成功');
            this.reloadPage();
          },
          err => {
            AmosAlert.error('错误', err);
          }
        );
      } else {
        console.log('error submit!!');
        return false;
      }
    });
  }

  setSearchAndSearch =(form)=>{
    let searchParam = [];
    for (let key in form ){
      searchParam.push(form[key]);
    }
    this.setState({ searchParam }, () => this.getEquipmentListData({ pageNumber: 0, pageSize: 10 }));
  }

  reloadPage = () => {
    this.clearSelectedRows();
    this.state.reload();
  }

  clearSelectedRows = () => {
    this.setState({ selectedRows: [], selectedRowKeys: [],enableEditOp: false });
  }

  render() {
    let { dataList, totalCount, selectedRowKeys, enableEditOp, showQuery,equipTypeData } = this.state;
    let _true_ = true;
    return (
      <div className="important-equipment" style={{ background: '#33333', height: '100%' }}>
        <EquipFacilitiesToolBar
          add={() => this.add()}
          delete={() => this.delete()}
          edit={() => this.edit()}
          filter={() => this.filter()}
        />
        <SplitterLayout open={showQuery} callback={this.changeStatus}>
          <EquipFacilitiesSearch equipTypeData={equipTypeData} search={this.setSearchAndSearch} />
        </SplitterLayout>
        <Modal
          className='match-equipment-bind safety-control-obj-equipment'
          header={this.getHead()}
          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>
    );
  }
}

export default EquipFacilities;
