import React from 'react'
import i18n from 'i18next'
import uiActions from 'actions/ui'
import cooperateActions from 'actions/cooperate'
import treeStores from 'stores/tree'
import serviceStores from 'src/stores/service'
import { getEventNodeById } from 'stores/funcs/newEvent'
import { saveCaseBeforeActions } from 'stores/funcs/service'

export default class JengaDebugBtn extends React.Component {
  constructor(props) {
    super(props)

    this.saveCase = this.saveCase.bind(this)
    this.debugService = this.debugService.bind(this)
    this.onClick = this.onClick.bind(this)
  }

  saveCase(done) {
    uiActions.toggleLoadingBar({
      show: true,
      title: i18n.t('LoadingBar.debugServiceTitle'),
      content: i18n.t('LoadingBar.debugServiceContent'),
      progress: 100,
      type: 'dbLoading'
    })
    saveCaseBeforeActions({
      success: () => {
        done && done()
      },
      fail: () => {
        uiActions.toggleLoadingBar({ show: false })
      }
    })
  }

  debugService(cb) {
    let node = getEventNodeById(this.props.nodeId)
    if (node) {
      let { nid, eid, gid, uid, client } = treeStores.curCaseInfo
      let data = {
        _nid: nid,
        _eid: eid,
        _gid: gid,
        _uid: uid,
        _sid: node.id,
        _locOffset: new Date().getTimezoneOffset() * -60
      }
      // 多人开发添加client
      cooperateActions.getIsGroupWork(isGroupWork => {
        if (isGroupWork) {
          data._client = client
        }
      })
      if (
        node &&
        node.props &&
        node.props.inParams &&
        node.props.inParams.length > 0
      ) {
        node.props.inParams.forEach(param => {
          if (param.name && (param.default || param.default === 0)) {
            data[param.name] = serviceStores.dealDefaultParam(
              param.default,
              param.type,
              true
            )
          }
        })
      }
      serviceStores.debugService(
        data,
        code => {
          uiActions.toggleLoadingBar({ show: false })
          cb && cb(code)
        },
        true
      )
    }
  }

  onClick() {
    this.saveCase(() => {
      this.debugService(code => {
        uiActions.toggleServiceDebug({ show: true, code })
      })
    })
  }

  render() {
    return (
      <button className="btn-clear btn-debug" onClick={this.onClick}>
        {i18n.t('EventView.jenga_nav.debug')}
      </button>
    )
  }
}
