import React from 'react'
import { Switch, Select } from 'antd'
import cls from 'classnames'
import i18n from 'i18next'
import treeActions from 'actions/tree'
import cooperateActions from 'actions/cooperate'
import treeStores from 'stores/tree'
import globalConfigStore from 'stores/globalConfig'
import { getEventNodeById } from 'stores/funcs/newEvent'
import { isSa, isHySa } from 'utils/commons/ctrlHide'
import externalPath from 'api/externalPath'
import iconStrObj from 'src/assets/icons/iconsStr'

export default class NodePublicService extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      publicService: this.getPublicService(),
      servicePath: this.getServicePath(),
      responseType: this.getResponseType(),
      receiveType: this.getReceiveType(),
      workSettings: globalConfigStore.workSettings,
      isCusDomain: this.dealCusDomain(globalConfigStore.workSettings)
    }
    this.responseTypeOptions = ['json', 'xml']
    // this.receiveTypeOptions = ['json', 'string', 'array', 'base64']
    this.receiveTypeOptions = ['json', 'string', 'array']
    this.onConfigChange = this.onConfigChange.bind(this)

    this.getServicePath = this.getServicePath.bind(this)
    this.getPublicService = this.getPublicService.bind(this)
    this.getResponseType = this.getResponseType.bind(this)
    this.getReceiveType = this.getReceiveType.bind(this)
    this.onChangeProps = this.onChangeProps.bind(this)
    this.onChangingPath = this.onChangingPath.bind(this)
    this.onChangedPath = this.onChangedPath.bind(this)
    this.onCopy = this.onCopy.bind(this)
    this.onCopyPublishPath = this.onCopyPublishPath.bind(this)
    this.onCopyPreviewPath = this.onCopyPreviewPath.bind(this)
    this.onChangeResponseType = this.onChangeResponseType.bind(this)
    this.onChangeReceiveType = this.onChangeReceiveType.bind(this)
    this.pathPrefix = this.pathPrefix.bind(this)
    this.publishPath = this.publishPath.bind(this)
    this.previewPath = this.previewPath.bind(this)
    this.targetPath = this.targetPath.bind(this)
    this.sidPath = this.sidPath.bind(this)
    this.isGroupWork = this.isGroupWork.bind(this)
  }

  componentDidMount() {
    this.unsubscribe = globalConfigStore.listen(this.onConfigChange)
  }

  componentWillUnmount() {
    this.unsubscribe()
  }

  componentDidUpdate(preProps) {
    if (this.props.nodeId !== preProps.nodeId) {
      this.setState({
        servicePath: this.getServicePath(),
        publicService: this.getPublicService(),
        responseType: this.getResponseType(),
        receiveType: this.getReceiveType(),
        isCusDomain: this.dealCusDomain(this.state.workSettings)
      })
    }
  }

  dealCusDomain(workSettings) {
    return [false, undefined].indexOf(treeStores.curCaseInfo.isPublished) >= 0
      ? false // 首次发布配置默认使用平台公共域名
      : workSettings
      ? workSettings.customDomain
      : false
  }

  onConfigChange(status) {
    let obj = {}
    if (status.types) {
      if (status.types.includes('workSettings')) {
        obj.workSettings = status.data.workSettings
        obj.isCusDomain = this.dealCusDomain(obj.workSettings)
      }
    }
    if (Object.keys(obj).length > 0) {
      this.setState(obj)
    }
  }

  getServicePath() {
    let node = getEventNodeById(this.props.nodeId)
    return node && node.props ? node.props.servicePath || '' : ''
  }

  getPublicService() {
    let node = getEventNodeById(this.props.nodeId)
    return node && node.props && node.props.publicService !== undefined
      ? node.props.publicService
      : false
  }

  getResponseType() {
    let node = getEventNodeById(this.props.nodeId)
    return node && node.props && node.props.responseType !== undefined
      ? node.props.responseType
      : 'json'
  }

  getReceiveType() {
    let node = getEventNodeById(this.props.nodeId)
    return node && node.props && node.props.receiveType !== undefined
      ? node.props.receiveType
      : 'json'
  }

  onChangeProps(type, value) {
    let props = {}
    switch (type) {
      case 'publicService':
        props.publicService = value
        if (props.publicService && !this.state.servicePath) {
          props.servicePath = this.sidPath()
        }
        break
      case 'servicePath':
        props.servicePath = value
        if (!value && this.state.publicService) {
          props.servicePath = this.sidPath()
        }
        break
      case 'responseType':
        props.responseType = value
        break
      case 'receiveType':
        props.receiveType = value
        break
    }
    if (Object.keys(props).length > 0) {
      this.setState(props)
      treeActions.changeNodeProps({
        nodeId: this.props.nodeId,
        props: props
      })
    }
  }

  onChangingPath(e) {
    let value = e && e.target ? e.target.value : e
    this.setState({
      servicePath: value
    })
  }

  onChangedPath() {
    this.onChangeProps('servicePath', this.state.servicePath)
  }

  onCopy(value) {
    let tInput = document.createElement('textarea')
    tInput.style.width = '0px'
    tInput.style.height = '0px'
    tInput.value = value
    document.body.appendChild(tInput)
    tInput.select()
    document.execCommand('copy')
    document.body.removeChild(tInput)
  }

  onCopyPublishPath() {
    this.onCopy(this.publishPath())
  }

  onCopyPreviewPath() {
    this.onCopy(this.previewPath())
  }

  onChangeResponseType(e) {
    this.setState(
      {
        responseType: e
      },
      () => {
        this.onChangeProps('responseType', this.state.responseType)
      }
    )
  }

  onChangeReceiveType(e) {
    this.setState(
      {
        receiveType: e
      },
      () => {
        this.onChangeProps('receiveType', this.state.receiveType)
      }
    )
  }

  pathPrefix(isPreview) {
    let prefix =
      (isPreview ? 'https://v4pre.h5sys.' : 'https://v4rel.h5sys.') +
      (i18n.language === 'zh' ? 'cn' : 'com')
    let { isCusDomain, workSettings } = this.state
    if (isCusDomain) {
      if (isPreview && workSettings && workSettings.previewDomain) {
        prefix = workSettings.previewDomain
      } else if (!isPreview && workSettings && workSettings.domain) {
        prefix = workSettings.domain
      }
    }
    if (isSa() && isPreview) {
      let protocol = location.protocol + '//'
      if (workSettings && workSettings.previewDomain) {
        prefix = protocol + workSettings.previewDomain
      } else {
        prefix = protocol + document.domain
      }
    }
    return prefix + '/api/' + treeStores.curCaseId + '/'
  }

  publishPath() {
    return this.pathPrefix() + this.targetPath()
  }

  previewPath() {
    return this.pathPrefix(true) + this.targetPath()
  }

  targetPath() {
    // let node = getEventNodeById(this.props.nodeId)
    return this.state.servicePath // || (node && node.id) || ''
  }

  sidPath() {
    let node = getEventNodeById(this.props.nodeId)
    return (node && node.id) || ''
  }

  isGroupWork() {
    let showGroupTips = false
    cooperateActions.getIsGroupWork(isGroupWork => {
      if (isGroupWork) {
        showGroupTips = true
      }
    })
    return showGroupTips
  }

  render() {
    // 小模块不需要
    if (treeStores.curClassId) {
      return null
    }
    // 多人开发添加client

    return (
      <div className={cls('jenga-node-public-service')}>
        <div className="row-wrap f--hlc">
          <div className="title">
            {i18n.t('EventView.jenga_extra.public_service')}
          </div>
          <Switch
            checked={this.state.publicService}
            onChange={this.onChangeProps.bind(this, 'publicService')}
            className="public-service-switch"
          />
          {!isHySa() && (
            <a
              className="help-link"
              href={externalPath.publicService}
              target="_blank"
            >
              <i
                className="ih5-icon-help"
                dangerouslySetInnerHTML={{ __html: iconStrObj.help }}
              />
            </a>
          )}
          {this.state.publicService ? (
            <>
              <div className="path-info">
                <div className="f--hlc">
                  {i18n.t('EventView.jenga_extra.service_path')}
                  <input
                    className="path-input"
                    onChange={this.onChangingPath}
                    onBlur={this.onChangedPath}
                    value={this.state.servicePath}
                    placeholder={i18n.t(
                      'EventView.jenga_extra.input_path_placeholder'
                    )}
                  />
                </div>
              </div>
              <div className="response-type">
                {i18n.t('EventView.jenga_extra.receive_type')}
                <Select
                  onChange={this.onChangeReceiveType}
                  getPopupContainer={triggerNode => triggerNode.parentNode}
                  value={this.state.receiveType}
                  size="small"
                  className="response-type-select"
                  dropdownClassName="response-type-select-dropdown"
                >
                  {this.receiveTypeOptions.map((op, optIndex) => (
                    <Select.Option value={op} key={optIndex}>
                      {i18n.t(
                        'EventView.jenga_extra.receive_type_option.' + op
                      )}
                    </Select.Option>
                  ))}
                </Select>
              </div>
              <div className="response-type">
                {i18n.t('EventView.jenga_extra.response_type')}
                <Select
                  onChange={this.onChangeResponseType}
                  getPopupContainer={triggerNode => triggerNode.parentNode}
                  value={this.state.responseType}
                  size="small"
                  className="response-type-select"
                  dropdownClassName="response-type-select-dropdown"
                >
                  {this.responseTypeOptions.map((op, optIndex) => (
                    <Select.Option value={op} key={optIndex}>
                      {i18n.t(
                        'EventView.jenga_extra.response_type_option.' + op
                      )}
                    </Select.Option>
                  ))}
                </Select>
              </div>
            </>
          ) : null}
        </div>
        {this.state.publicService ? (
          <>
            <div className="row-wrap path-wrap f--hlc">
              <div className="path-info">
                <div className="f--hlc preview-info">
                  {i18n.t('EventView.jenga_extra.preview_path')}
                  {this.pathPrefix(true)}
                  <div className="path-value" title={this.targetPath()}>
                    {this.targetPath()}
                  </div>
                  <button
                    className="btn-clear btn-copy-path"
                    onClick={this.onCopyPreviewPath}
                  >
                    {i18n.t('EventView.jenga_extra.copy_path')}
                  </button>
                </div>
                {this.isGroupWork() && (
                  <div className="notice-wrap f--hlc">
                    <div
                      className="icon"
                      dangerouslySetInnerHTML={{
                        __html: iconStrObj.noticeIcon
                      }}
                    />
                    <div className="notice-info">
                      {i18n.t(
                        'EventView.jenga_extra.preview_group_work_notice'
                      )}
                    </div>
                  </div>
                )}
              </div>
            </div>
            {!isSa() && (
              <div className="row-wrap path-wrap f--hlc">
                <div className="path-info">
                  <div className="f--hlc publish_path">
                    {i18n.t('EventView.jenga_extra.publish_path')}
                    {this.pathPrefix()}
                    <div className="path-value" title={this.targetPath()}>
                      {this.targetPath()}
                    </div>
                    <button
                      className="btn-clear btn-copy-path"
                      onClick={this.onCopyPublishPath}
                    >
                      {i18n.t('EventView.jenga_extra.copy_path')}
                    </button>
                  </div>
                  <div className="notice-wrap f--hlc">
                    <div
                      className="icon"
                      dangerouslySetInnerHTML={{
                        __html: iconStrObj.noticeIcon
                      }}
                    />
                    <div className="notice-info">
                      {i18n.t('EventView.jenga_extra.publish_notice')}
                    </div>
                  </div>
                </div>
              </div>
            )}
          </>
        ) : null}
      </div>
    )
  }
}
