import * as React from 'react';
import { Props, State } from './type';
import { Container, Divider } from './index.style';
import { jsonp } from '../utils/request';
import { getLoginInstance } from 'snail-login'
import { isSnail } from 'snail-helpers';
import { handlePathQuery } from '../utils/snailTargetHandler'

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

  static getDerivedStateFromProps(props){
    if(props.isEdit){
      return {
        title: props.title
      }
    }
  }

  public componentDidUpdate(prevProps) {
    const { topicId } = this.props
    let { timerId } = this.state
    if(prevProps.topicId !== topicId) {
      if(timerId) {
        clearTimeout(timerId)
      }
      timerId = setTimeout(() => {
        this.getTopicData(topicId)
      }, 500)
      this.setState({
        timerId
      })
    }
  }

  public async componentDidMount() {
    const { topicId } = this.props
    if(topicId) {
      if(isSnail()) {
        const login = getLoginInstance()
        // 客户端内同步登陆获取话题投票信息
        await login.isLogined()
      }
      this.getTopicData(topicId)
    }
  }

  public async getTopicData(topicId: string) {
    try {
      let res = await jsonp(`https://du.163.com/api/topic/detail.jsonp`, {
        topicId: topicId
      })
      if(res.code === 0) {
        let totalCount = 0
        if(res.topicWrapper.votable) {
          // 填充热门投票用户
          res.topicWrapper.voteOptions = res.topicWrapper.voteOptions.map(item => {
            if(!item.hotVoteUsers.length) {
              item.hotVoteUsers = [null,null,null]
            }
            totalCount += item.count
            return item
          })
        }
        this.setState({
          topicData: res.topicWrapper,
          totalCount
        })
      } else {
        this.setState({
          tips: '话题id输入有误'
        })
      }
    } catch {
      this.setState({
        tips: '话题id输入有误'
      })
    }
  }

  public clickHanler(topicId) {
    const { pos, isEdit } = this.props
    handlePathQuery({
      path: 'topicDetail',
      query: {
        topicId
      },
      logPointId: 'acttemplate1-7',
      logQuery: {
        category: 'acttemplate',
        topicId: topicId,
        pos
      },
      isEdit
    })
  }

  public render() {
    const { isEdit, style, banner, topicId, title } = this.props
    const { topicData, tips, totalCount } = this.state
    return (
      <Container style={{...style}}>
        {
          title ? <h1 className="title">
            {title}
          </h1> : null
        }
        {
            topicData ? <div className="topic" onClick={this.clickHanler.bind(this, topicId)}>
              {
                !topicData.votable && banner
                  ?  <img className="banner" src={banner.url} alt=""/> 
                  : null
              }
              <div className="topic__title">{topicData.topic.title}</div>
              <div className="topic__info">
                <span className="data">{topicData.topic.feedCount}篇内容</span>
                <span className="data right">{topicData.topic.followCount}人关注</span>
              </div>
              {
                topicData.votable ? <div className="topic__vote">
                  <div className="options">
                    {
                      topicData.voteOptions.map((item, index) => {
                        return (
                          <span
                            key={item.option.optionId} 
                            className={topicData.voteOptions.length === 3 ? 'item' : 'item-2'}
                          >
                            <span className={`box-text ${
                                topicData.votedOption 
                                ? topicData.votedOption.option.optionId === item.option.optionId
                                 ? `checked-${index}`
                                 : ''
                                : ''
                              }`}>
                              {item.option.optionText}
                              {
                                topicData.votedOption && topicData.votedOption.option.optionId === item.option.optionId
                                  ? <img className="icon" src="https://easyreadfs.nosdn.127.net/debddb7430c34b559d115350422de89f_1569327160273.png" alt="icon"/>
                                  : null
                              }
                            </span>
                            <div className="vote-users">
                              {
                                item.hotVoteUsers.map((user, index) => {
                                  return <span key={index} className="avatar">
                                    {
                                      user 
                                        ? <img src={user.imageUrl} alt="avatar"/>
                                        : <span className="empty-avatar"></span>
                                    }
                                  </span>
                                })
                              }
                            </div>
                            <span className="count"> { item.count } 人支持</span>
                          </span>
                        )
                      })
                    }
                  </div>
                  {
                    topicData.votedOption 
                      ? <div className="percent-select">
                        {
                          topicData.voteOptions.map((item, index) => {
                            let percent = Math.floor((item.count / totalCount) * 100)
                            return <span className={`percent-item ${
                              `checked-${index}`
                            } ${
                              index === topicData.voteOptions.length -1 ? 'last' : ''
                            }`} style={{
                              width: `${percent}%`,
                              display: percent === 0 ? 'none' : 'inline-block'
                            }}
                            >
                              {
                                percent >= 10 ? `${Math.round((item.count / totalCount) * 100)}%` : ''
                              }
                            </span>
                          })
                        }
                      </div>
                      : <div className="percent">选择观点后查看百分比</div>
                  }
                </div> : <div className="topic-desc">
                    {topicData.topic.description}
                </div>
              }
            </div> : <span>{tips}</span>
        }
        {
          !tips && !title && !topicId && isEdit && <div>蜗牛话题</div>
        }
        { topicData && <Divider/> }
      </Container>
    )
  }
}