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

import { Button, Modal, Spin, message } from 'antd'
import MacroSvg from 'assets/macro.svg'
import ConsumptionSvg from 'assets/consumption.svg'
import MedicineSvg from 'assets/medicine.svg'
import TechnologySvg from 'assets/technology.svg'
import IntelligentSvg from 'assets/intelligent.svg'
import New2 from 'assets/new2.png'

import ValidateLogin2p from 'components/ValidateLogin2p'
import ValidateEmpty from 'components/ValidateEmpty'
import { WebEditError } from 'components/Empty'
import {
  CollectionsService,
  IListSubject,
  ISympleIndustry,
  IListPermissionSubject,
  IListItem
} from './Collections.service'
import NoPermission, { INewPermissionType, ITryType } from 'Material/components/NoPermission'
import useTimeCount from 'Material/hooks/useTimeCount'
import styles from './css/RecentInfo.module.scss'

export enum IArticleType {
  JY = 'JY',
  YX = 'YX'
}
const SubjectList = [
  { label: '消费', svg: ConsumptionSvg },
  { label: '医药', svg: MedicineSvg },
  { label: '科技', svg: TechnologySvg },
  { label: '智造', svg: IntelligentSvg }
]
type IRecentInfoProps = {
  ArticleID?: number // 文章id
}
/**
 * 近期深度研究精选(重点公司)
 */
