import React from 'react'
import { Switch, Tooltip } from 'antd'
import i18n from 'i18next'
import cls from 'classnames'
import treeActions from 'actions/tree'
import uiActions from 'actions/ui'
import widgetStore from 'stores/widget'
import treeStores from 'stores/tree'
import { getEventNodeById } from 'stores/funcs/newEvent'
import { getDate } from 'utils/commons/getDate'
import { isHySa } from 'utils/commons/ctrlHide'
export default class TimerServiceParams extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      params: this.getParams(),
      defaultParams: [
        {
          name: 'param1',
          value: 'now'
        },
        {
          name: 'param2',
          value: 'finishTimes'
        },
        {
          name: 'param3',
          value: 'workerIndex'
        },
        {
          name: 'param4',
          value: 'workerCount'
        }
      ],
      title: this.getTitleName()
    }

    this.onChangeParam = this.onChangeParam.bind(this)
    this.onBlurParam = this.onBlurParam.bind(this)
    this.dealPeriodValue = this.dealPeriodValue.bind(this)
    this.onToggleRecordsPanel = this.onToggleRecordsPanel.bind(this)

    this.getParams = this.getParams.bind(this)
    this.getTitleName = this.getTitleName.bind(this)

    this.genInput = this.genInput.bind(this)
    this.genDefaultParams = this.genDefaultParams.bind(this)
  }

  componentDidUpdate(preProps) {
    if (preProps.nodeId !== this.props.nodeId) {
      this.setState({
        params: this.getParams(),
        title: this.getTitleName()
      })
    }
  }

  onChangeNoAuto(propName, index) {
    let obj = {}
    let newParams = JSON.parse(JSON.stringify(this.state.params))
    let param = newParams[index]
    param.value = !param.value
    obj[propName] = param.value
    this.setState(
      {
        params: newParams
      },
      () => {
        treeActions.changeNodeProps({
          nodeId: this.props.nodeId,
          props: obj
        })
      }
    )
  }

  onChangeParam(propName, index, e) {
    let value = e && e.target ? e.target.value : e
    let param = this.state.params[index]
    param.value = value
    this.setState({
      params: this.state.params
    })
  }

  onBlurParam(propName, index, e) {
    let obj = {}
    let value = e && e.target ? e.target.value : e
    let param = this.state.params[index]
    if (propName === 'startTime') {
      let regExp = /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s+(20|21|22|23|[0-1]\d):[0-5]\d:[0-5]\d$/
      if (!regExp.test(value)) {
        value = getDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
      }
    } else {
      // 对企业id为10000586作特殊处理
      value = parseFloat(value)
      if (isNaN(value) || value < 0) {
        // 用回对象原来的值
        let node = getEventNodeById(this.props.nodeId)
        value = node.props[propName] || 0
        if (propName === 'period') {
          // 最小时间间隔：60s
          value =
            value < 60
              ? treeStores.curCaseInfo.eid === 10000586
                ? value
                : 60
              : value
        } else if (propName === 'repeatTimes') {
          value = value > 9999999 ? 9999999 : value
        } else if (propName === 'workers') {
          // 并发线程大于等于1,小于100,默认1
          value = value === 0 ? 1 : value
        }
      } else {
        if (propName === 'period') {
          // 最小时间间隔：60s
          // value =
          //   value < 1
          //     ? treeStores.curCaseInfo.eid === 10000586
          //       ? value * 60
          //       : 60
          //     : value * 60
          value =
            value < 60
              ? treeStores.curCaseInfo.eid === 10000586
                ? value
                : 60
              : value
        } else if (propName === 'repeatTimes') {
          value = value > 9999999 ? 9999999 : value
        } else if (propName === 'workers') {
          value = parseInt(value)
          // 并发线程大于等于1,小于100,默认1
          value = value === 0 ? 1 : value > 100 ? 100 : value
        }
      }
    }
    if (propName === 'period') {
      param.value = this.dealPeriodValue(value)
      obj[propName] = this.dealPeriodValue(value)
    } else {
      param.value = value
      obj[propName] = value
    }
    this.setState(
      {
        params: this.state.params
      },
      () => {
        treeActions.changeNodeProps({
          nodeId: this.props.nodeId,
          props: obj
        })
      }
    )
  }

  dealPeriodValue(value) {
    // let newValue = parseFloat(value / 60)
    // if (!isNaN(newValue)) {
    //   // newValue小于1则自动变为最多2位小数
    //   if (newValue < 1) {
    //     newValue = parseFloat((value / 60).toFixed(2))
    //   }
    // }
    // return isNaN(newValue) ? 1 : newValue
    let newValue = parseInt(value)
    return newValue
  }

  onToggleRecordsPanel() {
    uiActions.toggleServicePanel({ show: true, nodeId: this.props.nodeId })
  }

  getParams() {
    let params = []
    let node = getEventNodeById(this.props.nodeId)
    if (node && widgetStore.widget[node.type]) {
      widgetStore.widget[node.type].map.props.forEach(prop => {
        let value =
          node.props[prop.name] === undefined
            ? prop.name === 'noAuto'
              ? false
              : ''
            : node.props[prop.name]
        if (prop.name === 'period') {
          value = this.dealPeriodValue(value)
        }
        params.push({
          name: prop.name,
          value: value,
          locale: prop.locale,
          desc: prop.desc,
          showDes: prop.showDes,
          placeholder: prop.placeholder
        })
      })
    }
    return params
  }

  getTitleName() {
    let title = ''
    let node = getEventNodeById(this.props.nodeId)
    if (node && widgetStore.widget[node.type]) {
      let map = widgetStore.widget[node.type].map
      title = map.locale ? map.locale[i18n.language] : map.name
    }
    return title ? title + i18n.t('EventView.jenga_extra.defination') : title
  }

  genInput(param, index) {
    let { desc, showDes } = param
    let tipContent = desc && desc[i18n.language]
    return (
      <div
        className={cls('param-item f--hlc', {
          'param-item-left': index % 3 !== 0,
          'param-item-bottom': index < 3
        })}
        key={index}
      >
        <div className="item-name">
          {param.locale ? param.locale[i18n.language] : param.name}
        </div>
        {!isHySa() && showDes && showDes === 1 && (
          <Tooltip
            title={tipContent}
            placement="right"
            destroyTooltipOnHide={true}
          >
            <div className="service-param-help">
              <div className="ih5-icon-help" />
            </div>
          </Tooltip>
        )}
        {index === 3 ? (
          <div className="item-input-wrap default-input-wrap f--hlc flex-1">
            <Switch
              checked={param.value}
              onChange={this.onChangeNoAuto.bind(this, param.name, index)}
              className="no-auto-switch"
            />
          </div>
        ) : (
          <div className="item-input-wrap default-input-wrap f--hlc flex-1">
            <input
              value={param.value}
              onChange={this.onChangeParam.bind(this, param.name, index)}
              onBlur={this.onBlurParam.bind(this, param.name, index)}
            />
            {index === 0 || index === 4 ? null : (
              <div className="input-postfix">
                {i18n.t(
                  'EventView.jenga_extra.postfix_' +
                    (index === 2 ? 'times' : 'mins')
                )}
              </div>
            )}
          </div>
        )}
      </div>
    )
  }

  genDefaultParams(param, index) {
    return (
      <div
        className={cls('param-item f--hlc', {
          'param-item-left': index % 3 !== 0
        })}
        key={index}
      >
        <div className="item-name">
          {i18n.t('EventView.jenga_extra.param') + (index + 1)}
        </div>
        <div className="item-input-wrap default-input-wrap f--hlc flex-1">
          <input
            className="default"
            readOnly={true}
            defaultValue={i18n.t('EventView.jenga_extra.' + param.value)}
          />
        </div>
      </div>
    )
  }

  render() {
    return (
      <div className="jenga-timer-service-params">
        <div className={cls('params f--h')}>
          <div className={cls('params-title f--hlc')}>
            {i18n.t('EventView.jenga_extra.serviceParams')}
          </div>
          <div className="main-wrap f--hlc">
            {this.state.params.map((param, index) => {
              return this.genInput(param, index)
            })}
          </div>
        </div>
        <div className={cls('params f--h')}>
          <div className={cls('params-title f--hlc')}>
            {i18n.t('EventView.jenga_extra.defaultParams')}
          </div>
          <div className="main-wrap f--hlc">
            {this.state.defaultParams.map((param, index) => {
              return this.genDefaultParams(param, index)
            })}
            <div className="record-break f--hcc">
              <div className="break" />
            </div>
            <button
              className="btn-clear btn-records"
              onClick={this.onToggleRecordsPanel}
            >
              {i18n.t('EventView.jenga_extra.recordsPanel')}
            </button>
          </div>
        </div>
        <div className="params-title params-def-title">
          {this.getTitleName()}
        </div>
      </div>
    )
  }
}
