import * as React from 'react'
import { createPortal } from 'react-dom'

import debounce from 'lodash.debounce'

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

import { showMessage } from '../../common/toast/toast'
import { QuetionNaire, QuestionItem } from '../../template-activity-container/type'
import Input from '../input'
import Textarea from '../text-area'
import Select from '../select'
import { signupRequest } from '../signup-request'
import { TemplateActivityContext } from '../../common/template-context'
import { lock, unlock } from '../../utils/body-scroll-lock'
import log from '../../utils/lofter-log'

interface Props {
  show: boolean;
  onCancel: () => void;
  onSubmit: () => void;
  data?: QuetionNaire;
  refetch?: () => Promise<any>;
  resubmit?: boolean;
}

class QuestionnaireModal extends React.Component<Props> {

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

  modalContent: HTMLElement;

  state = {
    formValue: {}
  }

  handleValueChange = (item: QuestionItem, value: string) => {
    const { formValue } = this.state
    this.setState({
      formValue: {
        ...formValue,
        [item.name]: value
      }
    })
  }

  renderTitle = (item: QuestionItem, index: number) => {
    return (
      <Styled.ModalContentQuesTitle>
        {
          item.required
            ? <img className="required" src="https://lofter.lf127.net/1618386338359/required.png" alt=""/>
            : null
        }
        <span>Q{index + 1}：</span>
        <span>{item.name}</span>
        {
          item.type === 'checkbox'
            ? '(多选)'
            : ''
        }
      </Styled.ModalContentQuesTitle>
    )
  }

  renderQues = (item: QuestionItem, index: number) => {
    if (item.type === 'input') {
      return (
        <Styled.ModalContentQuesItem key={item.name}>
          {
            this.renderTitle(item, index)
          }
          <Input 
            placeholder={item.placeholder}
            onChange={this.handleValueChange.bind(this, item)}
            limit={item.limit}
            isLast={index === this.props.data?.questionItems?.length - 1}
          />
        </Styled.ModalContentQuesItem>
      )
    } else if (item.type === 'textarea') {
      return (
        <Styled.ModalContentQuesItem key={item.name}>
          {
            this.renderTitle(item, index)
          }
          <Textarea 
            placeholder={item.placeholder}
            onChange={this.handleValueChange.bind(this, item)}
            limit={item.limit}
            isLast={index === this.props.data?.questionItems?.length - 1}
          />
        </Styled.ModalContentQuesItem>
      )
    } else if (
      item.type === 'radio'
      || item.type === 'checkbox'
    ) {
      return (
        <Styled.ModalContentQuesItem key={item.name}>
          {
            this.renderTitle(item, index)
          }
          <Select
            options={item.options}
            type={item.type}
            onChange={this.handleValueChange.bind(this, item)}
          />
        </Styled.ModalContentQuesItem>
      )
    }
  }

  validateForm = () => {
    return new Promise((resolve) => {
      this.props.data?.questionItems?.filter(item => item.required)
        .forEach(item => {
          if (!this.state.formValue[item.name]) {
            showMessage({
              text: '你的问卷还未答完喔~'
            })
            resolve(false)
            return
          }
        })
      this.props.data?.questionItems?.forEach((item, index) => {
        if (
          item.limit 
          && this.state.formValue[item.name] 
          && this.state.formValue[item.name].length > item.limit) {
          showMessage({
            text: `Q${index+1}问题字数限制${item.limit}内`
          })
          resolve(false)
        }
      })
      resolve(true)
    })
  }

  submit = debounce(async () => {
    let res = await this.validateForm()
    let data = Object.keys(this.state.formValue).map(item => ({
      question: item,
      answer: this.state.formValue[item]
    }))
    if (res) {
      try {
        log.capture('act-4', {
          category: 'actmould',
          action: 101,
          scene: 'actmould',
          actid: this.context?.activityInfo?.actEventInfo?.activityId,
          v: 'H5'
        })
        let fetchRes = await signupRequest({
          activityId: this.context?.activityInfo?.actEventInfo.activityId,
          data,
          resubmit: this.props.resubmit ? 1 : 0
        })
        // 请求成功
        if (fetchRes) {
          this.props.onCancel()
          // this.props?.refetch()
          if (!this.props.resubmit) {
            this.props.onSubmit()
          }
        }
      } catch(err) {
        console.log(err)
        // 请求发生未知错误
        showMessage({
          text: '请求失败'
        })
      }
    }
  }, 400)

  componentDidUpdate(preProps) {
    if (preProps.show !== this.props.show && this.props.show) {
      lock(this.modalContent)
    } else if (preProps.show !== this.props.show && !this.props.show) {
      unlock()
    }
  }

  public render() {
    const {
      show,
      onCancel,
      data
    } = this.props
    return (
      createPortal((
        <Styled.ModalContainer show={show}>
          <Styled.ModalMask onClick={onCancel} />
          <Styled.ModalContent>
            <Styled.ModalScroll
              ref={ref => this.modalContent = ref}
            >
              <Styled.ModalContentHeader>
                <Styled.ModalContentHeaderTitle>
                  {data?.name}
                </Styled.ModalContentHeaderTitle>
                <Styled.ModalContentHeaderDesc>
                  {data?.intro}
                </Styled.ModalContentHeaderDesc>
              </Styled.ModalContentHeader>
              <Styled.ModalContentBody>
                {
                  data?.questionItems?.map((item, index) => this.renderQues(item, index))
                }
              </Styled.ModalContentBody>
            </Styled.ModalScroll>
            <Styled.ModalContentFooter>
              <Styled.ModalContentFooterFlex>
                <Styled.ModalContentFooterBtn onClick={onCancel}>
                  取消
                </Styled.ModalContentFooterBtn>
                <Styled.ModalContentFooterBtn type="primary" onClick={this.submit}>
                  我要报名
                </Styled.ModalContentFooterBtn>
              </Styled.ModalContentFooterFlex>
            </Styled.ModalContentFooter>
          </Styled.ModalContent>
        </Styled.ModalContainer>
      ), document.getElementById('app')!)
    )
  }
}

export default QuestionnaireModal
