import React, { useRef, useState } from 'react'
import useRequest from '@ahooksjs/use-request/es'

import { Spin, Timeline, Result } from 'antd'

import { useLogin2p } from 'Login2p/Login2pContext'
import { WebNoAuthentication } from 'components/Empty'
import { IndepthService, ITimelineItem } from './Indepth.service'
import { MicroRoadshowService } from 'Material/MicroRoadshow.service'
import IndepthLayout from './components/IndepthLayout'
import TextEllipsis from './components/TextEllipsis'
import AudioFix from 'Activity/components/AudioFix'
import { IAudioDetail } from 'Activity/Activity.service'
import styles from './css/IndepthIndex.module.scss'

type IIndepthVideoProps = {
  permissionID: number // 行业ID
  industryID: number // 产业ID
  videoID: number // 视频ID
}
/**视频页*/
const IndepthVideo: React.FC<IIndepthVideoProps> = props => {
  const { permissionID, industryID, videoID } = props
  const login2p = useLogin2p()
  const videoRef = useRef<HTMLVideoElement>(null)
  const [audioVisible, setAudioVisible] = useState<boolean>(false)
  const [audioItem, setAudioItem] = useState<IAudioDetail>()

  // 拉取时间线
  const { data: timelineData, loading: timelineLoading } = useRequest(IndepthService.getTimeline, {
    defaultParams: [industryID, 1, 9999],
    formatResult: response => response.data.Data
  })
  // 视频详情
  const { data: videoData, loading: videoLoading } = useRequest(MicroRoadshowService.getVideoInfo, {
    defaultParams: [videoID],
    formatResult: response => response.data.Data
  })
  // 视频播放记录
  const { run: applyVideoHistory } = useRequest(MicroRoadshowService.postVideoHistory, {
    manual: true
  })

  const subTitle = () => {
    if (videoData?.AuthInfo.HasPermission === 1) return
    return (
      <div>
        <p>若想查看可以联系对口销售</p>
        {/* <p>
          {videoData?.AuthInfo.SellerName}:{videoData?.AuthInfo.SellerMobile}
        </p> */}
        <p>申请开通对应的试用权限</p>
      </div>
    )
  }
  const handleToOtherPage = (item: ITimelineItem) => {
    // 1:文章、2:  产品内测、3: 晨报点评 4:  活动回放、5：音频
    if (item.Resource === 5) {
      // 音频直接播放
      setAudioItem({
        ActivityId: item.ArticleId,
        Name: item.Title,
        Url: item.VoiceUrl,
        Type: item.Type,
        SourceId: item.Id
      })
      setAudioVisible(true)
      return
    }
    const urlFn: {
      [key: number]: string
    } = {
      1: `${window.location.origin}/material/info/${item.ArticleId}`,
      2: `${window.location.origin}/internal/article/${item.ArticleId}`,
      3: '',
      4: `${window.location.origin}/activity/video/${item.Id}`,
      5: ''
    }
    const url = urlFn[item.Resource]

    if (!url) return
    window.open(url)
  }
  const handleToLinkPage = (item: ITimelineItem) => {
    const url = `${window.location.origin}/material/info/${item.LinkArticleId}`
    !!item.LinkArticleId && window.open(url)
  }
  // 关闭音频
  const handleCloseAudio = () => {
    setAudioVisible(false)
    setAudioItem(undefined)
  }
  const handleOnplay = () => {
    videoRef.current &&
      parseInt(videoRef.current.currentTime.toString()) === 0 &&
      videoData &&
      applyVideoHistory(
        videoData?.IndustryVideo.ActivityId || videoData?.IndustryVideo.Id,
        videoData?.IndustryVideo.Type
      )
  }
  return (
    <IndepthLayout permissionID={permissionID}>
      <AudioFix audioDetail={audioItem as IAudioDetail} visible={audioVisible} onClose={handleCloseAudio} />
      {login2p.jwt ? (
        <div className={`page-max-width padding-t-md`}>
          <div className={styles['video-title']}>{videoData?.IndustryVideo?.Title}</div>
          <Spin spinning={timelineLoading || videoLoading}>
            <div className={styles['video-wrapper']}>
              <div className="v-content">
                <div className={`${styles['gray-bg']} v-wrap`}>
                  {videoData && videoData?.AuthInfo?.HasPermission === 1 ? (
                    <video
                      ref={videoRef}
                      src={videoData?.IndustryVideo.ResourceUrl}
                      className={styles['video-content']}
                      controls={true}
                      controlsList="nodownload"
                      autoPlay={true}
                      loop={true}
                      preload="auto"
                      onContextMenu={e => {
                        e.preventDefault()
                        return false
                      }}
                      onPlay={handleOnplay}
                    >
                      <p> 当前浏览器不支持video标签 </p>
                    </video>
                  ) : (
                    <Result
                      status="403"
                      title="您暂无权限查看此视频~"
                      subTitle={subTitle()}
                      style={{ margin: '5% auto' }}
                    />
                  )}
                </div>
                <div className={` ${styles['timeline-wrapper']} v-time-line`}>
                  <div className={`time-line-title ${styles['bt-line']}`}>时间线</div>
                  <Timeline
                    className="timeline-one"
                    items={
                      timelineData?.List?.map((item, index) => {
                        return {
                          color: 'grey',
                          children: (
                            <>
                              <div className="timeline-time">{item.PublishDate}</div>
                              <div>
                                <TextEllipsis
                                  key={index}
                                  content={
                                    <div>
                                      {item.Resource === 3 ? (
                                        <>
                                          <div className="blue-link">
                                            {!!item.LinkArticleId && (
                                              <span className="m-r-sm" onClick={handleToLinkPage.bind(this, item)}>
                                                {item.Title}
                                              </span>
                                            )}
                                            {item?.ListSubject?.map(itemSubject => (
                                              <span className="m-r-sm not-link" key={itemSubject.IndustrialSubjectId}>
                                                #{itemSubject.SubjectName}
                                              </span>
                                            ))}
                                          </div>
                                          <div
                                            dangerouslySetInnerHTML={{
                                              __html: item.Content.replace(/\n/g, '<br/>')
                                            }}
                                            className={`g-inline-block timeline-reset `}
                                          />
                                        </>
                                      ) : (
                                        <div
                                          dangerouslySetInnerHTML={{
                                            __html: item.Title.replace(/\n/g, '<br/>')
                                          }}
                                          className={`g-inline-block timeline-reset blue-link `}
                                          onClick={handleToOtherPage.bind(this, item)}
                                        />
                                      )}
                                    </div>
                                  }
                                  showTipsText={true}
                                  lineNumber={3}
                                />
                              </div>
                            </>
                          )
                        }
                      }) || []
                    }
                  />
                </div>
              </div>
            </div>
          </Spin>
        </div>
      ) : (
        <WebNoAuthentication />
      )}
    </IndepthLayout>
  )
}

export default IndepthVideo
