import React from 'react'
import i18n from 'i18next'
import { is } from 'immutable'
import newEventActions from 'actions/newEvent'
import newEventStores from 'stores/newEvent'
import {
  getActionBlockObjNode,
  getEventBlockByBid
} from 'stores/funcs/newEvent'
import {
  hasEsDbSeniorSearch,
  isApiMethod,
  paramIsHideKeep,
  isDbMallMethodShouldReload
} from 'stores/funcs/event/methodUtils'
import { shallowEqualImmutable } from 'utils/utils'
import { EVENT_BLOCK_TYPE } from 'const/const'
import propType from 'const/propType'
// import {
//   getActionDbNodeType,
//   getDbCols,
//   getNode,
//   getActionDbId
// } from './dbComs/actionDbFuncs'
import BlockActionMethodParamItem from './BlockActionMethodParamItem'
// import BlockActionMethodParamApiToggle from './BlockActionMethodParamApiToggle'
// import BlockActionMethodParamEsSeniorSearch from './BlockActionMethodParamEsSeniorSearch'

export default class BlockActionMethodParams extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      // paramsValue: this.getParamsValue(),
      // dbInfo: {}
    }

    this.onEventChange = this.onEventChange.bind(this)
    // this.updateDbInfo = this.updateDbInfo.bind(this)
    this.paramShouldShow = this.paramShouldShow.bind(this)
    // this.updateMethod = this.updateMethod.bind(this)
    this.getObject = this.getObject.bind(this)
    this.getName = this.getName.bind(this)
    // this.getParamsValue = this.getParamsValue.bind(this)
    // this.getInfo = this.getInfo.bind(this)
    this.getVisible = this.getVisible.bind(this)
    // this.replenishApiParams = this.replenishApiParams.bind(this)
    this.renderInfo = this.renderInfo.bind(this)
  }

  shouldComponentUpdate(nextProps, nextState) {
    return (
      !shallowEqualImmutable(this.props, nextProps) ||
      !shallowEqualImmutable(this.state, nextState)
    )
  }

  componentDidMount() {
    this.unsubscribe = newEventStores.listen(this.onEventChange)
    // this.updateDbInfo()
  }

  componentWillUnmount() {
    this.unsubscribe()
  }

  componentDidUpdate(preProps) {
    // if (preProps.bid !== this.props.bid) {
    //   this.setState({
    //     paramsValue: this.getParamsValue()
    //   })
    //   this.updateDbInfo()
    // } else if (
    //   !preProps.actionName &&
    //   preProps.actionName !== this.props.actionName
    // ) {
    //   // actionName由无到有
    //   process.nextTick(() => {
    //     this.updateDbInfo()
    //   })
    // } else if (
    //   // DbMall比较特殊,切换不同方法时需要重新获取DbCols
    //   preProps.actionName !== this.props.actionName &&
    //   isDbMallMethodShouldReload(this.props.actionName)
    // ) {
    //   process.nextTick(() => {
    //     this.updateDbInfo()
    //   })
    // }
  }

  onEventChange(status) {
    // let obj = {}
    // if (status) {
    //   if (
    //     status.types.includes('updateBlockProp') &&
    //     this.props.bid === status.data.affectBlockId &&
    //     ['object', 'action'].indexOf(status.data.prop) >= 0
    //   ) {
    //     let paramsValue = this.getParamsValue()
    //     if (!is(this.state.params, params)) {
    //       obj.params = params
    //     }
    //     // 切换对象时检查
    //     if (['object'].indexOf(status.data.prop) >= 0) {
    //       this.updateDbInfo()
    //     }
    //   } else if (
    //     status.types.includes('reloadParamsItemMethod') &&
    //     this.props.bid === status.data.affectBlockId
    //   ) {
    //     this.updateMethod()
    //   }
    // }
    // if (Object.keys(obj).length > 0) {
    //   this.setState(obj)
    // }
  }

  // updateDbInfo() {
  //   let { bid } = this.props
  //   let node = getNode({
  //     bid: this.props.bid,
  //     obj: this.getObject(),
  //     useObj: true,
  //     actionName: this.getName()
  //   })
  //   let dbId = getActionDbId({ node: node, bid: bid })
  //   let dbNodeType = getActionDbNodeType({
  //     node: node,
  //     bid: bid
  //   })
  //   if (dbId) {
  //     getDbCols({
  //       dbId: dbId,
  //       nodeType: dbNodeType,
  //       cb: dbCols => {
  //         this.setState({
  //           dbInfo: { dbId, dbCols, dbNodeType }
  //         })
  //       }
  //     })
  //   } else {
  //     if (Object.keys(this.state.dbInfo).length >= 0) {
  //       this.setState({
  //         dbInfo: {}
  //       })
  //     }
  //   }
  // }

  paramShouldShow(param, index) {
    let result = true
    switch (this.getVisible()) {
      case 'part':
        if (
          (!param.value && param.value !== 0 && param.value !== false) ||
          ((param.type === propType.Formula ||
            param.type === propType.FormulaColor ||
            param.type === propType.FormulaJson) &&
            param.value &&
            !param.value.code)
        ) {
          result = false
        }
        break
    }
    if (
      result &&
      paramIsHideKeep({
        param: param,
        bid: this.props.bid,
        actionName: this.getName(),
        index: index,
        nodeId: this.props.eventNodeId || newEventStores.curEventNodeId,
        isNewEvent: true
      })
    ) {
      result = false
    }
    return result
  }

  // updateMethod() {
  //   let objNode = getActionBlockObjNode({
  //     obj: this.getObject(),
  //     blockId: this.props.bid
  //   })
  //   if (objNode) {
  //     newEventActions.updateActionMethod({
  //       nodeId: objNode.id,
  //       targetBlockId: this.props.bid,
  //       methods: [this.getName()]
  //     })
  //   }
  // }

  getObject() {
    let _obj = null
    let block = getEventBlockByBid(this.props.bid)
    if (block) {
      _obj = block.object
    }
    return _obj
  }

  getName() {
    return this.props.actionName ? this.props.actionName || null : null
  }

  // getParamsValue() {
  //   let result = []
  //   let block = getEventBlockByBid(this.props.bid)
  //   if (
  //     block &&
  //     block.type === EVENT_BLOCK_TYPE.ACTION &&
  //     block.action &&
  //     block.action.params
  //   ) {
  //     result = block.action.params
  //   }
  //   return result
  // }

  getVisible() {
    return this.props.paramsVisible ? this.props.paramsVisible || 'all' : 'all'
  }

  // getInfo() {
  //   let result = undefined
  //   let block = getEventBlockByBid(this.props.bid)
  //   if (
  //     block &&
  //     block.type === EVENT_BLOCK_TYPE.ACTION &&
  //     block.action &&
  //     block.action.info
  //   ) {
  //     result = block.action.info
  //   }
  //   return result
  // }

  // replenishApiParams(apiGroups, result) {
  //   let groupHeader = (title, index) => {
  //     let className = 'params-group'
  //     if (index === 0) {
  //       className += ' first'
  //     }
  //     return (
  //       <div className={className} key={index + title}>
  //         <div className="title">{title}</div>
  //         <BlockActionMethodParamApiToggle
  //           group={title}
  //           bid={this.props.bid}
  //           actionName={this.props.actionName}
  //         />
  //       </div>
  //     )
  //   }
  //   let addGroupParams = (name, index, groupParams) => {
  //     let groupIndex = apiGroups.findIndex(group => group.name === name)
  //     if (groupIndex < 0) {
  //       groupParams.push(groupHeader(name, index))
  //     } else {
  //       let group = apiGroups[groupIndex]
  //       groupParams.push(group.header)
  //       groupParams = groupParams.concat(group.coms)
  //       apiGroups.splice(groupIndex, 1)
  //     }
  //     return groupParams
  //   }
  //   // 默认title
  //   let defaultHeaders = ['Header', 'Body']
  //   let groupParams = []
  //   defaultHeaders.forEach((header, index) => {
  //     groupParams = addGroupParams(header, index, groupParams)
  //   })
  //   // 把剩余的加上
  //   if (apiGroups.length > 0) {
  //     apiGroups.forEach(group => {
  //       groupParams.push(group.header)
  //       groupParams = groupParams.concat(group.coms)
  //     })
  //   }
  //   result = result.concat(groupParams)
  //   return result
  // }

  // replenishSeniorSearchParams(searchParams, result) {
  //   let groupParams = []
  //   let groupHeader = title => {
  //     let className = 'params-group first'
  //     return (
  //       <div className={className} key={title}>
  //         <BlockActionMethodParamEsSeniorSearch
  //           group={title}
  //           bid={this.props.bid}
  //           actionName={this.props.actionName}
  //         />
  //       </div>
  //     )
  //   }
  //   let addGroupParams = name => {
  //     groupParams.push(groupHeader(name))
  //     groupParams = groupParams.concat(searchParams[0].coms)
  //     return groupParams
  //   }
  //   if (searchParams && searchParams.length > 0) {
  //     groupParams = addGroupParams('SeniorEsSearch')
  //     if (result && result.length > 0) {
  //       if (
  //         result[0].props &&
  //         result[0].props.param &&
  //         result[0].props.param.name === 'query'
  //       ) {
  //         let pre = result.slice(0, 1)
  //         let sub = result.slice(1, result.length)
  //         result = pre.concat(groupParams).concat(sub)
  //       } else {
  //         result = groupParams.concat(result)
  //       }
  //     } else {
  //       result = groupParams
  //     }
  //   }
  //   return result
  // }

  renderInfo() {
    let params = this.props.params
    let visible = this.getVisible()
    let shouldRender = 0
    let normal = [] // 普通params
    let cloneChild = [] // 克隆对象params
    let groups = [] // 带pGroup的params {name, coms}
    let groupStyle = isApiMethod(this.props.actionName)
      ? {
          backgroundColor: '#385452',
          marginBottom: 0,
          paddingBottom: '2px'
        }
      : undefined
    let groupClass = undefined
    params.map((param, index) => {
      groupClass =
        hasEsDbSeniorSearch(this.props.actionName) && param.pGroup
          ? 'group-param-item'
          : groupClass
      if (this.paramShouldShow(param, index)) {
        shouldRender += 1
        if (param.pGroup && false) {
          let pGroup = groups.find(item => {
            return item.name === param.pGroup
          })
          if (pGroup) {
            pGroup.coms.push(
              <BlockActionMethodParamItem
                key={index}
                paramStyle={groupStyle}
                paramClass={groupClass}
                bid={this.props.bid}
                layer={this.props.layer}
                groupLayer={this.props.groupLayer}
                nestGroupLayer={this.props.nestGroupLayer}
                extraGapGroupLayer={this.props.extraGapGroupLayer}
                actionName={this.props.actionName}
                index={index}
                param={param}
                dbInfo={this.state.dbInfo}
                visible={visible}
              />
            )
          } else {
            let className = 'params-group'
            if (groups.length === 0) {
              className += ' first'
            }
            let groupName = i18n.exists('EventView.DbHeader.' + param.pGroup)
              ? i18n.t('EventView.DbHeader.' + param.pGroup)
              : param.pGroup
            let group = {
              name: param.pGroup,
              header: (
                <div className={className} key={index + param.pGroup}>
                  <div className="title">{groupName}</div>
                  {isApiMethod(this.props.actionName) ? (
                    <BlockActionMethodParamApiToggle
                      group={param.pGroup}
                      bid={this.props.bid}
                      actionName={this.props.actionName}
                    />
                  ) : null}
                </div>
              ),
              coms: [
                <BlockActionMethodParamItem
                  key={index}
                  paramStyle={groupStyle}
                  paramClass={groupClass}
                  bid={this.props.bid}
                  layer={this.props.layer}
                  groupLayer={this.props.groupLayer}
                  nestGroupLayer={this.props.nestGroupLayer}
                  extraGapGroupLayer={this.props.extraGapGroupLayer}
                  actionName={this.props.actionName}
                  index={index}
                  param={param}
                  dbInfo={this.state.dbInfo}
                  visible={visible}
                />
              ]
            }
            groups.push(group)
          }
        } else if (param.type === propType.CloneChild && false) {
          cloneChild.push(
            <BlockActionMethodParamItem
              key={index}
              bid={this.props.bid}
              layer={this.props.layer}
              groupLayer={this.props.groupLayer}
              nestGroupLayer={this.props.nestGroupLayer}
              extraGapGroupLayer={this.props.extraGapGroupLayer}
              actionName={this.props.actionName}
              index={index}
              param={param}
              dbInfo={this.state.dbInfo}
              visible={visible}
            />
          )
        } else {
          normal.push(
            <BlockActionMethodParamItem
              key={index}
              bid={this.props.bid}
              layer={this.props.layer}
              groupLayer={this.props.groupLayer}
              nestGroupLayer={this.props.nestGroupLayer}
              extraGapGroupLayer={this.props.extraGapGroupLayer}
              actionName={this.props.actionName}
              index={index}
              param={param}
              dbInfo={this.state.dbInfo}
              visible={visible}
              eventNodeId={this.props.eventNodeId}
            />
          )
        }
      }
    })
    let result = normal
    // if (isApiMethod(this.props.actionName)) {
    //   result = this.replenishApiParams(groups, result)
    // } else if (hasEsDbSeniorSearch(this.props.actionName)) {
    //   result = this.replenishSeniorSearchParams(groups, result)
    // } else {
    //   if (groups.length !== 0) {
    //     let groupParams = []
    //     groups.forEach(group => {
    //       groupParams.push(group.header)
    //       groupParams = groupParams.concat(group.coms)
    //     })
    //     result = result.concat(groupParams)
    //   }
    // }
    return {
      renderParams: result,
      shouldRender: shouldRender,
      cloneChildParams: cloneChild
    }
  }

  render() {
    let { shouldRender, renderParams, cloneChildParams } = this.renderInfo()
    return shouldRender > 0 ? (
      <div className="params-wrap">
        <div className="params">{renderParams}</div>
        {/* {cloneChildParams && cloneChildParams.length > 0
          ? cloneChildParams
          : null} */}
      </div>
    ) : null
  }
}
