import * as React from 'react'
import { LofterTitle } from '../lofterTitle'
import log from '../utils/lofter-log'
import { BaseComponent } from '../base-component'
import { imgResize } from '../utils/imgResize'
import { showMessage } from '../common/toast/toast';
import { isUpAppVersion, ios } from 'nw-detect';
import LazyLoad from 'react-lazy-load'
import debounce from 'lodash.debounce';
import { get, post } from '../utils/request'
import { getDeviceId } from '../utils/lofter-log'

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

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

const AVATAR_TYPE = 0,
  DRESSING_TYPE = 4,
  MUSICVIP_TYPE = 5

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

  state = new State()

  getGiftList = async (day: number) => {
    const mockUrl = 'https://nei.hz.netease.com/api/apimock-v2/c6da9202198a943efec7f11c8a937f16/newweb/giftPacks/secondDay.json'
    const url = day === 2 ? '//www.lofter.com/newweb/giftPacks/secondDay.json' : '//www.lofter.com/newweb/giftPacks/thirdDay.json'
    const res = await get(url)

    if (res.code === 0) {
      this.setState({
        giftList: res.data
      })
    }
  }

  receiveGift = debounce(async (type: number) => {
    const { giftList } = this.state
    const mockUrl = 'https://nei.hz.netease.com/api/apimock-v2/c6da9202198a943efec7f11c8a937f16/newweb/giftPacks/receive.json'
    const url = '//www.lofter.com/newweb/giftPacks/receive.json'
    post(url, {
      type
    }).then(res => {
      if (res.code !== 0) {
        return showMessage(res.msg)
      }
      if (res.data.res) {
        showMessage(`${type === 5 ? '领取成功！兑换方式请查看私信。' : '领取成功！'}`)
        const temp = giftList
        switch (type) {
          case 0:
            log.capture('newusergift-2', {
              category: 'newusergift',
              action: 101,
              scene: 'newusergift',
              v: '1.0.0',
              activityId: 'newusergif'
            });
            temp.avatarBox.status = 1
            break
          case 4:
            log.capture('newusergift-7', {
              category: 'newusergift',
              action: 101,
              scene: 'newusergift',
              v: '1.0.0',
              activityId: 'newusergif'
            });
            temp.dressingSuit.status = 1
            break
          case 5:
            log.capture('newusergift-8', {
              category: 'newusergift',
              action: 101,
              scene: 'newusergift',
              v: '1.0.0',
              activityId: 'newusergif'
            });
            temp.musicVip.status = 1
            break
        }
        this.setState({
          giftList: temp
        })
      } else {
        showMessage('领取失败')
      }
    })
  }, 1000, {
    leading: true,
    tailing: false,
  })

  getBind = async () => {
    const mockUrl = 'https://nei.hz.netease.com/api/apimock-v2/c6da9202198a943efec7f11c8a937f16/newweb/phoneAccount/getBind.json'
    const url = '//www.lofter.com/newweb/phoneAccount/getBind.json'

    const res = await get(url)
    if (res.code === 0) {
      if (!res.data?.bindPhone && !res.data?.verifyPhone) {
        return window.location.href = 'https://www.lofter.com/front/homesite/gift-packs/bind-phone'
      }
      return this.receiveGift(MUSICVIP_TYPE)
    }
  }

  initData = () => {
    this.getGiftList(this.props.day);
  }

  pageReload = () => {
    if (ios()) {
      const persistHandler = (event: any) => {
        if (event.persisted || performance.getEntriesByType("navigation")[0].type === 'back_forward') {
          this.initData()
        }
        return () => {
          window.removeEventListener('pageshow', persistHandler);
        }
      }
      window.addEventListener('pageshow', persistHandler);
    } else {
      document.addEventListener('visibilitychange', this.initData)
      return () => {
        document.removeEventListener('visibilitychange', this.initData)
      }
    }
  }

  componentDidMount() {
    this.pageReload();
    this.initData();
  }

  componentDidUpdate(preProps: any) {
    if (this.props.day !== preProps.day) {
      this.getGiftList(this.props.day);
    }
  }

  render() {
    let { style, marginTop, title, dressingImage, musicImage, avatarImage } = this.props
    let { giftList } = this.state
    return (
      <Styled.Container style={style}>
        <BaseComponent {...this.props}>
          <div className={marginTop && 'f-before'} style={{ marginTop: `${marginTop}rem` }}>
            {
              title &&
              <LofterTitle title={title} />
            }
            {
              giftList
              && giftList.musicVip
              && (
                <div
                  className='musicVipBox'
                  style={{ backgroundImage: `url(${musicImage ? musicImage.url : ''})` }}
                // style={{ backgroundImage: 'url("https://imglf6.lf127.net/bkimg/20221116094556/be18ab41-57c3-4611-b377-0d81ec448441.png")'}}
                >
                  <div className='musicVipContent'>
                    <LazyLoad className="musicVipImg" offsetVertical={900}>
                      <img src='https://imglf6.lf127.net/bkimg/20221115174222/88017531-9738-46ca-bcbb-711dbbcd83e1.png' />
                    </LazyLoad>
                    <div className='name'>
                      {giftList.musicVip.name}
                    </div>
                    <div className='text'>
                      {giftList.musicVip.tip}
                    </div>
                    <button
                      type='button'
                      className={`button ${giftList.musicVip.status === 1 ? 'disabled' : ''}`}
                      disabled={giftList.musicVip.status === 1}
                      onClick={this.getBind}
                    >
                      {giftList.musicVip.status === 1 ? '已领取' : '立即领取'}
                    </button>
                  </div>
                </div>
              )
            }
            {
              giftList
              && giftList.dressingSuit
              && (
                <div
                  className='dressingBox'
                  style={{ backgroundImage: `url(${dressingImage ? dressingImage.url : ''})` }}
                // style={{ backgroundImage: 'url("https://imglf4.lf127.net/bkimg/20221116095922/77534ffe-ec83-485b-a8a7-3e2c44034c1f.png")'}}
                >
                  <div className='dressingContent'>
                    <div className='dressingImgBox'>
                      <img
                        className='bkgImg'
                        src="https://imglf6.lf127.net/bkimg/20221124111228/6540d0e0-06fc-4e72-8ef6-74cbef6071ee.png"
                        alt=""
                      />
                      <img
                        className='svgImg'
                        src="https://imglf5.lf127.net/bkimg/20221124111832/e1ebc2cf-bc02-4120-a8a9-082a02ecc25c.png"
                        alt=""
                      />
                      <img
                        className='dressingImg'
                        src={imgResize(giftList.dressingSuit.img, 168, 168, 1)}
                        alt=""
                      />
                    </div>
                    <div className='name'>
                      {giftList.dressingSuit.name}
                    </div>
                    <div className='text'>
                      快去试试装扮套装吧~
                    </div>
                    <button
                      type='button'
                      className='button'
                      onClick={() => {
                        if (giftList.dressingSuit.status === 1) {
                          return window.location.href = 'https://www.lofter.com/front/suit/my?njb_navigator=false'
                        }
                        if (!isUpAppVersion('7.2.4')) {
                          showMessage('请升级最新版本后，再次领取。')
                        } else {
                          this.receiveGift(DRESSING_TYPE)
                        }
                      }}
                    >
                      {giftList.dressingSuit.status === 1 ? '激活并装扮' : '立即领取'}
                    </button>
                  </div>
                </div>
              )
            }
            {
              giftList
              && giftList.avatarBox
              && (
                <div
                  className='avatarContent'
                  style={{ backgroundImage: `url(${avatarImage ? avatarImage.url : ''})` }}
                // style={{ backgroundImage: 'url("https://imglf4.lf127.net/bkimg/20221116100556/0c779f4a-93e7-4ca9-b499-4b8f71360a46.png")'}}
                >
                  <LazyLoad className="avatarImg" offsetVertical={900}>
                    <img src={imgResize(giftList.avatarBox.image, 234, 234, 1, true)} />
                  </LazyLoad>
                  <div className='name'>
                    {giftList.avatarBox.name}
                  </div>
                  <div className='text'>
                    在下萌新一枚~
                  </div>
                  <button
                    type='button'
                    className='button'
                    // eslint-disable-next-line consistent-return
                    onClick={() => {
                      if (giftList.avatarBox.status === 1) {
                        window.location.href = 'https://www.lofter.com/front/account/avatar-box-center?njb_navigator=false'
                      } else {
                        this.receiveGift(AVATAR_TYPE)
                      }
                    }}
                  >
                    {giftList.avatarBox.status === 1 ? '前往佩戴' : '立即领取'}
                  </button>
                </div>
              )
            }
          </div>
        </BaseComponent>
      </Styled.Container>
    )
  }
}
