import React, { useState } from 'react'
import useRequest from '@ahooksjs/use-request/es'
import { useLocation, useHistory } from 'react-router-dom'

import { message } from 'antd'
import AudioImg from 'assets/audio-icon.svg'
import VideoReplayImg from 'assets/video-replay.svg'
import { ReactComponent as CityImg } from 'assets/city.svg'

import { useLogin2p } from 'Login2p/Login2pContext'
import { ActivityService, IActivitySpecialListItem, IActivityTypeListItem } from 'Activity/Activity.service'
import ActivityBtnComponent, { IStateStringType } from './ActivityBtn.component'
import { INewPermissionType } from 'Material/components/NoPermission'
import { INewestItem } from 'Newest/Newest.service'
import { IMyActivityItem } from 'Personal/Personal.service'
import styles from '../css/ActivityCard.module.scss'

export interface IActivityCard {
  item: IActivityTypeListItem | INewestItem | IMyActivityItem
  hasReplay?: boolean // 右边的回放
  hasBtn?: boolean // 右下角的按钮
  hasBorder?: boolean // 边框
  className?: string // 自定义样式
  selfChange?: boolean // 自身按钮状态改变
  btnOtherLine?: boolean // 按钮是否另起一行
  btnClass?: 'act-btn-sm'
  title?: string // 标红的标题
  btnGrous?: 'smcard' | 'detail' | 'bigcard' // smcard-如首页的小卡片，detail-如活动详情页，bigcard-如列表的大卡片
  onChangeSomething?: (activityId?: number) => void // 子组件变更后的操作
  onOpenVideoOrAudio?: (item: IActivityTypeListItem | INewestItem | IMyActivityItem) => void // 点击回放事件
}
const ActivityCard: React.FC<IActivityCard> = props => {
  const {
    item,
    hasReplay = false,
    hasBtn = false,
    hasBorder = false,
    className,
    selfChange = false,
    btnOtherLine = false,
    btnClass,
    title,
    btnGrous = 'bigcard',
    onChangeSomething,
    onOpenVideoOrAudio
  } = props
  const history = useHistory()
  const login2p = useLogin2p()
  const location = useLocation()

  const stateString = [
    { state: IStateStringType.Waitting, name: '未开始', className: 'waitting-div' },
    { state: IStateStringType.Going, name: '进行中', className: 'going-div' },
    { state: IStateStringType.End, name: '已结束', className: 'end-div' }
  ]
  const formatState = (state: string, type: 'name' | 'class') => {
    const findItem = stateString.find(item => item.state === state)
    return type === 'name' ? findItem?.name : findItem?.className
  }
  // 获取易懂链接
  const { run: getYidongUrl } = useRequest(ActivityService.getYidongActivityDetail, {
    manual: true,
    onSuccess: res => {
      res.data.Data?.YidongActivityUrl && window.open(res.data.Data?.YidongActivityUrl)
    }
  })
  const handleToDetail = (item: IActivityTypeListItem | IActivitySpecialListItem | INewestItem | IMyActivityItem) => {
    // 易懂活动，无权限时跳转详情页
    if (
      item?.AuthInfo?.HasPermission &&
      item?.AuthInfo?.HasPermission !== INewPermissionType.OK &&
      (item?.YidongActivityUrl || (item as IActivityTypeListItem)?.IsYidongActivity)
    ) {
      window.open(
        `${window.location.origin}/activity/detail/${
          (item as IActivityTypeListItem)?.ActivityId || (item as INewestItem)?.SourceId
        }`
      )
      // return message.error('您暂无权限参加此活动，若想参加可以申请开通对应的试用权限')
    }
    // 易懂同步过来的活动 直接跳转
    if (
      (item as IActivityTypeListItem)?.IsYidongActivity &&
      ((item as IActivityTypeListItem)?.ActivityId || (item as INewestItem)?.SourceId)
    ) {
      getYidongUrl((item as IActivityTypeListItem)?.ActivityId || (item as INewestItem)?.SourceId)
      return
    }
    if (item?.YidongActivityUrl) {
      window.open(item.YidongActivityUrl)
      return
    }
    window.open(
      `${window.location.origin}/activity/detail/${
        (item as IActivityTypeListItem)?.ActivityId || (item as INewestItem)?.SourceId
      }`
    )
  }
  const handleOpenAudio = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
    e.stopPropagation()
    // 检查是否登录了，未登录进入登录页面
    if (!login2p.jwt) {
      history.push(`/login2p?next=${encodeURIComponent(location.pathname + location.search)}`)
      return
    }
    onOpenVideoOrAudio && onOpenVideoOrAudio(item)
  }

  if (!item) return null
  return (
    <>
      {btnGrous === 'bigcard' && (
        <div
          className={`${styles['one-act-wrapper']} ${className}`}
          style={{ border: hasBorder ? '1px solid #EBEBEB' : 'none' }}
          onClick={handleToDetail.bind(this, item)}
        >
          <div className="one-act-title g-flex g-flex-between g-flex-v-center">
            <div className="g-flex g-flex-v-center ">
              {item.ActivityType === 1 ? (
                <div className="online-underline online-btn no-wrap">线上</div>
              ) : (
                <div className="online-underline underline-btn no-wrap">线下</div>
              )}
              <span>{item.ActivityTimeText}</span>
            </div>
            {hasReplay && (item as IActivityTypeListItem).AudioLink ? (
              <div className="title-right no-wrap" onClick={handleOpenAudio}>
                <img
                  src={(item as IActivityTypeListItem).FileType === 2 ? VideoReplayImg : AudioImg}
                  alt="icon"
                  className="xs-icon"
                />
                <span>回放</span>
              </div>
            ) : null}
          </div>
          <div className="one-act-content g-flex">
            <div className="content-img-wrapper">
              <div className={`t-l-flag ${formatState(item.ActiveState, 'class')}`}>
                {formatState(item.ActiveState, 'name')}
              </div>
              <img src={item.ImgUrl} alt="图片" className="act-bg-img" />
              {item.ImgUrlText && <img src={item.ImgUrlText} alt="图片" className="act-bgtext" />}
            </div>
            <div className="content-right-wrapper">
              <div className="r-title">
                {item.IsResearchPoints ? (
                  <div className="mfyx-label-normal mfyx-label-kd no-wrap">扣点</div>
                ) : item.IsExternalLabel ? (
                  <div className="mfyx-label-normal mfyx-label-wbzy no-wrap">外部资源</div>
                ) : null}
                {(item as IActivityTypeListItem)?.ActivityName || (item as INewestItem)?.Title}
              </div>
              {item.Expert ? (
                <div
                  dangerouslySetInnerHTML={{ __html: ' 专家背景：' + item.Expert }}
                  className="reset-pm g-inline-block r-des"
                />
              ) : (item as IActivityTypeListItem).Host || (item as INewestItem).Speaker ? (
                <div className="r-des">
                  主讲人：{(item as IActivityTypeListItem).Host || (item as INewestItem).Speaker}
                </div>
              ) : null}
              {item?.DistinguishedGuest && <div className="r-des">嘉宾：{item?.DistinguishedGuest}</div>}
              {item.City && (
                <div className="spec-city pos-bottom">
                  <CityImg fill="#3385FF" className="city-icon" />
                  <span>{item.City}</span>
                </div>
              )}
              {!btnOtherLine && hasBtn && (
                <div className="r-btn-wrapper" onClick={e => e.stopPropagation()}>
                  <ActivityBtnComponent
                    item={item}
                    onChangeSomething={onChangeSomething}
                    selfChange={selfChange}
                    btnClass={btnClass}
                  />
                </div>
              )}
            </div>
          </div>
          {btnOtherLine && hasBtn && (
            <div className="r-btn-wrapper" onClick={e => e.stopPropagation()}>
              <ActivityBtnComponent
                item={item}
                onChangeSomething={onChangeSomething}
                selfChange={selfChange}
                btnClass={btnClass}
              />
            </div>
          )}
        </div>
      )}
      {btnGrous === 'smcard' && (
        <div
          className={`${styles['one-act-wrapper']} ${styles['newest-activity-wrapper']} ${className ? className : ''}`}
          style={{ border: hasBorder ? '1px solid #DEE4EE' : 'none' }}
          onClick={handleToDetail.bind(this, item)}
        >
          <div className="newest-activity-title">
            <div className="r-title">
              {item.LabelKeywordImgLink && <img src={item.LabelKeywordImgLink} alt="标签" className="mfyx-label-img" />}
              {item.IsResearchPoints ? (
                <span className="mfyx-label-normal mfyx-label-kd no-wrap">扣点</span>
              ) : item.IsExternalLabel ? (
                <span className="mfyx-label-normal mfyx-label-wbzy no-wrap">外部资源</span>
              ) : null}

              <div
                className="inline-title"
                dangerouslySetInnerHTML={{
                  __html: title || (item as IActivityTypeListItem)?.ActivityName || (item as INewestItem)?.Title
                }}
              />
            </div>
          </div>
          <div className="one-act-content g-flex">
            <div className="content-img-wrapper">
              <div className={`t-l-flag ${formatState(item.ActiveState, 'class')}`}>
                {formatState(item.ActiveState, 'name')}
              </div>
              <img src={item.ImgUrl} alt="图片" className="act-bg-img" />
              {item.ImgUrlText && <img src={item.ImgUrlText} alt="图片" className="act-bgtext" />}
            </div>
            <div className="content-right-wrapper">
              <div className="g-flex g-flex-v-center m-b-sm">
                {item.ActivityType === 1 ? (
                  <div className="online-underline online-btn no-wrap">线上</div>
                ) : (
                  <div className="online-underline underline-btn no-wrap">线下</div>
                )}
                {item.City && (
                  <div className="spec-city ">
                    <CityImg fill="#faa12f" className="city-icon" />
                    <span>{item.City}</span>
                  </div>
                )}
              </div>
              <span className={item.ActiveState === IStateStringType.Going ? 'm-b-sm' : 'pos-bottom-right com-fz12'}>
                {item.ActivityTimeText}
              </span>
              {(item.Expert ||
                (item as IActivityTypeListItem).Host ||
                (item as INewestItem).Speaker ||
                item?.DistinguishedGuest) && (
                <div className="r-gray-box">
                  {item.Expert ? (
                    <div
                      dangerouslySetInnerHTML={{ __html: ' 专家背景：' + item.Expert }}
                      className="reset-pm g-inline-block r-des "
                    />
                  ) : (item as IActivityTypeListItem).Host || (item as INewestItem).Speaker ? (
                    <div className="r-des">
                      主讲人：{(item as IActivityTypeListItem).Host || (item as INewestItem).Speaker}
                    </div>
                  ) : null}
                  {item?.DistinguishedGuest && <div className="r-des">嘉宾：{item?.DistinguishedGuest}</div>}
                </div>
              )}
            </div>
          </div>
          {hasBtn && (
            <div className="r-btn-wrapper" onClick={e => e.stopPropagation()}>
              <ActivityBtnComponent
                item={item}
                onChangeSomething={onChangeSomething}
                selfChange={selfChange}
                btnClass={btnClass}
                btnGrous={btnGrous}
              />
            </div>
          )}
        </div>
      )}
    </>
  )
}

export default ActivityCard
