import * as React from 'react'
import { openAppLofter } from 'nw-app-lofter'


import { fetchMyColList } from '../actions'
import { CollectionPanel, OwnColDetail } from '../collection-panel'
import { NoColModal } from '../no-col-modal'
import { showMessage } from '../../common/toast/toast'

import {
  Container,
  Button
} from './index.style'

interface Props {
  className?: string;
  refresh: () => void;
  myInviteLength: number;
  activityId: string;
}

interface State {
  showPanel: boolean;
  showModal: boolean;
  colList: OwnColDetail[];
  loading: boolean;
}

export class InviteButton extends React.Component<Props> {
  state: State = {
    showPanel: false,
    showModal: false,
    colList: [],
    loading: false
  }

  getColList = () => {
    this.setState({
      loading: true
    })
    return fetchMyColList({
      activityId: this.props.activityId
    })
      .then(res => {
        this.setState({
          colList: res.data.collections,
          loading: false
        })
        return res.data.collections.length
      }).catch(() => {
        this.setState({
          loading: false
        })
      })
  }

  openPanel = async () => {
    const ua = window.navigator.userAgent.toLowerCase()
    /** 校验端内/端外 */
    if (!ua.includes('lofter')) {
      openAppLofter({
        path: 'webview',
        query: {
          url: window.location.href
        }
      })
      return 
    }
    if (this.state.loading) return
    if (this.props.myInviteLength >= 3) {
      showMessage({
        text: '你已达到邀请上限（3个）哦！'
      })
      return
    }
    let length = await this.getColList()
    if (length > 0) {
      this.setState({
        showPanel: true
      })
    } else if (length === 0) {
      this.setState({
        showModal: true
      })
    }
  }

  closePanel = () => {
    this.setState({
      showPanel: false
    })
  }

  render() {
    const {
      className,
      refresh
    } = this.props
    const {
      showPanel,
      showModal,
      colList,
      loading
    } = this.state

    return (
      <Container
        className={className}
      >
        {/* loading */}
        <Button
          onClick={this.openPanel}
        >
          {
            loading
              ? '加载中...'
              : '发布公开邀请'
          }
        </Button>
        <CollectionPanel
          show={showPanel}
          close={this.closePanel}
          data={colList}
          refresh={refresh}
          activityId={this.props.activityId}
        />
        <NoColModal
          show={showModal}
          onCancel={() => {
            this.setState({
              showModal: false
            })
          }}
        />
      </Container>
    )
  }
}
