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

import { Tooltip, message, Modal, Input } from 'antd'

import NoPowerImg from 'assets/nopower.png'
import BagImg from 'assets/bag.png'
import TipsSvg from 'assets/tips2.svg'

import NButton from 'components/NButton/NButton'
import { IArcticleInfo, MaterialService } from 'Material/Material.service'
import { ITryType, INewPermissionType } from './NoPermission'
import { PayType } from './BuyModel'
import { IActivityTypeDetailRes, ActivityService, IActivityCheckRes } from 'Activity/Activity.service'
import PayProcessModel from './PayProcessModel'
import styles from '../css/NoPermission.module.scss'
import { IColumnDetail } from 'Column/Column.service'

import UploadInfoModel from './UploadInfoModel'
interface IPayNoPermissionProps {
  dataInfo: IArcticleInfo | IActivityTypeDetailRes | IColumnDetail
  tryType: ITryType
  border?: boolean
  onRefresh?: () => void // 刷新页面
}
/**购买权限 */
const PayNoPermission: React.FC<IPayNoPermissionProps> = props => {
  const { dataInfo, tryType, border = false, onRefresh } = props
  const [visibleApply, setVisibleApply] = useState(false) // 普通申请权限弹框
  const [visibleBuyCard, setVisibleBuyCard] = useState(false) // 购买畅读卡弹框
  const payType = dataInfo.GoodsList.length > 1 ? PayType.Card : PayType.Single // 支付类型[1:畅销卡,2:单场活动

  const [emailVisible, setEmailVisible] = useState<boolean>() // 含有邮箱填写的弹框
  const [emailInput, setEmailInput] = useState<string>('') // 编写邮箱
  const [visibleUpload, setVisibleUpload] = useState(false) // 机构申请试用弹框

  // 申请试用接口
  const { run: postApplyTry } = useRequest(MaterialService.postApplyTry, {
    manual: true,
    onSuccess: res => {
      res.data.Ret === 200 ? message.success('提交成功，请等待销售人员与您联系') : message.info(res.data.Msg)
    }
  })

  // 活动报名之前的校验（权限、时间、点数、邮箱）
  const { run: applyActivityCheck } = useRequest(ActivityService.postActivityCheck, {
    manual: true,
    formatResult: response => response.data.Data,
    onSuccess: res => {
      handleReturnGoOn(res)
    }
  })

  // 邮箱的填写
  const { run: bindingEmailUse } = useRequest(ActivityService.bindingEmail, {
    manual: true,
    formatResult: response => response.data,
    onSuccess: res => {
      if (res.Ret !== 200) {
        message.error(res.ErrMsg || res.Msg)
      } else {
        handleOnClose()
        setVisibleBuyCard(true)
      }
    }
  })

  // 整理报名前的校验结果
  const handleReturnGoOn = (res: IActivityCheckRes) => {
    // 1.人数
    if (!res.CheckSiginUpNum) {
      Modal.warning({
        title: '提示',
        content: (
          <div dangerouslySetInnerHTML={{ __html: '此活动报名人数已满，请留意下期活动' }} className="reset-pm" />
        ),
        okText: '知道了',
        centered: true
      })
      return
    }
    // 2.时间
    if (!res.CheckTime) {
      Modal.warning({
        title: '提示',
        content: (
          <div
            dangerouslySetInnerHTML={{ __html: '该活动已截止报名 \n\n若想参加，请联系对口销售' }}
            className="reset-pm"
          />
        ),
        okText: '知道了',
        centered: true
      })
      return
    }
    //3.已有归属机构 ?
    if (res.IsNeedBusinessCard) {
      setVisibleUpload(true)
      return
    }

    // 4.邮箱绑定
    if (!res.CheckEmail) {
      setEmailVisible(true)
      return
    }
    // 都通过校验的话就打开畅读卡弹框
    setVisibleBuyCard(true)
  }
  // 关闭上传名片弹框
  const handleCloseUpload = () => {
    setVisibleUpload(false)
  }

  // 上传名片成功后,关闭上传名片弹框,并请求创建订单接口
  const handleUploadCardSuccess = () => {
    handleCloseUpload()
    setVisibleBuyCard(true)
  }

  // 点击购买畅读卡按钮
  const handleOpenBuyModel = () => {
    if (tryType === ITryType.Activity) {
      applyActivityCheck((dataInfo as IActivityTypeDetailRes).Detail.ActivityId)
    } else {
      //已有归属机构 这个在前的
      if ((dataInfo as IColumnDetail).Detail.IsNeedBusinessCard || (dataInfo as IArcticleInfo).IsNeedBusinessCard) {
        setVisibleUpload(true)
        return
      } else {
        setVisibleBuyCard(true)
      }
    }
  }
  // 申请试用
  const handleToAskTry = () => {
    // HasPermission=2,4,6，已提交过申请的，提示：您已提交过申请，请等待销售与您联系。
    const hasPermission = dataInfo.HasPermission
    if (
      hasPermission === INewPermissionType.HasApplyQY ||
      hasPermission === INewPermissionType.HasApplyFICC ||
      hasPermission === INewPermissionType.HasApplyPotential
    ) {
      message.info('您已提交过申请，请等待销售与您联系。')
      return
    }
    // HasPermission=3，5，不弹表单，直接提交申请
    if (hasPermission === INewPermissionType.NoApplyQY || hasPermission === INewPermissionType.NoApplyFICC) {
      const detailId =
        tryType === ITryType.Article
          ? (dataInfo as IArcticleInfo).Detail.ArticleId
          : tryType === ITryType.YanxuanSpecial
          ? (dataInfo as IColumnDetail).Detail.Id
          : (dataInfo as IActivityTypeDetailRes).Detail.ActivityId
      postApplyTry({ ApplyMethod: 1, DetailId: detailId, TryType: tryType })
      return
    }
    // HasPermission=7，弹表单填写，提交申请
    setVisibleApply(true)
  }
  // 关闭弹框
  const handleOnClose = () => {
    setEmailInput('')
    setEmailVisible(false)
  }
  // 邮箱填写
  const handleChangeEmail = (e: React.ChangeEvent<HTMLInputElement>) => {
    setEmailInput(e.target.value)
  }
  // 邮箱填写后报名
  const handleApplySignUpWithEmail = () => {
    if (!emailInput) return message.error('请输入邮箱地址')
    // 研选扣点校验通过时需要弹框扣点提示
    bindingEmailUse(emailInput)
  }

  const parentMethod = () => {
    setVisibleApply(false)
    // 关闭畅读卡弹框
    setVisibleBuyCard(false)
  }
  return (
    <>
      {emailVisible ? (
        <div onClick={e => e.stopPropagation()}>
          <Modal title="提示" centered open={emailVisible} onOk={handleApplySignUpWithEmail} onCancel={handleOnClose}>
            <div className="reset-pm">
              <p>应上市公司要求，该会议报名需提供邮箱，请填写您的工作邮箱</p>
              <p>
                <Input type="text" placeholder="请输入正确的邮箱地址" value={emailInput} onChange={handleChangeEmail} />
              </p>
            </div>
          </Modal>
        </div>
      ) : null}
      <div className={`${border ? styles['gray-boder-box'] : ''} ${styles['nopower-showwxpay-wrapper']} `}>
        {tryType !== ITryType.Activity ? <img src={NoPowerImg} alt="无权限" className="nopower-big-img" /> : null}
        <div className="nopower-content-wrapper">
          <div className={tryType !== ITryType.Activity ? 'nopower-title' : 'nopower-activity-title'}>
            {tryType === ITryType.Activity ? '暂无权限参加此活动' : '暂无权限查看完整报告'}
          </div>
          <div className="nopower-text">
            {payType === PayType.Card ? (
              <>
                <span>您可以购买畅读卡后查看</span>
                <span className="nopower-red">（{dataInfo.PopupPriceMsg}）</span>
                <Tooltip
                  title={
                    <div>
                      注释：畅读卡有效期内，可查阅无限量调研纪要及常规研选专栏，
                      参与所有公开活动（日卡自付费完成顺延24小时，月卡自付费完成当天顺延一个自然月）
                    </div>
                  }
                >
                  <img src={TipsSvg} alt="icon" className="nopower-tips-icon" />
                </Tooltip>
              </>
            ) : (
              <>
                <span>您可以通过单场付费</span>
                <span className="nopower-red">{dataInfo.PopupPriceMsg}</span>
                <span>参与</span>
              </>
            )}
          </div>
          {!(dataInfo as IActivityTypeDetailRes).OrderCode ? (
            <NButton type="primary" onClick={handleOpenBuyModel} size="large" className="btn-line">
              {payType === PayType.Card
                ? '购买畅读卡'
                : `付费报名${
                    !!(dataInfo as IActivityTypeDetailRes).Detail.IsLimitPeople
                      ? '(' +
                        (dataInfo as IActivityTypeDetailRes).Detail.SignupNum +
                        '/' +
                        (dataInfo as IActivityTypeDetailRes).Detail.LimitPeopleNum +
                        ')'
                      : ''
                  }`}
            </NButton>
          ) : null}
          <div className="nopower-text m-t-md">
            {(dataInfo as IActivityTypeDetailRes).Detail.IsResearchPoints
              ? '或者申请开通机构年度付费通道'
              : '或向销售申请开通机构试用权限'}
          </div>
          {!(dataInfo as IActivityTypeDetailRes).Detail.IsResearchPointsByUser ? (
            <>
              <NButton
                type="default"
                onClick={handleToAskTry}
                size="auto-large"
                className="btn-line"
                disabled={dataInfo.IsCompanyApply}
              >
                <div className="nopower-disable-text">申请试用</div>
                {dataInfo.IsCompanyApply && <span className="com-fz12">（贵司已申请过机构试用）</span>}
              </NButton>
              <div className="com-fz12 m-t-sm">（仅限机构投资者）</div>
            </>
          ) : null}
          <div className="g-inline-block">
            <div className="nopower-bag-wrapper">
              <img src={BagImg} alt="图片" className="nopower-bag-img" />
              {(dataInfo as IActivityTypeDetailRes).Detail.IsResearchPoints ? (
                <div className="nopower-bag-right">
                  <div className="nopower-br-text com-fw-bold">
                    服务报价：
                    <span className="com-fz20">5w/年</span>
                  </div>
                  <div className="nopower-br-text com-fz12 mobile-sm-text">
                    低至2000元/场专家、同业访谈
                    <br />
                    1000元/场重点公司小范围交流
                  </div>
                </div>
              ) : (
                <div className="nopower-bag-right">
                  <div className="nopower-br-text com-fw-bold">
                    机构订阅服务报价：
                    <span className="com-fz20">3w/年</span>
                  </div>
                  <div className="nopower-br-text com-fz12 mobile-sm-text">
                    无限量调研纪要及常规研选专栏查阅， 公开活动参与
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
      <PayProcessModel
        dataInfo={dataInfo}
        tryType={tryType}
        open={visibleBuyCard}
        applyTrial={visibleApply}
        onRefresh={onRefresh}
        parentMethod={parentMethod}
      />
      <UploadInfoModel
        visible={visibleUpload}
        onCloseModel={handleCloseUpload}
        handleSuccess={handleUploadCardSuccess}
      />
    </>
  )
}

export default PayNoPermission
