import React, { Component } from 'react';
import './index.scss'
import { Tabs, Toast } from "antd-mobile";
import { http } from "@/utils"
import storage from 'store2'
import { html } from '@/utils'
import { compareDesc } from "date-fns";
import { Link } from "react-router-dom";
import { connect } from "react-redux";


class Scores extends Component {

  store = storage.namespace('aiTestEntry')


  state = {
    selfTabs: [
      {title: '当前成绩'},
      {title: '今日最佳'},
      {title: '本月最佳'},
    ],
    rankList: [],
    rankListTabs: [
      {title: '日榜'},
      {title: '总榜'},
    ],
/*
    rankListTabs: [
      {title: '日榜'},
      {title: '周榜'},
      {title: '总榜'},
    ],
*/
    isExpandRankList: false,
    icons: [
      require('./rank-1.png'),
      require('./rank-2.png'),
      require('./rank-3.png'),
    ],
    isShowRule: false,
    isNeverShow: this.store.get('isNeverShow'),
    pageState: {},
    availableTestNum: 0,
    userScore: {},
    userAddress: {
      name: '',
      phone: '',
      address: '',
    },
    isShowUserAddress: false,
    entryButtonInRule: false,
  }

  componentDidMount() {
    this.getInitialData()
    this.getRankList(null, 0)
    if (!this.props.user.hasError) {
      this.getUserScores(0)
      this.getUserAddress()
    }
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.props.user.hasError !== prevProps.user.hasError) {
      this.getUserScores(0)
      this.getUserAddress()
    }
  }


  handleChange = (e) => {
    const isNeverSHow = e.target.checked
    this.setState({
      isNeverSHow,
    })
    this.store.set('isNeverShow', isNeverSHow)
  }

  startTest = () => {
    this.props.history.push('/ai-test/exam')
  }

  getInitialData = () => {
    http.get(`${API.home}/sys/activity_data`)
      .then(res => {
        const {code, msg, data} = res.data
        if (code === 200) {
          this.setState({
            pageState: data,
          })
        } else if (code === 3009) {
          this.props.history.push('/')
        } else {
          Toast.fail(msg, 2, null, false)
        }
      })
  }

  getRankList = (tab, type) => {
    http.get(`${API.home}/sys/at/ranks/${type === 0 ? 0 : 2}`)
      .then(res => {
        const {code, msg, data} = res.data
        if (code === 200) {
          this.setState({
            rankList: data,
          })
        } else {
          Toast.fail(msg, 2, null, false)
        }
      })
  }

  getUserScores = (type) => {
    http.get(`${API.home}/sys/at/user_score/${type}/0`)
      .then(res => {
        const {code, msg, data} = res.data

        if (code === 200) {
          this.setState({
            userScore: data,
          })
        } else {
          Toast.fail(msg, 2, null, false)
        }
      })
  }

  getUserAddress = () => {
    http.get(`${API.home}/sys/user_address_info`)
      .then(res => {
        const {code, msg, data} = res.data
        if (code === 200) {
          this.setState({
            userAddress: data,
          })
        }
      })
  }

  inputText = e => {
    const key = e.target.name
    const value = e.target.value
    this.setState(state => {
      return {
        userAddress: {
          ...state.userAddress, ...{
            [key]: value,
          },
        },
      }
    })
  }

  submitForm = (e) => {
    e.preventDefault()
    const {userAddress} = this.state
    if (!Object.values(userAddress).every(item => !!item)) {
      Toast.info('请填写完整')
      return
    }
    http.post(`${API.home}/sys/update_address`, userAddress)
      .then(res => {
        const {code, msg, data} = res.data
        if (code === 200) {
          Toast.success('提交成功', 2, null, false)
          this.setState({
            isShowUserAddress: false,
          })
        } else {
          Toast.fail(msg, 2, null, false)
        }
      })
  }

  render() {
    const {
      selfTabs,
      rankList,
      rankListTabs,
      icons,
      isExpandRankList,
      isShowRule,
      isNeverShow,
      pageState,
      userScore,
      isShowUserAddress,
      userAddress,
      entryButtonInRule,
    } = this.state
    const {user, history} = this.props
    const _rankList = Array.isArray(rankList) ? isExpandRankList ? rankList : rankList.slice(0, 10) : []
    return (
      <div className={'scores'}>
        <div className="banner">
          <img src={pageState.h5_banner} alt=""/>
        </div>
        <div className="info">
          <span>已有{pageState.join_num}人参加测试</span>
          <a href="javascript:void(0);" onClick={() => {
            this.setState({
              isShowRule: true,
            })
          }}>规则</a>
        </div>
        {
          <div className="score-list">
            <Tabs tabs={selfTabs} tabBarUnderlineStyle={{display: 'none'}} onChange={(tab, i) => {
              this.getUserScores(i)
            }}>
              {
                selfTabs.map((tab, index) => {
                  return <div className={'tab-content'} key={index}>
                    <table>
                      <thead>
                      <tr>
                        <th>分数</th>
                        <th>用时</th>
                        <th>{index === 0 && '最终'}排名</th>
                      </tr>
                      </thead>
                      <tbody>
                      {
                        user.hasError
                          ? <tr>
                            <td>--</td>
                            <td>--</td>
                            <td>--</td>
                          </tr>
                          : <tr>
                            {
                              userScore.score === '-' ? <td>'-'</td> :
                                <td>{userScore.score} <Link to={`/ai-test/analysis/${userScore.r_id}`}>解析</Link></td>
                            }
                            <td>{userScore.cost_time}</td>
                            {
                              userScore.rank === '-' ? <td>'-'</td> : <td>{userScore.rank}名</td>
                            }
                          </tr>
                      }
                      </tbody>
                    </table>
                  </div>
                })
              }
            </Tabs>
            <div className="share">
              <Link to={'/ai-test/report'}>分享</Link>
            </div>
          </div>
        }
        <div className="rank-list">
          <div className="head">
            <div>
              测试排行榜
            </div>
            <div>
              <span>仅显示前50名</span>
              <a href="javascript:void(0);" onClick={() => {
                if (user.hasError) {
                  history.push('/passport')
                } else {
                  this.setState({
                    isShowUserAddress: true,
                  })
                }
              }}>收货地址</a>
            </div>
          </div>
          <div className="list">
            <Tabs tabs={rankListTabs} tabBarUnderlineStyle={{display: 'none'}} onChange={this.getRankList}>
              {
                rankListTabs.map((item, index) => {
                  return <table key={index}>
                    <thead>
                    <tr>
                      <th>名次</th>
                      <th>昵称</th>
                      <th>成绩</th>
                      <th>奖品</th>
                    </tr>
                    </thead>
                    <tbody>
                    {
                      !!_rankList.length && _rankList.map((item, index) => {
                        return <tr key={index}>
                          <td>
                            {
                              index < 3 ? <img src={icons[index]} alt=""/> : index + 1
                            }
                          </td>
                          <td>
                            <img src={item.avatar} className={'avatar'} alt=""/>
                            {item.user_name}
                          </td>
                          <td>
                            <span className={'score'}>{item.score}</span>/<span>{item.cost_time}</span>
                          </td>
                          <td>
                           <div>
                             {
                               item.prize_url ? <a href={`${item.prize_url}#goback`}>{item.prize}</a> : item.prize
                             }
                           </div>

                          </td>
                        </tr>
                      })
                    }
                    </tbody>
                  </table>
                })
              }
            </Tabs>
            {
              rankList.length > 10 && (!isExpandRankList ?
                  <div className="expand" onClick={() => {
                    this.setState({
                      isExpandRankList: true,
                    })
                  }}>
                  <span>
                    展开更多
                    <i className={'iconfont iconiconfront-69'}></i>
                  </span>
                  </div>
                  :
                  <div className="expand" onClick={() => {
                    this.setState({
                      isExpandRankList: false,
                    })
                  }}>
                  <span>
                    收起
                    <i className={'iconfont iconiconfront-71'}></i>
                  </span>
                  </div>
              )
            }
          </div>
        </div>
        <div className="qrcode">
          <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/ai-test/qr.png" alt=""/>
          <div>得100分，请长按/扫码，免费领课！</div>
        </div>
        <div className="btn">
          {
            compareDesc(new Date(), pageState.stop_time * 1000) > 0 ?
              pageState.daily_test_num > 0
                ? <button className={'available'} onClick={() => {
                  isNeverShow ? this.startTest() : this.setState({
                    entryButtonInRule: true,
                    isShowRule: true,
                  })
                }}>开始测试<span>（今日可测试{pageState.daily_test_num}次）</span></button>
                : <Link to={`/ai-test/share?shareCode=${pageState.code}`}>
                  <button className={'get-chance'}>获取测试机会<span>（今日可测试0次）</span></button>
                </Link>
              : <button className={'unavailable'}>活动已结束</button>
          }
        </div>
        {
          isShowRule &&
          <Rule rule={pageState.rule} startTest={this.startTest} neverShow={this.handleChange} isNeverShow={isNeverShow}
                close={() => {
                  this.setState({
                    isShowRule: false,
                    entryButtonInRule: false,
                  })
                }} entryButtonInRule={entryButtonInRule}/>
        }
        {
          isShowUserAddress &&
          <div className="user-address-wrapper">
            <div className="user-address">
              <div className="title">收货信息</div>
              <div className="tip">获奖用户（以最终榜单为准）请及时填写收货信息</div>
              <form action="" onSubmit={this.submitForm}>
                <input type="text" placeholder={'收件人'} name={'name'} onChange={this.inputText}
                       value={userAddress.name}/>
                <input type="tel" placeholder={'联系方式'} name={'phone'} onChange={this.inputText}
                       value={userAddress.phone}/>
                <input type="text" placeholder={'收货地址'} name={'address'} onChange={this.inputText}
                       value={userAddress.address}/>
                <button type={'submit'}
                        className={Object.values(userAddress).every(value => !!value) ? 'available' : ''}>提交
                </button>
              </form>
              <i className={'close iconfont iconiconfront-2'} onClick={() => {
                this.setState({
                  isShowUserAddress: false,
                })
              }}/>
            </div>
          </div>
        }
      </div>
    );
  }
}

function Rule({neverShow, isNeverShow, rule, close, startTest, entryButtonInRule}) {
  return <div className="rule-mask">
    <div className="rule">
      <div>测试规则</div>
      <div dangerouslySetInnerHTML={html(rule)}></div>
      {
        entryButtonInRule && <>
          <div className="option">
            <input id={'never-show'} type="checkbox" onChange={neverShow} checked={isNeverShow}/>
            <label htmlFor="never-show">不再提示</label>
          </div>
          <button onClick={startTest}>进入测试</button>
        </>
      }
      <i className={'close iconfont iconiconfront-2'} onClick={close}/>
    </div>
  </div>
}


export default connect(
  ({user}) => ({user}),
  null,
)(Scores);