const RecentInfo: React.FC<IRecentInfoProps> = props => {
  const { ArticleID } = props

  const [showDisclaimers, setShowDisclaimers] = useState(false)
  const [maxLen, setmaxLen] = useState<number>(9)

  useEffect(() => {
    getDetail(ArticleID || 0, !ArticleID)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ArticleID])
  // 拉取数据
  const {
    data,
    loading: infoLoading,
    run: getDetail
  } = useRequest(CollectionsService.getRecentReportDetail, {
    manual: true,
    formatResult: response => response.data.Data
  })
  // 标的点击记录
  const { run: applyClick } = useRequest(CollectionsService.postReportClickHistory, {
    manual: true,
    formatResult: response => response.data.Data
  })
  // 申请路演
  const { run: applyRoadShow } = useRequest(CollectionsService.postApplyReportRoadShow, {
    manual: true,
    formatResult: response => response.data,
    onSuccess: res => {
      res.Success
        ? message.success('申请已提交')
        : Modal.info({
            title: res.Msg || res.ErrMsg,
            content: '',
            centered: true,
            okText: '知道了'
          })
    }
  })
  useTimeCount(
    ArticleID || data?.Detail.ArticleId || 0,
    'report',
    (data?.HasPermission && data?.HasPermission === INewPermissionType.OK) || false,
    1
  )

  // 补足表格
  const formatTable = (list: IListSubject[], index: number) => {
    let listMaxLen = 0
    data?.ListPermissionSubject?.forEach(item => {
      listMaxLen < item.ListSubject?.length && (listMaxLen = item.ListSubject?.length || 0)
    })
    maxLen !== listMaxLen && setmaxLen(listMaxLen)
    const listLength = list?.length || 0
    const num = listMaxLen - listLength
    if (num <= 0) return null
    const td = []
    for (let i = 0; i < num; i++) {
      td.push(<td key={`${index}_${i}`} />)
    }
    return td
  }

  const handleformatIcon = (name: string) => {
    const findItem = SubjectList.find(item => name.includes(item.label))
    return findItem?.svg || ''
  }
  // 跳转其他页面
  const handleToOther = (url?: string) => {
    url && window.open(url)
  }
  // 跳转报告详情
  const handleToArticle = (ID?: number) => {
    const url = `${window.location.origin}/material/info/${ID}`
    ID && window.open(url)
  }
  // 跳转产业详情
  const handleToIndepth = (ChartPermissionId: number, list: ISympleIndustry[]) => {
    if (list.length === 1) {
      const url = `${window.location.origin}/indepth/info/${ChartPermissionId}/${list[0].IndustrialManagementId}`
      window.open(url)
    }
  }
  // 滚动到指定位置
  const handleScrollToSubject = (ArticleId: number, ID: number) => {
    applyClick(ArticleId, ID)
    const findDiv = document.querySelector(`#company_${ID}`) as HTMLElement
    window.scrollTo(0, findDiv?.offsetTop)
  }
  const handleApplyRoadshow = (subjectName: string) => {
    Modal.confirm({
      title: '路演申请会提交至您的对口销售，确定要申请吗？',
      content: '',
      okText: '确定',
      cancelText: '取消',
      centered: true,
      closable: true,
      onOk: () => {
        data?.Detail?.ArticleId && applyRoadShow(data?.Detail?.ArticleId, subjectName)
      }
    })
  }
  return (
    <ValidateLogin2p>
      <Spin spinning={infoLoading}>
        <div className={`page-max-width `}>
          <div className={styles['recent-wrapper']}>
            <ValidateEmpty loading={infoLoading} data={data}>
              {data?.HasPermission && data?.HasPermission !== INewPermissionType.OK ? (
                <NoPermission
                  title={'您暂无权限查看此文章内容，若想查看可以申请开通哦'}
                  hasPermission={data?.HasPermission}
                  detailID={data?.Detail?.ArticleId}
                  tryType={ITryType.ReportSelection}
                />
              ) : (
                <>
                  {data?.HasPermission && data?.HasPermission === INewPermissionType.OK && !data.IsShow ? (
                    <WebEditError />
                  ) : (
                    <div className="recent-content">
                      <h1 className="recent-title">{data?.Detail.Title}</h1>
                      <div className="g-flex g-flex-between m-b-sm">
                        <span>{data?.Detail.Department}</span>
                        <span className="gray-text">{data?.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>
                      )}
                      <div className="description-text">产品说明：{data?.Detail.ProductDescription}</div>
                      <div className="recent-center-title m-b-xl">
                        <img src={MacroSvg} alt="icon" className="recent-icon g-va-middle" />
                        <span className="g-va-middle">宏观策略</span>
                      </div>
                      <div
                        className="recent-p"
                        dangerouslySetInnerHTML={{ __html: data?.Detail.MarketStrategy || '' }}
                      />

                      <div className="recent-right-content">
                        <span>
                          详细策略报告请&nbsp;
                          <span
                            className="blue-link com-cursor-p"
                            onClick={handleToOther.bind(this, data?.Detail.ReportLink)}
                          >
                            点击查看
                          </span>
                        </span>
                      </div>
                      <div className="recent-table-wrapper">
                        <table className="recent-table">
                          <tbody>
                            {data?.ListPermissionSubject?.map((item: IListPermissionSubject, index: number) => (
                              <tr key={index}>
                                <th>{item.PermissionName}</th>
                                {item?.ListSubject?.map(cItem => (
                                  <td
                                    key={cItem.IndustrialSubjectId}
                                    onClick={handleScrollToSubject.bind(
                                      this,
                                      data.Detail.ArticleId,
                                      cItem.IndustrialSubjectId
                                    )}
                                    className="com-cursor-p"
                                  >
                                    {cItem.SubjectName}
                                    {cItem.IsNew ? <img src={New2} alt="new" className="left-top-new" /> : null}
                                  </td>
                                ))}
                                {formatTable(item.ListSubject, index)}
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                      {data?.List?.map((item: IListItem) => (
                        <React.Fragment key={item.ChartPermissionId}>
                          <div className="recent-center-title m-b-md">
                            <img
                              src={handleformatIcon(item.PermissionName)}
                              alt="icon"
                              className="recent-icon g-va-middle"
                            />
                            <span className="g-va-middle">{item.PermissionName}</span>
                          </div>
                          {item?.List?.map(cItem => (
                            <React.Fragment key={cItem.IndustrialSubjectId}>
                              <div
                                className="recent-company-line g-flex g-flex-wap"
                                id={`company_${cItem.IndustrialSubjectId}`}
                              >
                                <strong className="m-r-sm">{cItem.SubjectName}</strong>
                                {cItem.IsNew && <div className="recent-new1">NEW</div>}
                                {cItem?.CompanyLabel?.map((childItem, childIndex) => (
                                  <span
                                    className={`blue-link ${childIndex === 0 ? 'm-l-md' : ''} m-r-lg`}
                                    key={childIndex}
                                  >
                                    #{childItem}
                                  </span>
                                ))}
                              </div>
                              <div className="recent-p" dangerouslySetInnerHTML={{ __html: cItem.Body || '' }} />
                              <div className="recent-mb-llg">
                                {cItem.OverviewArticleId ? (
                                  <div className="recent-right-content">
                                    <span>
                                      公司综述报告&nbsp;
                                      <span
                                        className="blue-link com-cursor-p"
                                        onClick={handleToArticle.bind(this, cItem.OverviewArticleId)}
                                      >
                                        点击查看
                                      </span>
                                    </span>
                                  </div>
                                ) : null}
                                {cItem?.List?.length > 0 ? (
                                  <div className="recent-right-content">
                                    <span>
                                      相关调研纪要、深度报告请&nbsp;
                                      <span
                                        className="blue-link com-cursor-p"
                                        onClick={handleToIndepth.bind(this, item.ChartPermissionId, cItem.List)}
                                      >
                                        点击查看
                                      </span>
                                    </span>
                                  </div>
                                ) : null}
                                {cItem.IsShowApplyButton && (
                                  <div className="g-flex g-flex-center">
                                    <Button
                                      ghost={true}
                                      type="primary"
                                      onClick={handleApplyRoadshow.bind(this, cItem.SubjectName)}
                                    >
                                      申请路演
                                    </Button>
                                  </div>
                                )}
                              </div>
                            </React.Fragment>
                          ))}
                        </React.Fragment>
                      ))}
                    </div>
                  )}
                </>
              )}
            </ValidateEmpty>
          </div>
        </div>
      </Spin>
    </ValidateLogin2p>
  )
}

export default RecentInfo
