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

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

import videoIcon from 'assets/video-icon.svg'
import audioIcon from 'assets/audio-icon.svg'
import stopIcon from 'assets/audio_stop.png'
import audioPlay from 'assets/audio_play.png'
import videoPlay from 'assets/video-play.svg'
import { default as CommentSvg } from 'assets/comment.svg'

import { MaterialService } from 'Material/Material.service'
import { MicroRoadshowService, IRoadshowistItem } from 'Material/MicroRoadshow.service'
import AskAdd from './AskAdd'
import { INewPermissionType, ITryType } from './NoPermission'
import CategoryTag from 'Indepth/components/CategoryTag'
import styles from '../css/ItemComponent.module.scss'
export interface IVideoAudioCard {
  item: IRoadshowistItem
  audioPlayId?: number
  title?: string // 标红的标题
  onItemClick?: () => void
  onCollect?: (ID: number) => void // 收藏与取消收藏
}
export enum ILabelType {
  RoadshowReplay = 1,
  SurveyFeedback = 2,
  IndustryVideo = 3,
  QASeries = 4
}
const labelOption = [
  { key: ILabelType.RoadshowReplay, name: '路演回放' },
  { key: ILabelType.SurveyFeedback, name: '调研反馈' },
  { key: ILabelType.IndustryVideo, name: '产业视频' },
  { key: ILabelType.QASeries, name: '问答系列' }
]
/**音视频卡片组件 */
const VideoAudioCard: React.FC<IVideoAudioCard> = props => {
  const { item, audioPlayId, title, onItemClick, onCollect } = props
  const [visibleComment, setVisibleComment] = useState(false)
  const [videoItem, setVideoItem] = useState(item)
  const [commentPlaceholder, setCommentPlaceholder] = useState('可以留下您对视频内容的看法或者疑问')
  const placeholderOption = { 1: '可以留下您对音频内容的看法或者疑问', 2: '可以留下您对视频内容的看法或者疑问' }

  // 留言
  const { run: applyComment } = useRequest(MicroRoadshowService.postRoadshowComment, {
    manual: true,
    onSuccess: res => {
      res.data.Success ? message.success(res.data.Msg) : message.error(res.data.ErrMsg)
    }
  })
  // 收藏与取消收藏
  const { run: applyCollect } = useRequest(MicroRoadshowService.postRoadshowCollect, {
    manual: true,
    onSuccess: res => {
      res.data.Success ? message.success(res.data.Msg) : message.error(res.data.ErrMsg)
      if (res.data.Success) {
        onCollect && onCollect(item.Id)
        const newItem = JSON.parse(JSON.stringify(videoItem))
        newItem.IsCollect = !newItem.IsCollect
        setVideoItem(newItem)
      }
    }
  })
  const { run: applyTry } = useRequest(MaterialService.postApplyTry, {
    manual: true,
    onSuccess: res => {
      res.data.Ret === 200 ? message.success('提交成功，请等待销售人员与您联系') : message.info(res.data.Msg)
    }
  })
  // 打开留言
  const handleOpenComment = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
    e.stopPropagation()
    setVisibleComment(true)
    if (item.Type === 1) {
      setCommentPlaceholder(placeholderOption[1])
      return
    }
    setCommentPlaceholder(placeholderOption[2])
  }
  // 收藏与取消收藏
  const handleCollectOrNot = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
    // todo
    e.stopPropagation()
    applyCollect(item.SourceId || item.Id, item.Type)
  }
  // Type: number // 类型  1-音频; 2-活动视频; 3-产业视频
  // Source: string //资源类型 报告 ：article 、图表 ：newchart、微路演 ：roadshow、活动 ：activity、活动视频：activityvideo、活动音频：activityvoice、专项调研活动：activityspecial"
  const handleOkAsk = (e?: React.MouseEvent<HTMLElement, MouseEvent>) => {
    // e?.stopPropagation()
    setVisibleComment(false)
  }
  const handleApplyComment = (ID: number, content: string) => {
    applyComment(ID, item.Type, content)
    handleOkAsk()
  }

  // 标题与播放按钮的点击
  const handleToSomePage = (item: IRoadshowistItem, type: 'detail' | 'play') => {
    // e.stopPropagation()
    // 类型  1-音频-活动详情页; 2-活动视频-活动详情页; 3-产业视频-产业详情页,4-问答
    const urlType: {
      [key: number]: () => { url: string; tryType: ITryType; text: string }
    } = {
      1: () => ({
        url: type === 'detail' ? `${window.location.origin}/activity/detail/${item.ActivityId}` : '',
        tryType: ITryType.MicroAudio,
        text: '音频'
      }),
      2: () => ({
        url:
          type === 'detail'
            ? `${window.location.origin}/activity/detail/${item.ActivityId}`
            : `${window.location.origin}/activity/video/${item.Id}`,
        tryType: ITryType.ActivityVideo,
        text: '视频'
      }),

      3: () => ({
        url:
          type === 'detail'
            ? `${window.location.origin}/indepth/info/${item.ChartPermissionId}/${item.IndustrialManagementId}`
            : `${window.location.origin}/indepth/video/${item.ChartPermissionId}/${item.IndustrialManagementId}/${item.Id}`,
        tryType: ITryType.MicroVideo,
        text: '视频'
      }),
      4: () => ({
        url: '',
        tryType: ITryType.MicroAudio,
        text: '音频' // 暂时是音频
      })
    }
    if (item.AuthInfo.HasPermission !== INewPermissionType.OK) {
      let content: React.ReactNode = (
        <div>
          <div>您暂无权限查看此{urlType[item.Type]().text}</div>
          <div>若想查看可以联系对口销售</div>
          {item.AuthInfo?.SellerName && (
            <div>
              {item.AuthInfo?.SellerName}：{item.AuthInfo?.SellerMobile}
            </div>
          )}
          <div>申请开通对应的试用权限</div>
        </div>
      )
      if (
        item.AuthInfo.HasPermission === INewPermissionType.HasApplyPotential ||
        item.AuthInfo.HasPermission === INewPermissionType.NoApplyPotential ||
        item.AuthInfo.HasPermission === INewPermissionType.HasApplyFICC ||
        item.AuthInfo.HasPermission === INewPermissionType.NoApplyFICC
      ) {
        content = (
          <div>
            <p>您暂无权限查看此{urlType[item.Type]().text}，若想查看可以申请开通对应的试用权限</p>
          </div>
        )
      }
      // 上传名片时-7，ApplyMethod为2，否则为1
      Modal.confirm({
        title: '提示',
        content: content,
        okText: '提交申请',
        cancelText: '取消',
        centered: true,
        closable: true,
        onOk: () => {
          applyTry({
            ApplyMethod: item.AuthInfo.HasPermission === INewPermissionType.NoApplyPotential ? 2 : 1,
            DetailId: item.Id,
            TryType: urlType[item.Type]().tryType
          })
        }
      })
      return
    }
    // 音频播放按钮点击抛出
    if (isAudioOrVideo(item) && type === 'play') {
      onItemClick && onItemClick()
      return
    }

    const url = urlType[item.Type]().url
    if (!url) return
    window.open(url)
  }
  // 判断是音频还是视频(返回true是音频)
  const isAudioOrVideo = (item: IRoadshowistItem) => {
    return item.Type === 1 || item.Type === 4
  }
  const formatLabel = (label: number) => {
    const labelItem = labelOption.find(item => item.key === label)
    return labelItem?.name || ''
  }
  if (!item) return null
  return (
    <div className={`${styles['roadshow-item']}`}>
      <div
        className={`roadshow-item-title ${item.Type === 4 ? '' : 'com-cursor-p'}`}
        onClick={handleToSomePage.bind(this, item, 'detail')}
        dangerouslySetInnerHTML={{
          __html: item?.LabelType
            ? `<span class="card-tag-lyhf no-wrap">${formatLabel(item.LabelType)}</span><span>${
                title || item?.Title
              }</span>`
            : title || item?.Title
        }}
      />
      <div className="video-line-box">
        <div className="video-img-wrapper">
          <img src={item.BackgroundImg} alt="图像" className="video-img-bg" />
          <div className={`right-top-bg ${isAudioOrVideo(item) ? 'right-top-blue' : 'right-top-orange'}`} />
          <img alt="图像" className="right-top-icon" src={isAudioOrVideo(item) ? audioIcon : videoIcon} />
          {isAudioOrVideo(item) ? (
            <img
              alt="图像"
              src={audioPlayId && audioPlayId === item.SourceId ? stopIcon : audioPlay}
              className="play-center"
              onClick={handleToSomePage.bind(this, item, 'play')}
            />
          ) : (
            <img
              alt="图像"
              src={videoPlay}
              className="play-center"
              onClick={handleToSomePage.bind(this, item, 'play')}
            />
          )}
          <span className="video-play-time">
            {dayjs(parseInt(item.PlaySeconds || '0', 10) * 1000 - 28800000).format(
              parseInt(item.PlaySeconds || '0', 10) >= 3600 ? 'HH:mm:ss' : 'mm:ss'
            )}
          </span>
        </div>
      </div>
      <div className="roadshow-footer">
        <div className="video-time">
          <CategoryTag content={item.ChartPermissionName} className="m-r-xs" />
          <span className="video-publishtime">{item.PublishTime}</span>
        </div>
        <div className="roadshow-right">
          <img src={CommentSvg} alt="图标" className="comment-icon" onClick={handleOpenComment} />
          {videoItem?.IsCollect ? (
            <StarFilled size={14} className="collect-icon " onClick={handleCollectOrNot} />
          ) : (
            <StarOutlined size={14} className="not-collect-icon" onClick={handleCollectOrNot} />
          )}
        </div>
      </div>
      <div onClick={e => e.stopPropagation()}>
        <AskAdd
          visible={visibleComment}
          ID={item?.SourceId || item.Id}
          placeholder={commentPlaceholder}
          onApply={handleApplyComment}
          onCloseModel={handleOkAsk}
        />
      </div>
    </div>
  )
}

export default VideoAudioCard
