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

import { message, Modal, Spin } from 'antd'
import { StarOutlined, StarFilled } from '@ant-design/icons'
import { default as CommentFillSvg } from 'assets/comment-fill.svg'
import { default as FindExpertSvg } from 'assets/findexpert.svg'

import ValidateEmpty from 'components/ValidateEmpty'
import { useLogin2p } from 'Login2p/Login2pContext'
import Research from './components/Research.container'
import NoPermission, { INewPermissionType, ISpecialType, ITryType } from './components/NoPermission'
import PayNoPermission from './components/PayNoPermission'
import AskAdd from './components/AskAdd'
import { IArcticleInfo, MaterialService } from './Material.service'
import useTimeCount from './hooks/useTimeCount'
import { setWxShare } from 'utils/wxConfig'
import { useMedia } from 'Context/Media/MediaContext'
import styles from './css/MaterialInfo.module.scss'

type IMaterialInfoProps = {
  articleID: number
}
export enum IArticleType {
  JY = 'JY',
  YX = 'YX'
}
// 报告
const MaterialInfo: React.FC<IMaterialInfoProps> = props => {
  const [visibleAsk, setVisibleAsk] = useState(false)
  const [specialType, setSpecialType] = useState<ISpecialType>(ISpecialType.NormalArticle)
  const login2p = useLogin2p()
  const media = useMedia()

  // 拉取数据
  const {
    data,
    loading: infoLoading,
    run: getArcticleDetail,
    refresh: refreshArcticleDetail
  } = useRequest(MaterialService.getArcticleDetail, {
    manual: true,
    formatResult: response => response.data.Data,
    onSuccess: res => {
      res?.Detail && setWxShare(res?.Detail.Title, res.Detail.Abstract.replace(/<[^>]+>/g, ''), res?.Detail.ShareImg)
      res?.Detail?.IsSpecialArticle
        ? setSpecialType(ISpecialType.SpecialArticle)
        : res?.IsResearch && setSpecialType(ISpecialType.ResearchArticle)
    }
  })

  // 收藏/取消收藏
  const { run: applyCollect } = useRequest(MaterialService.postActicleCollect, {
    manual: true,
    onSuccess: res => {
      message.info(res.data.Msg)
      getArcticleDetail(props.articleID)
    }
  })
  // 留言
  const { run: applyComment } = useRequest(MaterialService.postReportComment, {
    manual: true,
    onSuccess: res => {
      res.data.Success ? message.success(res.data.Msg) : message.error(res.data.ErrMsg)
    }
  })
  // 约访专家
  const { run: applyAppointmentExpert } = useRequest(MaterialService.postAskAppointmentExpert, {
    manual: true,
    onSuccess: res => {
      res.data.Success
        ? Modal.info({
            title: '提醒',
            content: '约访申请已提醒您的对口销售，请等待销售与您联系',
            okText: '知道了',
            centered: true
          })
        : message.error(res.data.Msg || res.data.ErrMsg)
    }
  })

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

  useTimeCount(
    props.articleID,
    'article',
    (data?.HasPermission && data?.HasPermission === INewPermissionType.OK) || false
  )

  const handleToApplyCollect = () => {
    applyCollect(props.articleID)
  }
  const handleOkAsk = () => {
    setVisibleAsk(false)
  }
  const handleApplyComment = (ID: number, content: string) => {
    applyComment(ID, content)
    handleOkAsk()
  }
  // 约访专家
  const handleToFindExpert = () => {
    Modal.confirm({
      title: '提醒',
      content: '约访专家的请求会提醒您的对口销售，确定要发起吗？',
      okText: '确定',
      cancelText: '取消',
      centered: true,
      closable: true,
      onOk: () => {
        applyAppointmentExpert(props.articleID)
      }
    })
  }
  const handleToRefresh = () => {
    console.log('有没有触发')

    // refreshArcticleDetail()
  }
  return (
    <Spin spinning={infoLoading}>
      <AskAdd visible={visibleAsk} ID={props.articleID} onApply={handleApplyComment} onCloseModel={handleOkAsk} />
      <ValidateEmpty loading={infoLoading} data={data}>
        {data?.HasPermission && data?.HasPermission !== INewPermissionType.OK && !data?.IsShowWxPay ? (
          <div className={styles['art-nopower-bg']}>
            <NoPermission
              hasPermission={data?.HasPermission}
              seller={data?.Detail?.Seller}
              detailID={props.articleID}
              tryType={ITryType.Article}
              specialType={specialType}
              border={true}
            />
          </div>
        ) : (
          <div className={styles['art-white-bg']}>
            {login2p.jwt && data?.HasPermission && data?.HasPermission === INewPermissionType.OK ? (
              <div className={styles['material-info-option']}>
                <span className="material-option-item" onClick={() => setVisibleAsk(true)}>
                  <img src={CommentFillSvg} alt="icon" className="option-icon" />
                  <span className="option-text">留言</span>
                </span>
                <span className="divide-line" />
                {data?.Detail?.IsApplyAppointmentExpert && (
                  <>
                    <span className="material-option-item" onClick={handleToFindExpert}>
                      <img src={FindExpertSvg} alt="icon" className="option-icon" />
                      <span className="option-text">约访专家</span>
                    </span>
                    <span className="divide-line" />
                  </>
                )}
                <span className="material-option-item" onClick={handleToApplyCollect}>
                  {data?.Detail.IsCollect ? (
                    <StarFilled size={16} className={`option-icon collect-color`} />
                  ) : (
                    <StarOutlined size={16} className="option-icon" />
                  )}
                  <span className="option-text option-text-ml">{data?.Detail.IsCollect ? '已' : ''}收藏</span>
                </span>
              </div>
            ) : null}
            {data && <Research info={data as IArcticleInfo} handleToRefresh={handleToRefresh} />}
            {data?.HasPermission && data?.HasPermission === INewPermissionType.OK && (
              <div className={`${styles['statement-wrapper']}`}>
                <strong>郑重声明：</strong>
                <p>
                  察研科技研选平台（以下简称“本平台”）所载内容仅供上海察研科技有限公司（以下简称“察研科技”）正式签约客户参考使用，察研科技不因任何机构或个人登录或浏览本页面内容而将该机构或个人视为察研科技的服务对象。
                </p>
                <p>
                  本平台所载信息为用户投稿、公开信息及从第三方合法取得的市场、行业及企业相关等信息，上述信息涉及的观点、陈述、判断等与察研科技立场无关，察研科技对此表述中立。察研科技并不对上述信息的准确性、真实性、可用性、安全性、完整性、正当性做出保证，您应当自行决定是否采纳并自行承担相应的责任。察研科技不对您因使用察研科技提供的任何信息做出的任何决策承担责任。
                </p>
                <p>
                  本平台所载信息、意见不构成任何买卖证券、基金及其他金融工具的投资决策建议或推荐，且在任何时候均不构成对任何人具有针对性的、指导具体投资的操作意见，您应当对本平台中的信息和意见进行评估，全面认识金融市场的风险收益特征，根据自身情况自主作出决策并自行承担风险。市场有风险，投资需谨慎。
                </p>
                <p>
                  未经察研科技书面许可，任何机构或个人不得以翻版、复制、发表、引用或再次分发他人等任何形式侵犯本平台发布的所有内容的版权。如因侵权行为给察研科技造成任何直接或间接的损失，察研科技保留追究一切法律责任的权利。
                </p>
              </div>
            )}
          </div>
        )}
      </ValidateEmpty>
    </Spin>
  )
}

export default MaterialInfo
