import * as React from 'react'

import { openAppLofter } from 'nw-app-lofter'

import debounce from 'lodash.debounce'

import {
  Props,
  State
} from './type'

import { TemplateActivityContext } from '../common/template-context'
import { signupRequest ,signupNotify} from './signup-request';
import QuestionnaireModal from './questionnaire-modal'
import { goToLogin } from '../utils/login'
import { showMessage } from '../common/toast/toast'
import log from '../utils/lofter-log'
import { BaseComponent } from '../base-component'


import * as Styled from './index.style'

export class TemplateActivitySignup extends React.Component<Props, State> {
  static defaultProps = new Props()

  state = new State()

  static contextType = TemplateActivityContext
  context: React.ContextType<typeof TemplateActivityContext>

  signup = debounce(async () => {
    if (this.props.isEdit) return

    const { signup } = this.state
    /** 校验端内/端外 */
    const ua = window.navigator.userAgent.toLowerCase()
    if (ua.indexOf('lofter') === -1) {
      openAppLofter({
        path: 'webview',
        query: {
          url: window.location.href
        },
        incantation: this.props.incantation || undefined
      })
      return 
    }
    /** 校验登录 */
    if (!this.context?.activityInfo?.hasLogin) {
      goToLogin(this.context?.getActivityInfo)
    }
    if ((signup ?? this.context?.activityInfo?.actUserInfo?.signup) !== false) {
      return 
    }
    log.capture('act-3', {
      category: 'actmould',
      action: 101,
      scene: 'actmould',
      actid: this.context?.activityInfo?.actEventInfo?.activityId,
      v: 'H5'
    })
    if (this.context?.activityInfo?.actUserInfo?.canSign === false) {
      showMessage({
        text: this.context?.activityInfo?.actUserInfo?.msg || '报名失败!'
      })
      return 
    }
    if (this.context?.activityInfo?.actEventInfo.signupConfig?.signupType === 'button') {
      let fetchRes = await signupRequest({
        activityId: this.context?.activityInfo?.actEventInfo.activityId
      })
      // 报名成功,重新获取活动信息
      if (fetchRes) {
        // this.context?.getActivityInfo()
        this.handleSignupStatusChange()
        // party2022 这个活动id加个特殊处理,在报名成功后提示toast,并且调用多一个接口（给用户发头像框并私信通知）
        if (this.context?.activityInfo?.actEventInfo.activityId === 'party2022')
        {
          await signupNotify();
        }
      }
    } else {
      this.handleShowModal()
    }
  }, 400)

  handleSignupStatusChange = () => {
    this.setState({
      signup: true
    })
  }

  handleShowModal = () => {
    this.setState({
      showModal: true
    })
  }

  hideModal() {
    this.setState({
      showModal: false
    })
  }

  componentDidMount() {
    if (this.props.isEdit) {
      this.watch()
    }
  }

  watch = () => {
    let el = document.getElementById('viewport-left')
    let vwEl = document.getElementById('viewport')
    let left = vwEl.getBoundingClientRect().left
    this.setState({
      viewportLeft: left
    })
    const config = { attributes: true, childList: true}
    const callback = (mutationList: any) => {
      mutationList.forEach((mutation: any) => {
        switch(mutation.type) {
          case 'childList':
            this.setState({
              viewportLeft: vwEl.getBoundingClientRect().left
            })
            break;
        }
      })
    }
    let observer = new MutationObserver(callback)
    observer.observe(el, config)
  }

  renderSignupBtn = ({
    btnBackgroundColor,
    btnBackgroundImage,
    signedBtnBackgroundImage,
    btnWidth,
    color,
    isSignup
  }: Props & {
    isSignup: boolean;
  }) => {
    if (btnBackgroundImage && !isSignup) {
      return (
        <Styled.SignupImgBtn
          btnWidth={btnWidth}
          src={btnBackgroundImage.url}
          onClick={this.signup.bind(this)}
        />
      )
    }
    if (signedBtnBackgroundImage && isSignup) {
      return (
        <Styled.SignupImgBtn
          btnWidth={btnWidth}
          src={signedBtnBackgroundImage.url}
          onClick={this.signup.bind(this)}
        />
      )
    }
    return (
      <Styled.SignupBtn
        backgroundColor={btnBackgroundColor}
        btnWidth={btnWidth}
        color={color}
        isSignup={isSignup}
        onClick={this.signup.bind(this)}
      >
        {
          isSignup
            ? '已报名'
            : this.props.btnText
        }
      </Styled.SignupBtn>
    )
  }

  render() {
    const {
      style,
      isEdit,
      paddingTop,
      paddingBottom,
      fixed,
      previewSigned
    } = this.props
    const {
      showModal,
      signup,
      viewportLeft
    } = this.state
    let isSignup = signup ?? this.context?.activityInfo?.actUserInfo?.signup
    // 用于编辑器模式下模拟已报名样式
    if (isEdit && previewSigned) {
      isSignup = true
    }
    return (
      <div 
        style={{
          ...style,
          paddingTop: `${paddingTop}rem`,
          paddingBottom: `${paddingBottom}rem`
        }}
        // 修复 safari 下编辑器无法显示 position：fixed 的按钮
        ref={(node) => {
          if (node) {
            node.style.setProperty("z-index", "auto", "important");
          }
        }}
      >
        <BaseComponent {...this.props}>
          {
            this.context === null && isEdit
              ? (
                <Styled.EmptyContainer>
                  请添加该组件至 [模板活动-容器]中
                </Styled.EmptyContainer>
              )
              : this.context?.activityInfo?.actEventInfo.signupConfig || !isEdit
                ? (
                    <Styled.BtnGroup
                      fixed={fixed} 
                      isEdit={isEdit}
                      clientHeight={document.body.clientHeight - 40 - 29}
                      viewportLeft={viewportLeft + (375*(1-this.props.btnWidth/10)/2)}
                      show={!showModal}
                    >
                      <div>
                        {
                          this.renderSignupBtn({
                            ...this.props,
                            isSignup
                          })
                        }
                        {
                          this.context?.activityInfo?.actEventInfo?.signupConfig
                            && isSignup
                              && this.context?.activityInfo?.actEventInfo?.signupConfig?.quesitonNaire
                                ? (
                                  <Styled.ReSignupBtn
                                    onClick={this.handleShowModal}
                                  >
                                    重新提交问卷
                                  </Styled.ReSignupBtn>
                                )
                                : null
                        }
                      </div>
                    </Styled.BtnGroup>
                )
                : (
                  <Styled.EmptyContainer>
                    该模板活动未配置报名模块
                  </Styled.EmptyContainer>
                )
          }
          <QuestionnaireModal
            show={showModal}
            onCancel={this.hideModal.bind(this)}
            onSubmit={this.handleSignupStatusChange}
            data={this.context?.activityInfo?.actEventInfo.signupConfig?.quesitonNaire}
            refetch={this.context?.getActivityInfo}
            resubmit={isSignup}
          />
        </BaseComponent>
      </div>
    )
  }
}