import React, { Component } from 'react';
import { AmosAlert, Modal, Button } from 'amos-framework';
import AmosGridTable from './../../common/tableComponent/table/AmosGridTable';
import TaskWorkModel from './TaskWorkModel';
import TaskWorkToolBar from './TaskWorkToolBar';
import SplitterLayout from '../../../common/side/SideQueryLayout';
import SearchView from './SearchView';
import WorkFlowStatus from './WorkFlowStatus';
import {
  getTaskworkDataAction,
  saveTaskworkAction,
  deleteTaskworkAction,
  getTaskworkTypeDataAction,
  getRegionDepartmentTreeAction
} from './../../../../services/bizService';
import { startTaskworkFlow } from './../../../../services/patrolService';
import TaskworkView from './TaskworkView';

const taskWorkTableColumns = self => {
  return [
    {
      title: '序号',
      render: (text, record, index) => `${index + 1}`
    },
    {
      title: '作业活动名称',
      dataIndex: 'name',
      key: 'name',
      width: '10%'
    },
    {
      title: '作业活动类型',
      dataIndex: 'type',
      key: 'type',
      width: '9%',
      render: text => self.getTypeName(text)
    },
    {
      title: '作业活动岗位',
      dataIndex: 'post',
      key: 'post',
      width: '9%'
    },
    {
      title: '作业活动部位',
      dataIndex: 'part',
      key: 'part',
      width: '9%'
    },
    {
      title: '所属风险区域',
      dataIndex: 'regionName',
      key: 'regionName',
      width: '9%'
    },
    {
      title: '部门/车间',
      dataIndex: 'departmentName',
      key: 'departmentName',
      width: '9%'
    },
    {
      title: '班组',
      dataIndex: 'groupName',
      key: 'groupName',
      width: '20%'
    },
    {
      title: '作业活动步骤',
      dataIndex: 'step',
      key: 'step',
      width: '7%',
      render: (text, record, index) => {
        let stepCount = 0;
        record && record.contentList && (stepCount = record.contentList.length);
        return (
          <span>
            <a href="javascript:;" onClick={() => {self.onDetailClick(record, 'step');}}>{stepCount}</a>
          </span>
        );
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: '5%',
      render: (text, record, index) => {
        return (
          <span>
            <a href="javascript:;" onClick={() => {self.onDetailClick(record, 'status');}}>{text > 1 ? '流程中' : '未流程中'}</a>
          </span>
        );
      }
    }
  ];
};

const defaultHeight = 580;

/**
 * 作业活动
 *
 * @class EquipFacilities
 * @extends {Component}
 */
class TaskWork extends Component {
  constructor(props) {
    super(props);

    this.pageConfig = {
      pageNumber: 0,
      pageSize: 10
    },
    this.state = {
      name: '',
      statusView: false,
      equipClassify: '',
      toolbarFlag: 0, //操作按钮flag 0新增，1编辑
      enableEditOp: false,
      lookupOp: false,
      pagination: true,
      selectedRows: [],
      selectedRowKeys: [],
      dataList: [], //表格数据集合
      size: 'small', //表格大小
      searchParam: [],
      totals: 0, //所有数据总和
      requestParam: [],
      regionDepartmentTree: [], //分区、部门、班组树
      taskworkId: 0, //作业活动ID
      showQuery: false //是否打开筛选
    };
  }

  componentDidMount() {
    getTaskworkTypeDataAction().then(data => {
      this.setState({ typeData: data });
    });
    getRegionDepartmentTreeAction().then(data => {
      this.setState({ regionDepartmentTree: data });
    });
  }

  onDetailClick(record, type) {
    if (type === 'step') {//查看作业活动步骤
      this.setState({ lookupOp: true, showRecord: record });
    }
    if (type === 'status') {//查看作业活动流程
      this.setState({ statusView: true, showRecord: record });
    }
  }

  onChange(type, value) {
    if (type === 'name') {
      this.setState({ name: value });
    } else {
      this.setState({ equipClassify: value });
    }
    let searchParam = [{ name: type, value, type: 'LIKE' }];
    this.getTaskWorkListData(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
    });
  }

  getTypeName = (type) => {
    const { typeData } = this.state;
    let tempType = [];
    tempType = typeData && typeData.filter(item => item.dictDataKey === type);
    let typeName = tempType && tempType[0] ? tempType[0].dictDataValue : '';
    return typeName;
  }

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

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

  /**
   * 获取表格刷新方法
   */
  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;
    }

    if (selectedRowKeys.length > 1) {
      AmosAlert.warning('提示', '请选择一条作业活动进行编辑');
      return;
    }

    let taskworkId = selectedRowKeys[0];

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

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

  startProcess = () => {
    let { selectedRowKeys,selectedRows } = this.state;
    if (selectedRowKeys === undefined || selectedRowKeys.length <= 0) {
      AmosAlert.warning('提示', '请先选择需要启动的作业活动');
      return;
    }
    let emptyStepTaskwork = selectedRows.filter(e=>(e.contentList || []).length === 0);
    if ((emptyStepTaskwork || []).length > 0 ) {
      AmosAlert.warning('提示', '作业活动步骤为空，不能发起执行流程');
      return;
    }
    AmosAlert.confirm('提示', '是否发起作业活动执行流程?', {
      callback: (flag) => {
        if (flag){
          let taskworkIds = selectedRowKeys.join(',');
          this.startTaskworkExecuteFlow(taskworkIds);
        }
      }
    });
  }

  startTaskworkExecuteFlow =(taskworkIds)=>{
    startTaskworkFlow(taskworkIds).then(data => {
      AmosAlert.success('启动成功');
    }, err => {
      AmosAlert.error('启动失败');
    });
  }


  showProcess = () => {
    console.log('showProcess');
    let { selectedRowKeys } = this.state;
    if (selectedRowKeys === undefined || selectedRowKeys.length <= 0) {
      AmosAlert.warning('提示', '请先选择需要查看的作业活动');
      return;
    }

    if (selectedRowKeys.length > 1) {
      AmosAlert.warning('提示', '请选择一条作业活动进行查看');
      return;
    }
  }

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

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

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

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

  getTaskWorkFormContext = () => {
    const { taskworkId, toolbarFlag, typeData, regionDepartmentTree } = this.state;
    return (<TaskWorkModel typeData={typeData} regionDepartmentTree={regionDepartmentTree} taskworkId={taskworkId} toolbarFlag={toolbarFlag} ref={component => this.model = component} />);
  }

  getTaskWorkData = (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 });
    }
  }

  getFooterButton = () => {
    return <Button type="minor" onClick={() => this.cancel('lookup')}>关闭</Button>;
  }

  getTaskWorkContextDetail = () => {
    let { showRecord } = this.state;
    if (showRecord) {
      return <TaskworkView taskwork={showRecord} />;
    }
  }

  getStatusView = (statusView) =>{
    let { showRecord } = this.state;
    if (statusView && showRecord) {
      return <WorkFlowStatus instanceId={showRecord.instanceId} />;
    }
  }

  submit = (e) => {
    let { form } = this.model;
    form.validate((valid, dataValues) => {
      if (valid) {
        let taskwork = {};
        Object.assign(taskwork, dataValues);
        taskwork.groupId = taskwork.groupId.join();
        saveTaskworkAction(taskwork).then(data => {
          AmosAlert.success('提示', '保存成功');
          this.state.reload();
          this.setState({
            enableEditOp: false
          });
        }, err => {
          AmosAlert.error('保存失败', err);
        }).catch(e => {
          AmosAlert.error('错误', '保存失败');
        });
      } else {
        console.log('error submit!!');
        return false;
      }
    });
  }

  render() {
    let { dataList, totalCount, selectedRowKeys, enableEditOp, showQuery, lookupOp, typeData, regionDepartmentTree, statusView } = this.state;
    let _true_ = true;
    return (
      <div className="important-equipment" style={{ background: '#33333', height: '100%' }}>
        <TaskWorkToolBar
          add={() => this.add()}
          delete={() => this.delete()}
          edit={() => this.edit()}
          startProcess={() => this.startProcess()}
          showProcess={() => this.showProcess()}
          filter={() => this.filter()}
          getTableListData={this.getTaskWorkData}
          pageConfig={this.pageConfig}
        />
        <SplitterLayout open={showQuery} callback={this.changeStatus}>
          <SearchView search={this.setSearchAndSearch} typeData={typeData} regionDepartmentTree={regionDepartmentTree} />
        </SplitterLayout>
        <Modal
          className='param-model'
          header={this.getHead()}
          visible={enableEditOp}
          width={'50%'}
          destroyContent
          onCancel={() => this.cancel('add')}
          content={this.getTaskWorkFormContext()}
          onOk={(e) => this.submit(e)}
          outterClosable={!_true_}
        />
        <Modal
          className='param-model'
          header='作业活动步骤查看'
          visible={lookupOp}
          width='50%'
          destroyContent
          onCancel={() => this.cancel('lookup')}
          content={this.getTaskWorkContextDetail()}
          footer={this.getFooterButton()}
        />
        <Modal
          className='taskwork-status-model'
          header='作业活动执行流程'
          visible={statusView}
          width='50%'
          destroyContent
          onCancel={() => this.cancel('statusView')}
          content={this.getStatusView(statusView)}
          noDefaultFooter
        />
        <AmosGridTable
          rowKey="id"
          columns={taskWorkTableColumns(this)}
          callBack={this.reload}
          dataList={dataList}
          totals={totalCount}
          getTableDataAction={this.getTaskWorkListData}
          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 TaskWork;
