import * as React from 'react';
import { getLoginInstance } from 'snail-login'
import { isSnail, isIphone } from 'snail-helpers';
import { getLogInstance } from 'snail-log';
import { Container } from './item.style';
import { jsonp } from '../../utils/request';
import { formatAvatar } from '../../utils/format';

export class Props {
  loginPromise: Promise<void>;
  id: number;
  userDesc: string;
  bookDesc: string;
  shareRead: any;
  shareReadData: any;
  title: string;
  isEdit: boolean;
}

export class State {
  public shareRead;
  public shareReadData;
  public timerId = 0;
  public status = 1;
  public isBtnShow = false;
  public leftBtnText = '';
  public rightBtnText = '';
  public leftClass = '';
  public rightClass = '';
  public priceUnit = '';
}

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

  // public componentDidUpdate(prevProps, prevState) {
  //   const { shareReadId } = this.props
  //   let { timerId, status } = this.state
  //   if(prevProps.shareReadId !== shareReadId) {
  //     if(timerId) {
  //       clearTimeout(timerId)
  //     }
  //     timerId = setTimeout(() => {
  //       this.getShareReadData(shareReadId)
  //     }, 500)
  //     this.setState({
  //       timerId,
  //     })
  //   }
  // }

  public async componentDidMount() {
    const { id } = this.props
    this.setState({
      priceUnit: isIphone() ? '币' : '元'
    })
    if(id) {
      if(isSnail()) {
        const login = getLoginInstance()
        // 客户端内同步登陆获取所在共读信息
        await login.isLogined()
      }
      this.getShareReadData(id)
    }
  }

  public updateStatus(status: number) {
    const { shareRead, priceUnit } = this.state
    switch (status) {
      case -4:
        {
          this.setState({
            isBtnShow: false,
            leftClass: 'btn-1-dis',
            leftBtnText: '共读已结束'
          })
        }
        break
      case -3:
        {
          this.setState({
            isBtnShow: false,
            leftClass: 'btn-1-dis',
            leftBtnText: '共读已解散'
          })
        }
        break
      case -2:
        {
          this.setState({
            isBtnShow: false,
            leftClass: 'btn-1-watch',
            leftBtnText: '免费围观'
          })
        }
        break
      case -1:
        {
          this.setState({
            isBtnShow: false,
            leftClass: 'btn-1-watch',
            leftBtnText: `${shareRead.watchMoney / 100}${
              priceUnit
            }围观`
          })
        }
        break
      case 1:
        {
          this.setState({
            isBtnShow: false,
            leftClass: 'btn-1 strong',
            leftBtnText: '立即加入'
          })
        }
        break
      case 2:
        {
          this.setState({
            isBtnShow: false,
            leftClass: 'btn-1 strong',
            leftBtnText: `${shareRead.joinMoney / 100}${
              priceUnit
            }参加共读`
          })
        }
        break
      case 3:
        {
          this.setState({
            isBtnShow: false,
            leftClass: 'btn-1-dis',
            leftBtnText: '共读人数已满'
          })
        }
        break
      case 4:
        {
          this.setState({
            isBtnShow: true,
            leftClass: 'btn-2-watch left',
            leftBtnText: '限免围观',
            rightClass: 'btn-2 strong',
            rightBtnText: '立即加入'
          })
        }
        break
      case 5:
        {
          this.setState({
            isBtnShow: true,
            leftClass: 'btn-2-watch left',
            leftBtnText: '限免围观',
            rightClass: 'btn-2-dis',
            rightBtnText: '共读人数已满'
          })
        }
        break
      case 6:
        {
          this.setState({
            isBtnShow: true,
            leftClass: 'btn-2-watch left',
            leftBtnText: `${
              shareRead.watchMoney
                ? shareRead.watchMoney / 100 + priceUnit
                : '限免'
            }围观`,
            rightClass: 'btn-2 strong',
            rightBtnText: `${shareRead.joinMoney / 100}${
              priceUnit
            }参加共读`
          })
        }
        break
      case 7:
        {
          this.setState({
            isBtnShow: true,
            leftClass: 'btn-2-watch left',
            leftBtnText: `${
              shareRead.watchMoney
                ? shareRead.watchMoney / 100 + priceUnit
                : '限免'
            }围观`,
            rightClass: 'btn-2-dis',
            rightBtnText: '共读人数已满'
          })
        }
        break
      case 8:
        {
          this.setState({
            isBtnShow: false,
            leftClass: 'btn-1',
            leftBtnText: '申请加入'
          })
        }
        break
      case 9:
        {
          this.setState({
            isBtnShow: false,
            leftClass: 'btn-1 strong',
            leftBtnText: `${shareRead.joinMoney / 100}${
              priceUnit
            }立即加入`
          })
        }
        break
      case 10:
        {
          this.setState({
            isBtnShow: false,
            leftClass: 'btn-1',
            leftBtnText: '申请加入'
          })
        }
        break
      case 13:
      case 11:
      case 15:
      case 16:
        {
          this.setState({
            isBtnShow: false,
            leftClass: 'btn-1',
            leftBtnText: '去看看'
          })
        }
        break
      case 12:
        {
          this.setState({
            isBtnShow: false,
            leftClass: 'btn-1-dis',
            leftBtnText: '已申请，等待审核中...'
          })
        }
        break
      case 14:
        {
          this.setState({
            isBtnShow: false,
            leftClass: 'btn-1-dis',
            leftBtnText: '共读人数已满'
          })
        }
        break
    }
  }

  public async getShareReadData(shareReadId: number) {
    let res = await jsonp('https://du.163.com/api/shareRead.jsonp', {
      shareReadId,
      effective: false
    })
    if(res.code === 0) {
      let value = res.shareReadWrapper
      let shareRead = value.shareRead
      let status: number = 1
      this.setState({
        shareRead,
        shareReadData: value
      })
      if (value.currentUserStatus === 1) {
        status = 12 // 已申请
      } else if (value.currentUserStatus === 0) {
        status = value.currentStatus === 1 ? 16 : 13 //在共读中
      } else if (value.currentUserStatus === 2) {
        status = value.currentStatus === 1 ? 15 : 11 //在围观中
      } else if (value.currentStatus === 0 || value.currentStatus === -1) {
        switch (shareRead.auditType) {
          case 0:
            {
              // 公开
              status = shareRead.canWatch
                ? shareRead.needPay
                  ? shareRead.readerLimit <=
                    shareRead.readerUserIds.split(',').length
                    ? 7 // 付费+人满+围
                    : 6 // 付费+人未满+围
                  : shareRead.readerLimit <=
                    shareRead.readerUserIds.split(',').length
                  ? 5 // 免费+人满+围
                  : 4 // 免费+人未满+围
                : shareRead.readerLimit <=
                  shareRead.readerUserIds.split(',').length
                ? 3 // 人满+不围
                : shareRead.needPay
                ? 2 // 付费+不围
                : 1 // 免费+不围
            }
            break
          case 1:
            {
              // 需审核
              shareRead.readerLimit <=
              shareRead.readerUserIds.split(',').length
                ? (status = 14) // 人满
                : (status = 10) // 需审核
            }
            break
          case 2:
            {
              // 私密
              status =
                shareRead.readerLimit <=
                shareRead.readerUserIds.split(',').length
                  ? 14 // 人满
                  : shareRead.needPay
                  ? 9 // 付费+私密
                  : 8 // 免费+私密
            }
            break
        }
      } else {
        status =
          value.currentUserStatus === 2
            ? 15 // 结束后围观
            : shareRead.canWatch
            ? shareRead.watchMoney
              ? -1
              : -2
            : -4
      }
      this.setState({
        status
      }, () => {
        this.updateStatus(status)
      })
    }
  }

  public goShareReadHandle(){
    const { id, isEdit } = this.props
    if(!isEdit) {
      const log = getLogInstance();
      log.sendLog('acttemplate1-14', {
        category: 'acttemplate',
        pos: id,
        id
      });
      setTimeout(() => {
        location.href = `https://du.163.com/static/common/shareRead/index.html?shareReadId=${id}`
      }, 300)
    } else {
      location.href = `https://du.163.com/static/common/shareRead/index.html?shareReadId=${id}`
    }
  }

  public render() {
    // console.log('this.props', this.props);
    const { title, userDesc, bookDesc, shareReadData: propShareReadData } = this.props;
    const { leftClass, leftBtnText, rightBtnText, rightClass, isBtnShow, shareReadData: stateShareReadData } = this.state
    const shareReadData = stateShareReadData || propShareReadData;
    // console.log('shareReadData', shareReadData);
    return <Container>
      <div className="header">
        {
          <div className="title">{title ? title : shareReadData.shareRead.title}</div>
        }
      </div> 
      {
        shareReadData ? <div className="share-read" onClick={this.goShareReadHandle.bind(this)}>
          <div className="content">
            <div className="words">
              <div className="user">
                <img className="avatar" src={formatAvatar(shareReadData.shareReadCreator.user.imageUrl)} alt="avatar"/>
                <div className="info">
                  <div className="nickName">{shareReadData.shareReadCreator.user.nickName}</div>
                  <div className="desc">{
                    userDesc 
                    || shareReadData.shareReadCreator.userIdentity.title
                    || shareReadData.shareReadCreator.user.introduction
                  }</div>
                </div>
              </div>
              <div className="book">
                <div className="intro">
                  <div className="book-title">{shareReadData.bookWrapper.book.title}</div>
                  <div className="desc">{bookDesc || shareReadData.shareRead.description || shareReadData.bookWrapper.book.description}</div>
                </div>
              </div>
            </div>
            <img className="book-cover" src={shareReadData.bookWrapper.book.imageUrl} alt=""/>
          </div>
          {
            shareReadData.shareRead.images ? (
              <div className="img-list">
                {
                  shareReadData.shareRead.images.map(url => {
                    return <img className="preview-img" src={`${url}?imageView&thumbnail=400y400`} alt="preview"/>
                  })
                }
              </div>
            ) : null
          }
          <div className="action">
            <div className={leftClass}>{leftBtnText}</div>
            {
              isBtnShow ? <div className={rightClass}>{rightBtnText}</div> : null
            }
          </div>
        </div> : null
      }
    </Container>
  }
}