import * as React from 'react'
import * as Styled from './index.style'

import {
  Props,
  State
} from './type'
import {
  formatNumber
} from '../utils/format';
import { TemplateActivityContext } from '../common/template-context'
import { goToLogin } from '../utils/login';
import {
  fetchProcess,
  postDunToProcess
} from './actions'
import {
  Announcement
} from './announcement';

const MOCK_ITEMS = [
  {
      "time": 1658303922923,
      "blogInfo": {
          "blogNickName": "我是一个演示数据",
          "bigAvaImg": "https://avaimg.lf127.net/img/76ea61b0bb16e6d3/b1dMQ0t6SzQzNEpQSXM1UDBEaSs0bVFmVTh5T1YxWkpXK0l1VUs1YXFOUT0.jpg",
          "blogId": 1286320395,
          "blogName": "flz0031",
          "selfIntro": "",
          "imageProtected": false
      },
      "type": 2
  },
  {
      "time": 1658303098970,
      "blogInfo": {
          "blogNickName": "我是一个演示数据",
          "bigAvaImg": "https://avaimg.lf127.net/img/739342e8ee7d77ed/aUNBazBSVlNSc1h6TmIyRHNybFdZdVJvOXpPbnJiaVJ5OVZHc21yRDJlYz0.jpg",
          "blogId": 529047591,
          "blogName": "pan22012",
          "selfIntro": "",
          "imageProtected": false
      },
      "type": 2
  },
  {
      "time": 1658299979991,
      "blogInfo": {
          "blogNickName": "我是一个演示数据",
          "bigAvaImg": "https://avaimg.lf127.net/img/76ea61b0bb16e6d3/b1dMQ0t6SzQzNEpQSXM1UDBEaSs0bVFmVTh5T1YxWkpXK0l1VUs1YXFOUT0.jpg",
          "blogId": 1286320395,
          "blogName": "flz0031",
          "selfIntro": "",
          "imageProtected": false
      },
      "type": 2
  }
]

const TypeMessage = new Map([
  [0, '发文助力成功~'],
  [1, '刚刚蹲在了评论区 助力成功～'],
  [2, '支持助力成功~']
])

export class TemplateActivityProcess extends React.Component<
  Props,
  State,
  React.ContextType<typeof TemplateActivityContext>
> {
  static defaultProps = new Props()

  state = new State()

  static contextType = TemplateActivityContext

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


  activityId: string | null = null;

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

  componentDidMount() {
    this.refresh();
  }

  public render() {
    const {
      isEdit,
      style: oriStyle,
      process,
      supportButton
    } = this.props;
    const {
      processBarData
    } = this.state;
    const style = { ...oriStyle };

    let percent = 0;
    if (processBarData) {
      percent = Math.min(100, 100 * processBarData.processBar.currentCount/processBarData.processBar.targetCount);
    }

    let itemList = (processBarData && processBarData.itemList) || []
    let mocking = false;
    if (isEdit && itemList.length === 0) {
      mocking = true;
      itemList = MOCK_ITEMS as any;
    }

    return (
      <div style={style}>
        {
          mocking && (
            <Styled.MockingBox>
              当前数据为演示数据
            </Styled.MockingBox>
          )
        }
        <Styled.Box>
          <Styled.ProcessTitleBox>
            当前进度&nbsp;
            <strong>
              {processBarData
                ? Math.min(processBarData.processBar.targetCount, processBarData.processBar.currentCount)
                : '--'
              }
            </strong>
            <span>
              &nbsp;/&nbsp;
              {processBarData
                ? formatNumber(processBarData.processBar.targetCount)
                : '--'
              }
            </span>
          </Styled.ProcessTitleBox>
          <Styled.ProcessBox>
            <Styled.ProcessBarBox>
              <Styled.ProcessBarBg
                percent={percent}
                image={process.barImage && process.barImage.url}
                color={process.barColor}
              >
              </Styled.ProcessBarBg>
              {
                percent !== 100 && (
                  <Styled.ProcessBarIcon
                    percent={percent}
                    image={process.barIcon && process.barIcon.url}
                  />
                )
              }
            </Styled.ProcessBarBox>
            <Styled.ProcessBarFlagImage
              image={
                percent === 100
                  ? (process.flagCompleteImage && process.flagCompleteImage.url)
                  : ( process.flagImage && process.flagImage.url)
              }
            />
          </Styled.ProcessBox>
          {
            processBarData && processBarData.processBar.buttonAct !== 0 && (
              <Styled.SupportButton
                className={processBarData.dun ? 'disabled' : ''}
                enableImage={supportButton.enableImage && supportButton.enableImage.url}
                disableImage={supportButton.disableImage && supportButton.disableImage.url}
                onClick={async () => {
                  if (!processBarData.dun) {
                    if (processBarData.processBar.type === 1) {
                      if (!this.context?.activityInfo?.hasLogin) {
                        goToLogin(this.context?.getActivityInfo)
                        return;
                      }

                      await postDunToProcess(
                        this.props.processId,
                        this.activityId,
                        processBarData.processBar.target
                      )
                      this.refresh();
                    } else {
                      window.location.href = `https://www.lofter.com/tag/${encodeURIComponent(processBarData.processBar.target)}`
                    }
                  }
                }}
              />
            )
          }
          {
            processBarData && itemList.length > 0
            && (
              <Styled.AnnouncementBox>
                <Announcement
                  announcements={
                    itemList.map(({ blogInfo }) => (
                      <Styled.AnnouncementItem>
                        <Styled.AnnouncementItemAvatar
                          src={blogInfo.bigAvaImg}
                        />
                        <Styled.AnnouncementItemText>
                          <span>{blogInfo.blogNickName}</span>
                          <strong>{TypeMessage.get(processBarData.processBar.type)}</strong>
                        </Styled.AnnouncementItemText>
                      </Styled.AnnouncementItem>
                    ))
                  }
                />
              </Styled.AnnouncementBox>
            )
          }
        </Styled.Box>
      </div>
    )
  }

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

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

    const data = await fetchProcess(
      this.props.processId,
      this.activityId
    )

    this.setState({
      processBarData: data
    })

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

