import * as React from 'react'

import {
  formatNumber,
  padding
} from '../utils/format';
import { TemplateActivityContext } from '../common/template-context';
import { goToLogin } from '../utils/login'

import * as Styled from './index.style'
import {
  Props,
  State
} from './type'
import {
  fetchRank,
  postDunToRankItem,
  RankItem
} from './actions';


const SHOWING_ITEM_MIN_COUNT = 5;

const MOCK_RANK_ITEMS = [
  {
      "score": 19,
      "blogInfo": {
          "blogNickName": "我是一个演示数据",
          "bigAvaImg": "https://avaimg.lf127.net/img/739342e8ee7d77ed/aUNBazBSVlNSc1h6TmIyRHNybFdZdVJvOXpPbnJiaVJ5OVZHc21yRDJlYz0.jpg",
          "blogId": 529047591,
          "blogName": "pan22012",
          "selfIntro": "",
          "imageProtected": false
      },
      "buttonAct": 0,
      "dun": 0
  },
  {
      "score": 18,
      "blogInfo": {
          "blogNickName": "我是一个演示数据",
          "bigAvaImg": "https://avaimg.lf127.net/img/MTZIUnRCd0dETFcyZ1U4L3BuRVFRYlJkR1EwOGZUNzV4ejJJeFhUZzlvc3FjSTBXZmUzSzZ3PT0.jpg",
          "blogId": 1286330644,
          "blogName": "flz002",
          "selfIntro": "",
          "imageProtected": false
      },
      "buttonAct": 0,
      "dun": 0
  },
  {
      "score": 11,
      "blogInfo": {
          "blogNickName": "我是一个演示数据",
          "bigAvaImg": "https://avaimg.lf127.net/img/98814176f56195d6/TWR3ejFUazF0OGZ2K0txWU5RUFhkVVEwblhNS3B4eEpFa3pNQndSRkxsMD0.jpg",
          "blogId": 496674184,
          "blogName": "qatest002",
          "selfIntro": "",
          "imageProtected": false
      },
      "buttonAct": 0,
      "dun": 0
  },
  {
      "score": 10,
      "blogInfo": {
          "blogNickName": "我是一个演示数据",
          "bigAvaImg": "https://avaimg.lf127.net/img/4733ef579c36b4b6/ZURaNmU4eEF2NWEyZlFnOVpuWjJjOFR1VFVwaWQzOHhQMExBaU0vVzloTT0.jpg",
          "blogId": 542262100,
          "blogName": "11111111112222222222333333333344444444445555555555",
          "selfIntro": "",
          "imageProtected": false
      },
      "buttonAct": 0,
      "dun": 0
  },
  {
      "score": 10,
      "blogInfo": {
          "blogNickName": "我是一个演示数据",
          "bigAvaImg": "https://avaimg.lf127.net/img/ce786004eba5a003/NzJoNSthVzlMK2p4b1U3VitvRGg5bDhnRmIrNHN2SHM4R2RZOWlYMkIyZz0.jpg",
          "blogId": 508150100,
          "blogName": "gggg6368",
          "selfIntro": "",
          "imageProtected": true
      },
      "buttonAct": 0,
      "dun": 0
  }
];


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

  state = new State()

  static contextType = TemplateActivityContext

  context: React.ContextType<typeof TemplateActivityContext> = null;

  expendMax = 10;

  activityId: string | null = null;

  componentDidUpdate (prevProps: Props) {
    if (
      (
        this.context
        && this.context.activityInfo
        && this.activityId !== this.context.activityInfo.actEventInfo.activityId
      ) || prevProps.rankId !== this.props.rankId
    ) {
      this.refresh();
    }
  }

  componentDidMount() {
    this.refresh();
  }

  public render() {
    const {
      isEdit,
      style: oriStyle,
      rankHeader,
    } = this.props
    let {
      expand,
      rankItemList
    } = this.state;
    const style = { ...oriStyle };
    let mocking = false;

    if (isEdit && rankItemList.length < SHOWING_ITEM_MIN_COUNT) {
      mocking = true;
      rankItemList = MOCK_RANK_ITEMS as any;
    }

    const withButton = rankItemList[0] && rankItemList[0].buttonAct === 1;
    const shouldShowExpend = rankItemList.length > this.expendMax;
    const showingRankItemList = !expand ? rankItemList.slice(0, this.expendMax) : rankItemList;

    return (
      <div style={style}>
        {
          mocking && (
            <Styled.MockingBox>
              当前数据为演示数据
            </Styled.MockingBox>
          )
        }
        {
          !this.context && isEdit
            ? (
              <Styled.EmptyContainer>
                请添加该组件至 [模板活动-容器]中
              </Styled.EmptyContainer>
            )
            : (
              showingRankItemList.length < SHOWING_ITEM_MIN_COUNT ? (
                <Styled.EmptyContainer>
                  榜单正在计算中
                </Styled.EmptyContainer>
              ) : (
                <div>
                  {
                    !withButton
                    && (
                      <Styled.RankItemHeader
                        textColor={rankHeader.textColor || '#4DECE3'}
                      >
                        <Styled.RankItemHeaderTop>{rankHeader.topText}</Styled.RankItemHeaderTop>
                        <Styled.RankItemHeaderContent>{rankHeader.contentText}</Styled.RankItemHeaderContent>
                        <Styled.RankItemHeaderScore>{rankHeader.scoreText}</Styled.RankItemHeaderScore>
                      </Styled.RankItemHeader>
                    )
                  }
                  {showingRankItemList.map((rankItem, index) => {
                    const blogUrl = `https://${rankItem.blogInfo.blogName}.lofter.com`;
                    return (
                      <Styled.RankItem
                        key={rankItem.blogInfo.blogId}
                        className={withButton ? 'with-button' : ''}
                      >
                        <Styled.RankItemTop>
                          <svg
                            className="rank-item-icon"
                            width="51" height="23" viewBox="0 0 51 23" fill="none" xmlns="http://www.w3.org/2000/svg">
                            <path d="M16.0109 0.803759H1.54263L0.85792 4.28685H6.18675L2.64412 22H6.57376L10.1164 4.28685H15.3261L16.0109 0.803759ZM31.588 6.63868C31.588 3.36398 29.2064 0.625138 25.1875 0.625138C23.1333 0.625138 20.8708 1.4587 19.293 3.03651C17.4175 4.91202 16.8519 7.32339 16.0481 11.4019C15.6015 13.7835 15.3931 15.2124 15.3931 16.1651C15.3931 19.4398 17.745 22.1786 21.7639 22.1786C23.818 22.1786 26.1103 21.3451 27.6881 19.7672C29.5636 17.8917 30.1293 15.4804 30.9331 11.4019C31.3796 9.02028 31.588 7.59132 31.588 6.63868ZM27.5988 6.93638C27.5988 7.97833 27.3607 9.58591 27.0034 11.4019C26.2294 15.3315 25.7531 16.5819 24.9493 17.4452C24.205 18.249 23.1929 18.7253 22.0616 18.7253C20.6326 18.7253 19.3525 17.7429 19.3525 15.8674C19.3525 14.8254 19.6205 13.2178 19.9777 11.4019C20.7517 7.47224 21.228 6.2219 22.0318 5.35857C22.7761 4.55478 23.7883 4.07846 24.9195 4.07846C26.3485 4.07846 27.5988 5.06087 27.5988 6.93638ZM50.3231 6.40052C50.3231 3.09605 48.2392 0.803759 44.637 0.803759H37.1052L32.8481 22H36.7777L38.4151 13.7835H42.4936C47.5843 13.7835 50.3231 10.1813 50.3231 6.40052ZM46.3637 6.72799C46.3637 8.33557 45.2027 10.3004 42.6424 10.3004H39.1296L40.3501 4.28685H43.9821C45.7385 4.28685 46.3637 5.38834 46.3637 6.72799Z" fill="#A7A7A7"/>
                          </svg>
                          <span>
                            {padding(index + 1)}
                          </span>
                        </Styled.RankItemTop>
                        <Styled.RankItemAvatar
                          href={blogUrl}
                          className={withButton ? 'with-button' : ''}
                        >
                          <img src={rankItem.blogInfo.bigAvaImg} />
                        </Styled.RankItemAvatar>
                        {
                          withButton ? (
                            <Styled.RankItemContentBox>
                              <Styled.RankItemNickName>
                                <a href={blogUrl}>
                                  {rankItem.blogInfo.blogNickName}
                                </a>
                              </Styled.RankItemNickName>
                              <Styled.RankItemScore>
                                {formatNumber(rankItem.score)}
                                &nbsp;{rankHeader.scoreText}
                              </Styled.RankItemScore>
                            </Styled.RankItemContentBox>
                          ) : (
                            <>
                              <Styled.RankItemNickName>
                                <a href={blogUrl}>
                                  {rankItem.blogInfo.blogNickName}
                                </a>
                              </Styled.RankItemNickName>
                              <Styled.RankItemScoreColumn>
                                {formatNumber(rankItem.score)}
                              </Styled.RankItemScoreColumn>
                            </>
                          )
                        }
                        {
                          withButton && (
                            rankItem.dun === 0 ? (
                              <Styled.RankItemButton
                                onClick={() => {
                                  this.postDunToRankItem(rankItem)
                                }}
                              >
                                我蹲
                              </Styled.RankItemButton>
                            ) : (
                              <Styled.RankItemButton>
                                已蹲
                              </Styled.RankItemButton>
                            )
                          )
                        }
                      </Styled.RankItem>
                    )
                })}
                {
                  shouldShowExpend && (
                    !expand ? (
                      <Styled.ExpendMore
                        onClick={() => {
                          this.setState({
                            expand: true
                          })
                        }}
                      >
                        <span>加载更多</span>
                        <svg width="32" height="23" viewBox="0 0 32 23" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M31 2L16.5 11L2 2" stroke="#4DECE3" strokeWidth="3" strokeLinecap="round" stroke-linejoin="round"/>
                        <path d="M31.5 11.5L17 21.5L2.5 11.5" stroke="#4DECE3" strokeWidth="3" strokeLinecap="round" stroke-linejoin="round"/>
                        </svg>
                      </Styled.ExpendMore>
                    ) : (
                      <Styled.HideMore
                        onClick={() => {
                          this.setState({
                            expand: false
                          })
                        }}
                      >
                        <span>收起</span>
                        <svg width="32" height="23" viewBox="0 0 32 23" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M31 2L16.5 11L2 2" stroke="#4DECE3" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/>
                        <path d="M31.5 11.5L17 21.5L2.5 11.5" stroke="#4DECE3" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/>
                        </svg>
                      </Styled.HideMore>
                    )
                  )
                }
              </div>
            )
          )
        }
      </div>
    )
  }

  async postDunToRankItem (
    rankItem: RankItem
  ) {
    if (!this.activityId || !this.props.rankId) {
      return;
    }

    if (!this.context?.activityInfo?.hasLogin) {
      goToLogin(this.context?.getActivityInfo)
      return;
    }

    await postDunToRankItem(
      this.props.rankId,
      this.activityId,
      rankItem.blogInfo.blogId
    )
    this.refresh();
  }


  async refresh () {
    this.activityId = (
      this.context
      && this.context.activityInfo
      && this.context.activityInfo.actEventInfo.activityId
    );

    if (!this.activityId || !this.props.rankId) {
      return;
    }

    const { itemList } = await fetchRank(
      this.props.rankId,
      this.activityId
    )

    this.setState({
      rankItemList: itemList
    })
  }
}

