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

import { Col, Row, Tag, Spin, Modal, message } from 'antd'
import { PlayCircleOutlined } from '@ant-design/icons'

import { ReactComponent as CityImg } from 'assets/city.svg'
import NewImg from 'assets/new.png'

import { useLogin2p } from 'Login2p/Login2pContext'
import { useMedia } from 'Context/Media/MediaContext'
import { ActivityService, IActivityTypeDetailRes, IArticleListItem, IListndustrialItem } from './Activity.service'
import NoPermission, { INewPermissionType, ISpecialType, ITryType } from 'Material/components/NoPermission'
import AudioControler from './components/AudioControler'
import ActivityBtnComponent, { IStateStringType } from './components/ActivityBtn.component'
import ResearchActivity from 'Community/components/ResearchActivity'
import NButton from 'components/NButton/NButton'
import { setWxShare } from 'utils/wxConfig'
import PayNoPermission from 'Material/components/PayNoPermission'
import Countdown from 'Material/components/Countdown'
import PayProcessModel from 'Material/components/PayProcessModel'
import styles from './css/ActivityTypeDetail.module.scss'

export interface IActivityTypeDetail {
  activityID: number
}

/**活动详情页 */
const ActivityTypeDetail: React.FC<IActivityTypeDetail> = props => {
  const { activityID } = props
  const login2p = useLogin2p()
  const history = useHistory()
  const media = useMedia()

  const [refreshFlag, setRefreshFlag] = useState<boolean>(false)
  const [visibleLink, setVisibleLink] = useState<boolean>(false)
  const [openContinuePay, setOpenContinuePay] = useState<boolean>(false) // 去继续支付
  const [openPayProcess, setOpenPayProcess] = useState<boolean>(false) // 付费报名

  useEffect(() => {
    const code = sessionStorage.getItem('invite_code') || login2p.inviteCode
    activityID && run(activityID, code || undefined)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activityID])

  // 活动详情
  const {
    data,
    loading: activityDetailLoading,
    refresh: refreshDetail,
    run
  } = useRequest(ActivityService.getActivityTypeDetail, {
    manual: true,
    formatResult: response => response.data.Data,
    onSuccess: res => {
      res?.Detail && setWxShare(res?.Detail.ActivityName, res?.Detail.ActivityTimeText, res?.Detail.ShareImg)
      handleToOtherPage()
    }
  })
  // 取消订单
  const { run: postOrderCancel } = useRequest(ActivityService.postOrderCancel, {
    manual: true,
    formatResult: response => response.data,
    onSuccess: res => {
      res.Success ? refreshDetail() : message.error(res.Msg || res.ErrMsg)
    }
  })

  // 查看视频
  const handleToVideoPage = () => {
    if (!data?.Detail.VideoDetail) return
    const url = `${window.location.origin}/activity/video/${data?.Detail.VideoDetail.Id}`
    window.open(url)
  }
  // 易董活动跳转地址
  const handleToOtherPage = () => {
    if (!data?.Detail?.YidongActivityUrl) return
    const aLink = document.createElement('a')
    aLink.href = data?.Detail.YidongActivityUrl
    aLink.target = '_blank'
    aLink.click()
  }
  // 是否存在多篇报告
  const handleArticleLink = () => {
    if (data?.Detail?.ArticleList.length === 1) {
      const url = `${window.location.origin}/material/info/${data?.Detail?.ArticleList[0]?.ArticleId}`
      window.open(url)
    } else {
      setVisibleLink(true)
    }
  }
  const handleClickLink = (item: IArticleListItem) => {
    const url = `${window.location.origin}/material/info/${item.ArticleId}`
    window.open(url)
  }
  // 关闭多篇报告的打开
  const handleToClose = () => {
    setVisibleLink(false)
  }

  const handleToIndepthPage = (item: IListndustrialItem) => {
    // 没有这个页面
    if (!item.IsJump) return
    // history.push(
    //   `/indepth/info/${item.ChartPermissionId}/${item.IndustrialManagementId}${
    //     login2p.inviteCode ? '?invite_code=' + login2p.inviteCode : ''
    //   }`
    // )
  }
  const formatLinkText = (url: string) => {
    return url.indexOf('http') >= 0 ? (
      <a href={url} target="_blank" rel="noreferrer" className="detail-link">
        {url}
      </a>
    ) : (
      url
    )
  }
  // 登录报名
  const handleToShowMore = () => {
    if (!login2p.jwt) {
      history.push(`/login2p?next=${encodeURIComponent(window.location.pathname + window.location.search)}`)
      return
    }
  }
  const handleToRefresh = () => {
    // 支付之后刷新页面
    refreshDetail()
    setRefreshFlag(!refreshFlag)
    setOpenContinuePay(false)
    setOpenPayProcess(false)
  }

  // 取消订单
  const handleCancelOrder = () => {
    if (!data?.OrderCode) return
    postOrderCancel(data.OrderCode)
  }
  // 继续支付
  const handleToContinuePay = () => {
    if (!data?.OrderCode) return
    // 打开支付码
    setOpenContinuePay(true)
  }
  // const formatCountdown = <Countdown countdown={data?.PayTimeCountdown || 0} />
  // 点数不足付费报名
  const handlePayForSignUp = () => {
    setOpenPayProcess(true)
  }
  const parentMethod = () => {
    setOpenPayProcess(false)
  }
  return (
    <div className={styles['activity-detail-page']}>
      <Spin spinning={activityDetailLoading}>
        <Row>
          <Col
            xs={{ span: 24, offset: 0 }}
            sm={{ span: 24, offset: 0 }}
            md={{ span: 24, offset: 0 }}
            lg={{ span: 20, offset: 2 }}
            xl={{ span: 20, offset: 2 }}
          >
            <Row wrap={false} gutter={24} justify="start">
              <Col flex={1} className="m-b-sm">
                {data?.Detail ? (
                  <div
                    className={`activity-detail-content ${
                      data?.HasPermission !== INewPermissionType.OK && data?.IsShowWxPay && !media.isSmallMax
                        ? 'activity-content-nopower'
                        : ''
                    }`}
                  >
                    {data.OrderCode && data.PayTimeCountdown > 0 && (
                      <div className="activity-wait-pay-wrapper">
                        <div className="com-fw-bold com-fz18 m-b-xs">待支付</div>
                        <div className="com-fw-bold com-fz18">
                          剩余支付时间：
                          <span className="countdown-text">
                            <Countdown countdown={data.PayTimeCountdown} onTimeChange={refreshDetail} />
                          </span>
                        </div>
                        <div className="g-flex g-flex-center">
                          <NButton type="default" size="large" className="m-t-md m-r-md" onClick={handleCancelOrder}>
                            取消订单
                          </NButton>
                          <NButton type="primary" size="large" className="m-t-md" onClick={handleToContinuePay}>
                            去支付
                          </NButton>
                        </div>
                      </div>
                    )}
                    <div className="activity-detail-title">
                      {data?.Detail?.IsResearchPoints ? (
                        <span className={`mfyx-label-normal mfyx-label-kd no-wrap`}>扣点</span>
                      ) : data?.Detail?.IsExternalLabel ? (
                        <span className={`mfyx-label-normal mfyx-label-wbzy no-wrap`}>外部资源</span>
                      ) : null}
                      <span className="com-fz18">{data?.Detail.ActivityName}</span>
                    </div>
                    <div className="activity-detail-list">
                      {data?.Detail.VoiceDetail && (
                        <div className="audio-div">
                          <AudioControler audioDetail={data?.Detail.VoiceDetail} />
                        </div>
                      )}
                      {data?.Detail.VideoDetail && (
                        <div className="audio-div">
                          <div className="custom-video" onClick={handleToVideoPage}>
                            <PlayCircleOutlined className="video-control-play" />
                            <div className="video-name m-r-lg">{data?.Detail.VideoDetail.Title}</div>
                            <div className="video-duration">
                              {dayjs(data?.Detail.VideoDetail.VideoDuration * 1000 - 28800000).format(
                                data?.Detail.VideoDetail.VideoDuration >= 3600 ? 'HH:mm:ss' : 'mm:ss'
                              )}
                            </div>
                          </div>
                        </div>
                      )}
                      <div className="activity-detail-line">
                        <span className="activity-detail-label">活动类型：</span>
                        <span className="g-va-middle no-wrap">{data?.Detail.ActivityTypeName}</span>
                        {data?.Detail.City && (
                          <div className="city-wrapper g-va-middle">
                            <CityImg fill="#faa12f" className="city-img" />
                            <span className="g-va-middle">{data?.Detail.City}</span>
                          </div>
                        )}
                      </div>
                      <div className="activity-detail-line">
                        <span className="activity-detail-label">产业标签：</span>
                        {data?.Detail.Label && <span className="m-r-md"> {data?.Detail.Label}</span>}
                        <div>
                          {data?.Detail?.Listndustrial?.map(item => (
                            <React.Fragment key={item.IndustrialManagementId}>
                              <Tag
                                color={item.IsJump ? 'blue' : 'default'}
                                className={`tag-ml ${item.IsJump ? 'com-cursor-p' : ''}`}
                                onClick={handleToIndepthPage.bind(this, item)}
                              >
                                {item.IndustryName}
                              </Tag>
                              {item.IndustryNewLabel && <img src={NewImg} alt="新的" className="new-flag" />}
                            </React.Fragment>
                          ))}
                        </div>
                      </div>
                      <div className="activity-detail-line">
                        <span className="activity-detail-label">活动时间：</span>
                        {data?.Detail.ActivityTimeText}
                      </div>

                      {data?.Detail.DistinguishedGuest && data?.HasPermission === INewPermissionType.OK && (
                        <div className="activity-detail-line">
                          <span className="activity-detail-label">嘉宾：</span>
                          {data?.Detail.DistinguishedGuest}
                        </div>
                      )}
                      {data?.Detail.Host && (
                        <div className="activity-detail-line">
                          <span className="activity-detail-label">主持人：</span>
                          {data?.Detail.Host}
                        </div>
                      )}
                      {data?.Detail.Speaker && data?.HasPermission === INewPermissionType.OK && (
                        <div className="activity-detail-line">
                          <span className="activity-detail-label">主讲人：</span>
                          {data?.Detail.Speaker}
                        </div>
                      )}
                      {data?.Detail.Expert && (
                        <div className="activity-detail-line">
                          <span className="activity-detail-label">专家背景：</span>
                          <div dangerouslySetInnerHTML={{ __html: data?.Detail.Expert }} className="reset-pm" />
                        </div>
                      )}
                      {login2p.jwt && data?.Detail.Address && (
                        <div className="activity-detail-line">
                          <span className="activity-detail-label">活动地点：</span>
                          {data.Detail.ActivityTypeId === 4
                            ? data.Detail.IsSignup
                              ? data?.Detail.Address
                              : '请报名获取'
                            : data?.Detail.Address}
                        </div>
                      )}

                      {data?.Detail.MainlandTell && data?.HasPermission === INewPermissionType.OK && (
                        <div className="activity-detail-line">
                          <span className="activity-detail-label">大陆拨入：</span>
                          <span className="detail-link">{data?.Detail.MainlandTell}</span>
                        </div>
                      )}
                      {data?.Detail.HongKongTell && data?.HasPermission === INewPermissionType.OK && (
                        <div className="activity-detail-line">
                          <span className="activity-detail-label">香港拨入：</span>
                          <span className="detail-link">{data?.Detail.HongKongTell}</span>
                        </div>
                      )}
                      {data?.Detail.TaiwanTell && data?.HasPermission === INewPermissionType.OK && (
                        <div className="activity-detail-line">
                          <span className="activity-detail-label">台湾拨入：</span>
                          <span className="detail-link">{data?.Detail.TaiwanTell}</span>
                        </div>
                      )}
                      {data?.Detail.AmericaTell && data?.HasPermission === INewPermissionType.OK && (
                        <div className="activity-detail-line">
                          <span className="activity-detail-label">美国拨入：</span>
                          <span className="detail-link">{data?.Detail.AmericaTell}</span>
                        </div>
                      )}
                      {login2p.jwt &&
                        data?.Detail.ParticipationCode &&
                        data?.HasPermission === INewPermissionType.OK && (
                          <div className="activity-detail-line">
                            <span className="activity-detail-label">拨入密码：</span>
                            {!!data?.Detail.IsLimitPeople
                              ? data.Detail.IsSignup
                                ? data?.Detail.ParticipationCode
                                : '请报名获取'
                              : data?.Detail.ParticipationCode}
                          </div>
                        )}
                      {login2p.jwt &&
                        data?.Detail.OnlineParticipation &&
                        data?.HasPermission === INewPermissionType.OK && (
                          <div className="activity-detail-line">
                            <span className="activity-detail-label">网络参会：</span>
                            {!!data?.Detail.IsLimitPeople &&
                            !data.Detail.IsSignup &&
                            [1, 2].includes(data.Detail.ActivityTypeId) ? (
                              '请报名获取'
                            ) : (
                              <a
                                href={data?.Detail.OnlineParticipation}
                                target="_blank"
                                rel="noreferrer"
                                className="detail-link"
                              >
                                {data?.Detail.OnlineParticipation}
                              </a>
                            )}
                          </div>
                        )}
                      {login2p.jwt &&
                        data?.Detail.LinkParticipants &&
                        data?.HasPermission === INewPermissionType.OK && (
                          <div className="activity-detail-line">
                            <span className="activity-detail-label">链接参会：</span>
                            {!!data?.Detail.IsLimitPeople
                              ? data.Detail.IsSignup
                                ? formatLinkText(data?.Detail.LinkParticipants)
                                : '请报名获取'
                              : formatLinkText(data?.Detail.LinkParticipants)}
                          </div>
                        )}
                      {(data?.Detail?.ArticleList?.length || 0) > 0 &&
                        data?.HasPermission === INewPermissionType.OK && (
                          <div className="activity-detail-line">
                            <span className="activity-detail-label">相关报告：</span>
                            <div onClick={handleArticleLink} className="detail-btn-link">
                              点击查看
                            </div>
                          </div>
                        )}
                      {data?.Detail.Theme && (
                        <div className="activity-detail-line">
                          <span className="activity-detail-label">主题：</span>
                          <div dangerouslySetInnerHTML={{ __html: data?.Detail.Theme }} className="reset-pm" />
                        </div>
                      )}
                      {login2p.jwt &&
                        data?.Detail.TencentConferenceNumber &&
                        data?.HasPermission === INewPermissionType.OK && (
                          <div className="activity-detail-line">
                            <span className="activity-detail-label">腾讯会议号：</span>
                            <div className="detail-link">
                              {!!data?.Detail.IsLimitPeople || data.Detail.IsYidongConduct
                                ? data.Detail.IsSignup
                                  ? data?.Detail.TencentConferenceNumber
                                  : '请报名获取'
                                : data?.Detail.TencentConferenceNumber}
                            </div>
                          </div>
                        )}
                      {data?.Detail.AppAttendance && data?.HasPermission === INewPermissionType.OK && (
                        <div className="activity-detail-line">
                          <span className="activity-detail-label">App参会：</span>
                          {data.Detail.AppAttendance}
                        </div>
                      )}
                      {login2p.jwt &&
                        data?.Detail.ConferencePassword &&
                        data?.HasPermission === INewPermissionType.OK && (
                          <div className="activity-detail-line">
                            <span className="activity-detail-label">会议密码：</span>
                            {!!data?.Detail.IsLimitPeople
                              ? data.Detail.IsSignup
                                ? data.Detail.ConferencePassword
                                : '请报名获取'
                              : data.Detail.ConferencePassword}
                          </div>
                        )}
                      {data?.Detail.Highlights && (
                        <div className="activity-detail-line">
                          <span className="activity-detail-label">活动亮点：</span>
                          <div dangerouslySetInnerHTML={{ __html: data?.Detail.Highlights }} className="reset-pm" />
                        </div>
                      )}
                      {data?.Detail.Remarks && (
                        <div className="activity-detail-line">
                          <span className="activity-detail-label">备注：</span>
                          <div dangerouslySetInnerHTML={{ __html: data?.Detail.Remarks }} className="reset-pm" />
                        </div>
                      )}
                    </div>
                    {login2p.jwt &&
                      data.HasPermission === INewPermissionType.OK &&
                      data?.Detail.ActiveState !== IStateStringType.End &&
                      data?.Detail && (
                        <div className="detail-btn-wrapper">
                          <ActivityBtnComponent
                            item={data?.Detail}
                            btnGrous="detail"
                            onChangeSomething={refreshDetail}
                            onNeedToDoSome={handlePayForSignUp}
                            isType="详情"
                          />
                        </div>
                      )}
                    {!login2p.jwt && (
                      <div className="detail-btn-wrapper">
                        <NButton type="primary" onClick={handleToShowMore} size="login-large" className="m-center">
                          请登录后报名
                        </NButton>
                      </div>
                    )}
                    {!activityDetailLoading &&
                    login2p.jwt &&
                    data?.HasPermission !== INewPermissionType.OK &&
                    data?.IsShowWxPay &&
                    !media.isSmallMax ? (
                      <div className="activity-paynopermission-wrapper">
                        <div className="white-wrapper" />
                        <div className="white-bg">
                          <PayNoPermission
                            dataInfo={data as IActivityTypeDetailRes}
                            tryType={ITryType.Activity}
                            onRefresh={handleToRefresh}
                          />
                        </div>
                      </div>
                    ) : null}
                  </div>
                ) : null}
                {!activityDetailLoading &&
                login2p.jwt &&
                data?.HasPermission !== INewPermissionType.OK &&
                !data?.IsShowWxPay &&
                !media.isSmallMax ? (
                  <NoPermission
                    hasPermission={data?.HasPermission}
                    detailID={activityID}
                    specialType={
                      data?.IsResearchSpecial
                        ? ISpecialType.ResearchSpecial
                        : data?.IsResearch
                        ? ISpecialType.ResearchActivity
                        : ISpecialType.Activity
                    }
                    tryType={ITryType.Activity}
                    border={true}
                  />
                ) : null}
                {!activityDetailLoading && !!data ? (
                  <PayProcessModel
                    dataInfo={data as IActivityTypeDetailRes}
                    tryType={ITryType.Activity}
                    open={openPayProcess}
                    continuePayFlag={openContinuePay}
                    onRefresh={handleToRefresh}
                    parentMethod={parentMethod}
                  />
                ) : null}
              </Col>
              <Col flex={'542px'} xs={0} sm={0} md={0} lg={0} xl={24} xxl={24}>
                <ResearchActivity isRefresh={refreshFlag} />
              </Col>
            </Row>
          </Col>
        </Row>
      </Spin>
      <Modal
        open={visibleLink}
        title="请选择报告"
        onCancel={handleToClose}
        destroyOnClose={true}
        maskClosable={false}
        footer={null}
        centered
      >
        <div>
          {data?.Detail?.ArticleList?.map(item => (
            <p key={item.ArticleId} onClick={handleClickLink.bind(this, item)} className="detail-dialog-link">
              {item.Title}
            </p>
          ))}
        </div>
      </Modal>
    </div>
  )
}

export default ActivityTypeDetail
