import React from 'react'
import {Modal} from 'react-bootstrap'
import FlowDiagram from 'components/FlowDiagram'
import ReportForm from 'components/ReportForm'
import formatter from 'utils/formatter.js'
import './style.scss'

/** 显示待办、经办、办结、关注事项的表格*/

class TaskTable extends React.Component {
  static propTypes = {
    // tasks: React.PropTypes.arrayOf(React.PropTypes.shape({
    //   subject: React.PropTypes.string.isRequired,
    //   businessKey: React.PropTypes.string.isRequired,
    //   processDefinitionId: React.PropTypes.string.isRequired,
    //   processDefinitionName: React.PropTypes.string,
    //   taskName: React.PropTypes.string,
    //   url: React.PropTypes.string.isRequired,
    //   processInstanceId:React.PropTypes.string.isRequired,
    //   createTime: React.PropTypes.number,
    //   currentActivityName:React.PropTypes.string,
    //   currentAssigneeName:React.PropTypes.string,
    //   startUserName:React.PropTypes.string.isRequired
    // })),

    onTaskChange: React.PropTypes.func,

    taskType: React.PropTypes.string
  }

  constructor (props, context) {
    super(props, context)

    this.state = {
      showFlowDiagram: false,
      showReportForm: false,
      reporting: false
    }
  }

  hideFlowDiagram = () => {
    this.setState({showFlowDiagram: false})
  }

  hideReportForm = () => {
    this.setState({showReportForm: false, reporting: false})
  }

  showMask = () => {
    this.setState({reporting: true})
  }

  generateActions = (businessKey, task) => {
    let taskType = this.props.taskType
    var dom = '<a class="flow-diagram-btn" data-processinstanceid=' + task.processInstanceId +
        ' data-processdefinitionid=' + task.processDefinitionId + '>流程图</a>'
    if (taskType === 'historyTask') {
      dom += '<a class="print-report-btn" data-businessid=' + task.businessKey + '  data-reportype=' +
        task.param.reportType + ' data-processdefinitionid=' + task.processDefinitionId + '>打印</a>'
    }
    return dom
  }

  generateSubject (subject, task) {
    var url = task.url
    let path = url.split('?')[0]

    // 对url进行二次处理，强行转成react的url
    if (path === '/payment2/examinePayment') {
      url = url.replace('/payment2/examinePayment', '/contract/payment/examine')
    } else if (path === '/payment2/paymentDetails') {
      url = url.replace('/payment2/paymentDetails', '/contract/payment/details')
    } else if (path === '/payment2/fillPayment') {
      url = url.replace('/payment2/fillPayment', '/contract/payment/edit')
    } else if (path === '/payment2/printPayment') {
      url = url.replace('/payment2/printPayment', '/contract/payment/print')
    } else if (path === '/payment2/examineGuarantee') {
      url = url.replace('/payment2/examineGuarantee', '/contract/guarantee/examine')
    } else if (path === '/payment2/guaranteeDetails') {
      url = url.replace('/payment2/guaranteeDetails', '/contract/guarantee/details')
    } else if (path === '/payment2/applyGuarantee') {
      url = url.replace('/payment2/applyGuarantee', '/contract/guarantee/apply')
    } else if (path === '/payment2/printGuarantee') {
      url = url.replace('/payment2/printGuarantee', '/contract/guarantee/print')
    }

    return '<a target="_blank" href=' + url + '>' + subject + '</a>'
  }

