import React, { Component } from 'react'
import { getCoinRechargeItemsGuest, addCoinRechargeOrderGuest, addPayOrderGuest } from '@/services/common'
import styles from './Recharge.less'
import iconGold from '@/assets/icon_gold.png'
import iconDefaultAvatar from '@/assets/icon_default_avatar.png'
import { notification, Modal } from 'antd'
import Login from './Login'

class Recharge extends Component {
  constructor (props) {
    super(props)
    this.state = {
      choosenItem: {},
      visible: false,
      userInfo: {},
    }
  }
  componentDidMount () {
    const userString = localStorage.userInfo
    const { no, amount, res } = this.props.location.query
    if (userString) {
      const json = JSON.parse(userString)
      this.setState({ userInfo: json })
    }
    
    if (res === '1') {
      notification.success({
        message: '充值成功',
        description: <div><p>订单号: {no}</p><p>支付金额: {amount}</p> </div>,
        duration: 0
      })
    }
    this.getCoinRechargeItemsGuest()
  }

  // 获取充值项目
  getCoinRechargeItemsGuest = async () => {
    const _state = {}
    try {
      const { code, data } = await getCoinRechargeItemsGuest()
      if (code === 'OK' && data) {
        const { list } = data
        const payAliPc = list && list.find(item => item.payWay === 204)
        _state.payAliPc = (payAliPc && payAliPc.items) || []
      } 
    } catch (e) {
      console.log(e)
    }
    this.setState(_state)
  }

  onChoose = (item) => () => {
    this.setState({ choosenItem: item })
  }

  // 充值
  onRecharge = async (e) => {
    e.preventDefault()
    const { choosenItem, userInfo } = this.state
    if (!choosenItem || !choosenItem.itemId) {
      notification.error({message: '请选择充值金额'})
      return
    }
    if (!userInfo || !userInfo.userId) {
      notification.error({ message: '请先登录' })
      return
    }
    if (this.state.uploading) {
      return
    }
    this.setState({ uploading: true })
    // 创建金币充值订单
    const { code, data } = await addCoinRechargeOrderGuest({
      itemId: choosenItem.itemId, userId: userInfo.userId
    })
    if (code === 'OK' && data) {
      const { orderId } = data
      this.addPayOrderGuest(orderId)
    }
  }
  addPayOrderGuest = async (orderId) => {
    const { code, data } = await addPayOrderGuest({ orderId })
    if (code === 'OK' && data) {
      const { payParams } = data
      const node = document.createElement('div')
      node.innerHTML = payParams
      document.body.appendChild(node)
      
      if (document.forms[0]) {
        document.forms[0].submit();
      }
      
    }
    this.setState({ uploading: false })
  }

  // 登录
  onLogin = () => {
    this.setState({ visible: true })
  }
  onModalCancel = () => {
    this.setState({ visible: false })
  }

  // 登录成功
  onLoginOk = (data) => {
    localStorage.userInfo = JSON.stringify(data)
    this.setState({ visible: false, userInfo: data })
  }

  // 退出登录
  onLoginOut = () => {
    localStorage.removeItem('userInfo')
    this.setState({
      userInfo: {}
    })
  }

  render () {
    const { payAliPc, choosenItem, visible, userInfo, uploading, payParams } = this.state
    return (
      <div className={styles['wrap']}>
        <div className={styles['header-wrap']}>
          <div className={styles['user-default-info']} onClick={this.onLogin} hidden={userInfo && userInfo.userId}>
            <img src={iconDefaultAvatar} alt=""/>
            <span>登录</span>
          </div>
          <div className={styles['user-info']} hidden={!userInfo || !userInfo.userId}>
            <img src={userInfo.userAvatar} alt=""/>
            <div className={styles['user-name']}>
              <h4>{userInfo.userName}</h4>
              <p>ID:{userInfo.userId}</p>
            </div>
          </div>
          <div hidden={!userInfo || !userInfo.userId} onClick={this.onLoginOut} className={styles['logout-btn']}> 
            退出登录
          </div>
        </div>
        <div className={styles['content-wrap']}>
          <div className={styles['banner-bg']}></div>
          <div className={styles['main-content-wrap']}>
            <div className={styles['list-wrap']}>
              {
                payAliPc && payAliPc.map((item) => (
                  <div 
                    key={item.itemId} 
                    className={styles['list-item-wrap']}
                  >
                    <div 
                      className={
                        `${styles['list-item']} ${choosenItem && choosenItem.itemId === item.itemId ? styles['list-item-active'] : ''}`
                      } 
                      onClick={this.onChoose(item)}
                    >
                      <div className={styles['item-top']}>
                        <img src={iconGold} alt=""/>
                        <span>{item.itemCoin}</span>
                      </div>
                      
                      <div className={styles['item-price']}>¥ {item.itemPrice}</div>
                    </div>
                  </div>
                ))
              }
            </div>

            <div className={styles['recharge-btn-wrap']}>
              <a 
                href="#" 
                className={`${styles['recharge-btn']} ${uploading?styles['recharge-btn-loading']:''}`} 
                onClick={this.onRecharge}
              >充值</a>
            </div>
          </div>
        </div>
        <Login 
          visible={visible}
          onCancel={this.onModalCancel}
          onOk={this.onLoginOk}
        />
      </div>
    )
  }
}
export default Recharge
