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

import { message } from 'antd'
import { EyeOutlined, StarFilled, StarOutlined } from '@ant-design/icons'

import { default as PeopleSvg } from 'assets/people.svg'
import { default as RecommendSvg } from 'assets/recommend.svg'

import { IBillBoardItem, IIndepthArticleItem, IListHzReportItem, ISearchReportItem } from 'Indepth/Indepth.service'
import CategoryTag from './CategoryTag'
import { ICommunityArticleList } from 'Community/Community.service'
import { ColumnService } from 'Column/Column.service'
import { IHomeArticleListItem, MaterialService } from 'Material/Material.service'
import { IMyCollectionItem } from 'Personal/Personal.service'
import classNames from 'classnames'
import { useLogin2p } from 'Login2p/Login2pContext'
import styles from '../css/ArticleCard.module.scss'

interface IArticleCardProps {
  articleItem:
    | IHomeArticleListItem
    | ISearchReportItem
    | IListHzReportItem
    | IBillBoardItem
    | ICommunityArticleList
    | IIndepthArticleItem
    | IMyCollectionItem
  className?: string
  rankIndex?: number // 含有排行的传
  showType?: boolean // 展示标签
  afterShow?: 'industry' | 'subject' // 标题后面跟的是产业还是标的
  jumpType?: 'industry' | 'theme' // 标题后面跳转类型
  sizeType?: 'smcard' | 'lgcard'
  onCollect?: (articleID: number, item?: any) => void
}
/**报告列表卡片 */
const ArticleCard: React.FC<IArticleCardProps> = props => {
  const {
    articleItem,
    className,
    rankIndex,
    showType = false,
    afterShow = 'industry',
    jumpType = 'industry',
    sizeType = 'lgcard',
    onCollect
  } = props
  const history = useHistory()
  const login2p = useLogin2p()

  // 收藏/取消收藏（报告）
  const { run: applyCollect } = useRequest(MaterialService.postActicleCollect, {
    manual: true,
    onSuccess: res => {
      message.info(res.data.Msg)
      res.data.Success && onCollect && onCollect(articleItem.ArticleId, articleItem)
    }
  })
  // 收藏/取消收藏（研选专栏）
  const { run: applyCollectColumn } = useRequest(ColumnService.postColumnCollect, {
    manual: true,
    onSuccess: res => {
      message.info(res.data.Msg)
      res.data.Success && onCollect && onCollect(articleItem.ArticleId, articleItem)
    }
  })

  const handleToOther = (ID: number, ChartPermissionId: number) => {
    if (jumpType === 'industry') {
      history.push(
        `/indepth/info/${ChartPermissionId}/${ID}${login2p.inviteCode ? '?invite_code=' + login2p.inviteCode : ''}`
      )
    }
    if (jumpType === 'theme') {
      history.push(`/community/theme/${ID}${login2p.inviteCode ? '?invite_code=' + login2p.inviteCode : ''}`)
    }
  }
  const iRankClass = classNames(
    'i-rank',
    { 'i-rank-first': rankIndex === 1 },
    { 'i-rank-sec': rankIndex === 2 },
    { 'i-rank-thr': rankIndex === 3 }
  )
  const handleCollection = (ID: number) => {
    if ((articleItem as IMyCollectionItem)?.IsSpecial) {
      applyCollectColumn(ID, (articleItem as IMyCollectionItem)?.IsCollect ? 2 : 1)
      return
    }
    applyCollect(ID)
  }
  // 进入作者详情页
  const handleToAuthorInfo = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
    e.stopPropagation()
    if ((articleItem as ICommunityArticleList)?.IsSpecial) {
      // 进入专栏详情页
      history.push(
        `/column/view/${(articleItem as ICommunityArticleList).SpecialColumnId}${
          login2p.inviteCode ? '?invite_code=' + login2p.inviteCode : ''
        }`
      )
      return
    }
    // 主题作者详情页
    history.push(
      `/community/author/${(articleItem as ICommunityArticleList).DepartmentId}${
        login2p.inviteCode ? '?invite_code=' + login2p.inviteCode : ''
      }`
    )
  }
  const handleClickBlock = () => {
    // 笔记/观点详情页
    if ((articleItem as ICommunityArticleList).IsSpecial) {
      window.open(`${window.location.origin}/column/detail/${articleItem.ArticleId}`)
      return
    }
    // Resource 1报告 2产品内测
    const urlResource: {
      [key: number]: string
    } = {
      1: `${window.location.origin}/material/info/${articleItem.ArticleId}`,
      2: `${window.location.origin}/internal/article/${articleItem.ArticleId}`
      // 3: `${window.location.origin}/indepth/info/${item.ChartPermissionId}/${item.IndustrialManagementId}`
    }
    const url = urlResource[(articleItem as IIndepthArticleItem)?.Resource || 1]
    if (!url) return
    window.open(url)
  }
  // 如果是列表显示，隐藏img标签
  const handleHideImg = (html: string) => {
    return html.replace(/<img[^>]*>/gi, '')
  }

  return (
    <div className={`${styles['article-card-wrapper']} ${className || ''}`}>
      {sizeType === 'lgcard' && (
        <img
          src={articleItem?.ImgUrlPc || ''}
          alt="图片"
          className="card-img com-cursor-p"
          onClick={handleClickBlock}
        />
      )}
      <div className="card-content">
        <div>
          <span className="card-title-wrapper">
            <span className="card-title">
              {rankIndex && <span className={iRankClass}>{rankIndex}</span>}
              {(articleItem as IHomeArticleListItem)?.IsRed && <span className="red-point m-r-xs" />}
              {(articleItem as ICommunityArticleList).TopTime > 0 && (
                <img src={RecommendSvg} alt="icon" className="article-recommend-icon" />
              )}
              {(articleItem as IBillBoardItem)?.LabelKeywordImgLink && (
                <img src={(articleItem as IBillBoardItem)?.LabelKeywordImgLink} alt="标签" className="mfyx-label-img" />
              )}
              {(articleItem as ICommunityArticleList).ArticleTypeName && (
                <span
                  className={`card-tag com-fz12 ${
                    (articleItem as ICommunityArticleList).ArticleTypeName.length > 2 ? 'card-name-space' : ''
                  }`}
                >
                  {(articleItem as ICommunityArticleList).ArticleTypeName}
                </span>
              )}
              <span className="card-title-span com-cursor-p" onClick={handleClickBlock}>
                {articleItem.Title}
              </span>
            </span>
          </span>
          {afterShow === 'industry' && (
            <>
              {(articleItem as ISearchReportItem)?.List?.map(item => (
                <span
                  key={item.IndustrialManagementId}
                  className="card-label card-label-click"
                  onClick={handleToOther.bind(this, item.IndustrialManagementId, item.ChartPermissionId)}
                >
                  #{item.IndustryName}
                </span>
              ))}
            </>
          )}
          {afterShow === 'subject' && (
            <>
              {(articleItem as ICommunityArticleList)?.ListSubject?.map(item => (
                <span key={item.IndustrialSubjectId} className="card-label card-unclick-text">
                  #{item.SubjectName}
                </span>
              ))}
            </>
          )}
          {(articleItem as ICommunityArticleList)?.IsSpecial
            ? (articleItem as ICommunityArticleList)?.IndustryTags?.map(item => (
                <span key={item} className="card-label card-unclick-text">
                  #{item}
                </span>
              ))
            : null}
          {(articleItem as ICommunityArticleList)?.IsSpecial
            ? (articleItem as ICommunityArticleList)?.CompanyTags?.map(item => (
                <span key={item} className="card-label card-unclick-text">
                  #{item}
                </span>
              ))
            : null}
        </div>
        {sizeType === 'lgcard' ? (
          <div
            className="card-annotation"
            dangerouslySetInnerHTML={{ __html: handleHideImg(articleItem?.Annotation || '') }}
          />
        ) : (
          <div className="m-b" />
        )}
        <div className="card-time">
          {(articleItem as ICommunityArticleList)?.NickName ? (
            <>
              <div className="people-wrapper" onClick={handleToAuthorInfo}>
                <img src={PeopleSvg} alt="图标" className="people-icon" />
                <span className="people-name">{(articleItem as ICommunityArticleList)?.NickName}</span>
              </div>
              <div className="g-flex g-flex-v-center">
                <span className="card-time-span">{dayjs(articleItem.PublishDate).format('YYYY-MM-DD')}</span>
                <div className="pv-look">
                  <EyeOutlined size={14} className="pv-icon footer-sm-icon" />
                  <span>{articleItem.Pv}</span>
                </div>
                {(articleItem as IIndepthArticleItem)?.Resource !== 2 && (
                  <div className="collect-cout" onClick={handleCollection.bind(this, articleItem.ArticleId)}>
                    {(articleItem as ICommunityArticleList)?.IsCollect ? (
                      <StarFilled size={14} className="collect-icon footer-sm-icon" />
                    ) : (
                      <StarOutlined size={14} className="collect-icon footer-sm-icon" />
                    )}

                    <span>{(articleItem as ICommunityArticleList)?.CollectNum}</span>
                  </div>
                )}
              </div>
            </>
          ) : (
            <>
              <div>
                <span className="card-time-span">{dayjs(articleItem.PublishDate).format('YYYY-MM-DD')}</span>
                {showType && <CategoryTag content={(articleItem as IBillBoardItem).ChartPermissionName} />}
              </div>
              <div className="g-flex g-flex-v-center">
                <div className="pv-look">
                  <EyeOutlined size={14} className="pv-icon footer-sm-icon" />
                  <span>{articleItem.Pv}</span>
                </div>
                {(articleItem as IIndepthArticleItem)?.Resource !== 2 && (
                  <div className="collect-cout" onClick={handleCollection.bind(this, articleItem.ArticleId)}>
                    {(articleItem as ICommunityArticleList)?.IsCollect ? (
                      <StarFilled size={14} className="collect-icon footer-sm-icon" />
                    ) : (
                      <StarOutlined size={14} className="collect-icon footer-sm-icon" />
                    )}

                    <span>{(articleItem as ICommunityArticleList)?.CollectNum}</span>
                  </div>
                )}
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  )
}

export default ArticleCard