  getOptions (taskType) {
    const TASK_TABLE_OPTION = {
      classes: 'table table-striped table-hover table-no-bordered',
      pagination: 'true',
      sidePagination: 'server',
      // sidePagination: 'client',
      search: 'true',
      onLoadSuccess: this.props.onTaskChange
    }

    if (taskType === 'todoTask') {
      return Object.assign({
        url: '/qdp/payment/bpm/task/query/todoTask?' + new Date().getTime(),
        sortName: 'createTime',
        sortOrder: 'desc',
        columns: [{
          title: '主题',
          halign: 'center',
          field: 'subject',
          formatter: this.generateSubject,
          searchable: true
        }, {
          title: '发起人',
          halign: 'center',
          field: 'startUserName',
          searchable: false
        }, {
          title: '当前环节',
          halign: 'center',
          field: 'taskName',
          searchable: false
        }, {
          title: '开始时间',
          halign: 'center',
          field: 'createTime',
          formatter: formatter.formatTime,
          sortable: true,
          searchable: false
        }, {
          title: '操作',
          halign: 'center',
          formatter: this.generateActions,
          field: 'businessKey',
          searchable: false
        }]
      }, TASK_TABLE_OPTION)
    } else if (taskType === 'passTask') {
      return Object.assign({
        url: '/qdp/payment/bpm/task/query/passTask?' + new Date().getTime(),
        sortName: 'createTime',
        sortOrder: 'desc',
        columns: [{
          title: '主题',
          halign: 'center',
          field: 'subject',
          formatter: this.generateSubject
        }, {
          title: '发起人',
          halign: 'center',
          field: 'startUserName',
          searchable: false
        }, {
          title: '当前环节',
          halign: 'center',
          field: 'currentActivityName',
          searchable: false
        }, {
          title: '当前处理人',
          halign: 'center',
          field: 'currentAssigneeName',
          searchable: false
        }, {
          title: '开始时间',
          halign: 'center',
          field: 'createTime',
          formatter: formatter.formatTime,
          sortable: true,
          searchable: false
        }, {
          title: '操作',
          halign: 'center',
          formatter: this.generateActions,
          field: 'businessKey',
          searchable: false
        }]
      }, TASK_TABLE_OPTION)
    } else if (taskType === 'historyTask') {
      return Object.assign({
        url: '/qdp/payment/bpm/task/query/historyTask?' + new Date().getTime(),
        sortName: 'endTime',
        sortOrder: 'desc',
        columns: [{
          title: '主题',
          halign: 'center',
          field: 'subject',
          formatter: this.generateSubject
        }, {
          title: '发起人',
          halign: 'center',
          field: 'startUserName',
          searchable: false
        }, {
          title: '开始时间',
          halign: 'center',
          field: 'startTime',
          formatter: formatter.formatTime,
          sortable: true,
          searchable: false
        }, {
          title: '结束时间',
          halign: 'center',
          field: 'endTime',
          formatter: formatter.formatTime,
          sortable: true,
          searchable: false
        }, {
          title: '操作',
          halign: 'center',
          formatter: this.generateActions,
          field: 'businessKey',
          searchable: false
        }]
      }, TASK_TABLE_OPTION)
    } else if (taskType === 'participantTask') {
      return Object.assign({
        url: '/qdp/payment/bpm/task/query/participantTask?' + new Date().getTime(),
        sortName: 'startTime',
        sortOrder: 'desc',
        columns: [{
          title: '主题',
          halign: 'center',
          field: 'subject',
          formatter: this.generateSubject
        }, {
          title: '发起人',
          halign: 'center',
          field: 'startUserName',
          searchable: false
        }, {
          title: '当前环节',
          halign: 'center',
          field: 'currentActivityName',
          searchable: false
        }, {
          title: '当前处理人',
          halign: 'center',
          field: 'currentAssigneeName',
          searchable: false
        }, {
          title: '开始时间',
          halign: 'center',
          field: 'startTime',
          formatter: formatter.formatTime,
          sortable: true,
          searchable: false
        }, {
          title: '操作',
          halign: 'center',
          formatter: this.generateActions,
          field: 'businessKey',
          searchable: false
        }]
      }, TASK_TABLE_OPTION)
    } else {
      return {}
    }
  }

  componentWillMount () {
    $.extend($.fn.bootstrapTable.defaults, {
      formatSearch () {
        return '主题'
      }
    })
  }

  componentWillReceiveProps (nextProps) {
    if (nextProps.taskType !== this.props.taskType) {
      $(this.refs.table).bootstrapTable('destroy')
      $(this.refs.table).bootstrapTable(this.getOptions(nextProps.taskType))
    }
  }

  componentDidMount () {
    setTimeout(function () {
      $(this.refs.table).bootstrapTable(this.getOptions(this.props.taskType))
    }.bind(this), 300)

    $(document).on('click', '.flow-diagram-btn', function (e) {
      this.setState({
        processInstanceId: $(e.target).data('processinstanceid') + '',
        processDefinitionId: $(e.target).data('processdefinitionid'),
        showFlowDiagram: true
      })
    }.bind(this))

    $(document).on('click', '.print-report-btn', function (e) {
      console.log('print-report!')
      this.setState({
        showReportForm: true,
        reportType: $(e.target).data('reportype'),
        processDefinitionId: $(e.target).data('processdefinitionid'),
        businessId: $(e.target).data('businessid')
      })
    }.bind(this))
  }

  render () {
    // console.log('taskTable:render')
    return (
      <div style={{position: 'relative'}}>
        <table ref='table' />
        <Modal bsSize='large' show={this.state.showFlowDiagram} onHide={this.hideFlowDiagram}>
          <Modal.Header closeButton>
            <Modal.Title>流程图</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <FlowDiagram processInstanceId={this.state.processInstanceId}
              processDefinitionId={this.state.processDefinitionId} />
          </Modal.Body>
        </Modal>
        <Modal bsSize='large' show={this.state.showReportForm} onHide={this.hideReportForm}>
          <Modal.Header closeButton>
            <Modal.Title>选择打印参数</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <ReportForm onReport={this.showMask}
              reportType={this.state.reportType} processDefinitionId={this.state.processDefinitionId}
              businessId={this.state.businessId} onClickCancel={this.hideReportForm} />
          </Modal.Body>
        </Modal>
        <div className={this.state.reporting ? 'payment-page-mask' : 'hidden'} />
      </div>
    )
  }
}

TaskTable.defaultProps = {
  tasks: [],
  taskType: 'todoTask'
}

export default TaskTable
