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

import { Col, Row, Spin } from 'antd'

import SecondMenu from 'Material/components/SecondMenu'
import { CollectionsService, IWeeklyDetailRes, IWeeklyList } from './Collections.service'
import ValidateLogin2p from 'components/ValidateLogin2p'
import ValidateEmpty from 'components/ValidateEmpty'
import NoPermission, { INewPermissionType, ITryType } from 'Material/components/NoPermission'
import { WebEditError } from 'components/Empty'
import AudioControler from 'Activity/components/AudioControler'
import { IAudioDetail } from 'Activity/Activity.service'
import useTimeCount from 'Material/hooks/useTimeCount'
import { useLogin2p } from 'Login2p/Login2pContext'
import styles from './css/ResearchSummary.module.scss'

enum IMenuKey {
  ThisWeek = 2,
  LastWeek = 3
}

type IResearchSummaryProps = {
  menuID?: number // 菜单
  ArticleID?: number // 文章id
}
const MenuList = [
  { key: IMenuKey.ThisWeek, name: '本周研究汇总' },
  { key: IMenuKey.LastWeek, name: '上周纪要汇总' }
]
/**
 * 本周/上周研究汇总
 */
const ResearchSummary: React.FC<IResearchSummaryProps> = props => {
  const { menuID, ArticleID } = props
  const history = useHistory()
  const login2p = useLogin2p()

  const [menuKey, setMenuKey] = useState<IMenuKey>(IMenuKey.ThisWeek)
  const [articleKey, setArticleKey] = useState<number>()
  const [dataDetail, setDataDetail] = useState<IWeeklyDetailRes>()
  const [showDisclaimers, setShowDisclaimers] = useState(false)
  const [audioDetail, setAudioDetail] = useState<IAudioDetail>()

  useEffect(() => {
    menuID && setMenuKey(menuID)
    ArticleID && setArticleKey(ArticleID)
    getWeeklyList(1, 9999, menuID || 2)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [menuID, ArticleID])

  // 拉取本周/上周列表
  const {
    data,
    loading: listLoading,
    run: getWeeklyList
  } = useRequest(CollectionsService.getWeeklyReportList, {
    manual: true,
    formatResult: response => response.data.Data,
    onSuccess: res => {
      setArticleKey(ArticleID || res?.List[0]?.ArticleId)
      menuID && menuID === IMenuKey.LastWeek
        ? getLastWeekDetail(ArticleID || res?.List[0]?.ArticleId)
        : getThisWeekDetail(ArticleID || res?.List[0]?.ArticleId)
    }
  })
  // 拉取本周详情
  const { loading: weeklyLoading, run: getThisWeekDetail } = useRequest(CollectionsService.getResearchReportDetail, {
    manual: true,
    formatResult: response => response.data.Data,
    onSuccess: res => {
      setDataDetail(res)
      const audio = {
        ActivityId: res?.Detail?.ArticleId, //活动ID
        Name: res?.Detail?.VideoName, //视频名称
        PlaySeconds: res?.Detail?.VideoPlaySeconds, // 时长
        Url: res?.Detail?.VideoUrl //地址
      }
      setAudioDetail(audio)
    }
  })
  // 拉取上周详情
  const { loading: lastweeklyLoading, run: getLastWeekDetail } = useRequest(CollectionsService.getMinutesReportDetail, {
    manual: true,
    formatResult: response => response.data.Data,
    onSuccess: res => {
      setDataDetail(res)
    }
  })
  useTimeCount(
    ArticleID || data?.List[0]?.ArticleId || 0,
    'report',
    (dataDetail?.HasPermission && dataDetail?.HasPermission === INewPermissionType.OK) || false,
    menuID
  )

  // 本周/上周切换
  const handleChangeSecondMenu = (key: string | number) => {
    setMenuKey(key as IMenuKey)
    setAudioDetail(undefined)
    history.push(`/summary/${key}${login2p.inviteCode ? '?invite_code=' + login2p.inviteCode : ''}`)
  }
  // 文章选择
  const handleClickArticle = (item: IWeeklyList) => {
    setAudioDetail(undefined)
    history.push(
      `/summary/${menuKey}/${item.ArticleId}${login2p.inviteCode ? '?invite_code=' + login2p.inviteCode : ''}`
    )
  }
  const handleToArticle = (ID?: string) => {
    const url = `${window.location.origin}/material/info/${ID}`
    ID && window.open(url)
  }
  return (
    <div className={styles['researchsummary-page']}>
      <SecondMenu list={MenuList} defalutKey={menuKey} onChange={handleChangeSecondMenu} />
      <div className="page-max-width">
        <Row wrap={false} className="m-t-md">
          <Col className={styles['researchsummary-left']}>
            <div className={styles['researchsummary-list']}>
              {data?.List?.map((item: IWeeklyList, index: number) => (
                <div className={styles['smfllow-wrapper']} key={item.ArticleId}>
                  <div
                    className={`title-line hover-line ${item.ArticleId === articleKey ? 'active-line' : ''}`}
                    onClick={handleClickArticle.bind(this, item)}
                  >
                    <span className="title">{item.Title}</span>
                  </div>
                </div>
              ))}
            </div>
          </Col>
          <Col flex={1}>
            <div className="researchsummary-content-wrapper">
              <ValidateLogin2p>
                <Spin spinning={weeklyLoading || lastweeklyLoading}>
                  <div className={styles['researchsummary-wrapper']}>
                    <ValidateEmpty loading={listLoading || weeklyLoading || lastweeklyLoading} data={dataDetail}>
                      {dataDetail?.HasPermission && dataDetail?.HasPermission !== INewPermissionType.OK ? (
                        <NoPermission
                          title={'您暂无权限查看此文章内容，若想查看可以申请开通哦'}
                          hasPermission={dataDetail?.HasPermission}
                          detailID={dataDetail?.Detail?.ArticleId || (ArticleID as number)}
                          tryType={menuKey === IMenuKey.ThisWeek ? ITryType.Researchsummary : ITryType.Minutessummary}
                        />
                      ) : (
                        <>
                          {dataDetail?.HasPermission &&
                          dataDetail?.HasPermission === INewPermissionType.OK &&
                          !dataDetail.IsShow ? (
                            <WebEditError />
                          ) : (
                            <div className="researchsummary-content">
                              <h1 className="researchsummary-title">{dataDetail?.Detail.Title}</h1>
                              <div className="g-flex g-flex-between m-b-sm">
                                <span>{dataDetail?.Detail.Department}</span>
                                <span className="gray-text">{dataDetail?.Detail.PublishDate}</span>
                              </div>
                              <div className="gray-text m-b-sm">
                                注：请务必阅读&nbsp;
                                <span
                                  className="blue-link com-cursor-p"
                                  onClick={() => setShowDisclaimers(!showDisclaimers)}
                                >
                                  免责声明
                                </span>
                              </div>
                              {showDisclaimers && (
                                <p className="gray-text m-b-sm com-fz14">
                                  <p className="disclaimers-p">
                                    1、本报告仅供弘则弥道（上海）投资咨询有限公司正式签约的机构客户使用，不会仅因接收人/接受机构收到本报告而将其视为客户。
                                  </p>
                                  <p className="disclaimers-p">
                                    2、本报告根据国际和行业通行的准则，以合法渠道获得这些信息，尽可能保证可靠、准确和完整，但并不保证报告所述信息的准确性和完整性，也不保证本报告所包含的信息或建议在本报告发出后不会发生任何变更。本报告中所提供的信息仅供参考。
                                  </p>
                                  <p className="disclaimers-p">
                                    3、报告中的内容不对投资者做出的最终操作建议做任何的担保，也没有任何形式的分享投资收益或者分担投资损失的书面或口头承诺。不作为客户在投资、法律、会计或税务等方面的最终操作建议，也不作为道义的、责任的和法律的依据或者凭证，无论是否已经明示或者暗示。
                                  </p>
                                  <p className="disclaimers-p">
                                    4、在任何情况下，本公司不对客户/接受人/接受机构因使用报告中内容所引致的一切损失负责任，客户/接受人/接受机构需自行承担全部风险。
                                  </p>
                                </p>
                              )}
                              {audioDetail?.Url && (
                                <div className="m-t-lg m-b-lg">
                                  <AudioControler audioDetail={audioDetail} />
                                </div>
                              )}

                              {dataDetail?.Detail?.Abstract && (
                                <div className="left-block">摘要：{dataDetail?.Detail?.Abstract}</div>
                              )}
                              <div className="dashed-line" />

                              {dataDetail?.List?.map((item, index) => (
                                <React.Fragment key={index}>
                                  <div className="researchsummary-center-title m-b-md">
                                    <img src={item.IcoLink} alt="icon" className="researchsummary-icon g-va-middle" />
                                    <span className="g-va-middle com-fz14">{item.ListName}</span>
                                  </div>
                                  {item?.List?.map(cItem => (
                                    <React.Fragment key={cItem.ChartPermissionId}>
                                      {cItem.PermissionName && (
                                        <div className="research-categary-block">
                                          {cItem.IcoLink && (
                                            <img
                                              src={cItem.IcoLink}
                                              alt="图标"
                                              className="researchsummary-icon g-va-middle"
                                            />
                                          )}

                                          <span className="g-va-middle com-fz14">{cItem.PermissionName}</span>
                                        </div>
                                      )}

                                      {cItem?.List?.map((childItem, childIndex) => (
                                        <React.Fragment key={childIndex}>
                                          <div
                                            className="researchsummary-p"
                                            key={childIndex}
                                            dangerouslySetInnerHTML={{ __html: childItem.Body || '' }}
                                          />
                                          {childItem.ReportLink && (
                                            <div className="researchsummary-right-content">
                                              <span
                                                className="blue-link com-cursor-p"
                                                onClick={handleToArticle.bind(this, childItem.ReportLink)}
                                              >
                                                点击查看详情
                                              </span>
                                            </div>
                                          )}
                                          {childIndex !== cItem?.List.length - 1 && <div className="dashed-line2" />}
                                        </React.Fragment>
                                      ))}
                                    </React.Fragment>
                                  ))}
                                </React.Fragment>
                              ))}
                            </div>
                          )}
                        </>
                      )}
                    </ValidateEmpty>
                  </div>
                </Spin>
              </ValidateLogin2p>
            </div>
          </Col>
        </Row>
      </div>
    </div>
  )
}

export default ResearchSummary
