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

import { Modal, Input, message, Tooltip, Radio, RadioChangeEvent } from 'antd'
// import TipsSvg from 'assets/tips.svg'

import {
  ActivityService,
  IActivityCheckRes,
  IActivitySignupRes,
  IActivitySpecialListItem,
  IActivitySpecialTripAddRes,
  IActivityTypeDetail,
  IActivityTypeListItem
} from 'Activity/Activity.service'

import { useLogin2p } from 'Login2p/Login2pContext'
import { isTimeGreaterThanCurrent, iswithinOneHour } from 'utils/computeTime'
import NButton, { NButtonSizeType } from 'components/NButton/NButton'
import { INewPermissionType, ITryType } from 'Material/components/NoPermission'
import AskAdd from 'Material/components/AskAdd'
import ApplyPermission from 'Material/components/ApplyPermission'
import Picture from './Picture'
import { MaterialService } from 'Material/Material.service'
import { INewestItem } from 'Newest/Newest.service'
import { IMyActivityItem } from 'Personal/Personal.service'
import styles from '../css/ActivityCard.module.scss'
import UploadInfoModel from 'Material/components/UploadInfoModel'

export enum IActivityBtnType {
  Appointment = 'appointment',
  CancelApp = 'cancelApp',
  Ask = 'ask',
  Message = 'message',
  CancelMsg = 'cancelMsg',
  Call = 'call',
  CancelCall = 'cancelCall',
  SignUp = 'signup',
  CancelSignUp = 'cancelSignUp',
  Detail = 'detail'
}
export enum IActivitySpecialBtnType {
  Scheduling = 'scheduling',
  SpecSignUp = 'specialsignup',
  SpecCancelSignUp = 'cancelSpecialSignUp',
  Join = 'join',
  CancelJoin = 'cancelJoin'
}
export enum IActivitySignupType {
  FullStarffed = 'FullStarffed', // 人数已满
  TwoPeople = 'TwoPeople', // 单机构超过两人
  BreakPromise = 'BreakPromise', // 爽约次数过多
  Overtime = 'Overtime', // 超时
  Success = 'Success' // 成功
}
export enum IStateStringType {
  Waitting = '1', // 未开始
  Going = '2', // 进行中
  End = '3' // 已结束
}
export interface IActivityBtnComponent {
  item: IActivityTypeListItem | IActivitySpecialListItem | IActivityTypeDetail | INewestItem | IMyActivityItem
  isSpecial?: boolean // 专项调研活动的按钮
  selfChange?: boolean // 自身按钮状态改变
  btnClass?: 'act-btn-sm' | 'research-btn-sm' // 按钮的自定义样式
  btnGrous?: 'smcard' | 'detail' | 'bigcard' // smcard-如首页的小卡片，detail-如活动详情页，bigcard-如列表的大卡片
  isType?: string
  onChangeSomething?: (activityId?: number) => void // 子组件变更后的操作
  onNeedToDoSome?: () => void // 父组件的操作
}
const ActivityBtnComponent: React.FC<IActivityBtnComponent> = props => {
  const {
    item,
    isSpecial = false,
    selfChange = false,
    btnClass,
    isType,
    btnGrous = 'smcard',
    onChangeSomething,
    onNeedToDoSome
  } = props

  const [visible, setVisible] = useState(false)
  const [callVisible, setCallVisible] = useState(false) // 报名方式选择的弹框
  const [callType, setCallType] = useState<number>() //  报名方式：1预约外呼，2自主拨入，3我要报名 4自主入会
  const [visibleApply, setVisibleApply] = useState(false) // 申请弹框
  const [bigImg, setBigImg] = useState<string>() // 行程安排的数据
  const [actItem, setActItem] = useState<
    IActivityTypeListItem | IActivitySpecialListItem | IActivityTypeDetail | INewestItem
  >()
  const [emailInput, setEmailInput] = useState<string>() // 编写邮箱
  const [emailVisible, setEmailVisible] = useState<boolean>() // 含有邮箱填写的弹框
  const [actionType, setActionType] = useState<IActivityBtnType | IActivitySpecialBtnType>() // 记录点击了哪个按钮操作
  const [resourceCountData, setResourceCountData] = useState({ CompanyPoints: '0', ActivityPoints: '0' }) // 记录活动扣点数据
  // const [visibleApply, setVisibleApply] = useState(false) // 普通申请权限弹框
  const [visibleUpload, setVisibleUpload] = useState(false) // 机构申请试用弹框

  const login2p = useLogin2p()
  const location = useLocation()
  const history = useHistory()

  useEffect(() => {
    if (item) {
      setActItem(JSON.parse(JSON.stringify(item)))
    }
  }, [item])

  // 专项调研的活动报名
  const { run: applyActivitySpectialTripAdd } = useRequest(ActivityService.postActivitySpectialTripAdd, {
    manual: true,
    formatResult: response => response.data.Data,
    onSuccess: res => {
      handleTodoSpecial(res, IActivitySpecialBtnType.SpecSignUp)
    }
  })
  // 专项调研的取消活动报名
  const { run: applyActivitySpectialTripCancel } = useRequest(ActivityService.postActivitySpectialTripCancel, {
    manual: true,
    onSuccess: res => {
      if (res.data.Ret === 200) {
        message.success('取消成功')
        selfChange && handleSelfChangeBtn(IActivitySpecialBtnType.SpecCancelSignUp)
        onChangeSomething &&
          onChangeSomething((item as IActivityTypeListItem).ActivityId || (item as INewestItem).SourceId)
      } else {
        Modal.info({
          title: '提示',
          content: <div dangerouslySetInnerHTML={{ __html: res.data.Msg }} className="reset-pm" />,
          okText: '知道了',
          centered: true
        })
      }
    }
  })
  // 专项调研的感兴趣/不感兴趣
  const { run: applyActivitySpecialSignup } = useRequest(ActivityService.postActivitySpectialSignup, {
    manual: true,
    formatResult: response => response.data.Data,
    onSuccess: res => {
      handleTodoSpecial(res, actItem?.IsSignup ? IActivitySpecialBtnType.CancelJoin : IActivitySpecialBtnType.Join)
    }
  })
  // 帮我代问的权限校验
  const { run: applyCheckApplyBefore } = useRequest(ActivityService.postCheckApplyBefore, {
    manual: true,
    formatResult: response => response.data.Data,
    onSuccess: res => {
      if (res.SignupStatus === IActivitySignupType.Success) {
        setVisible(true)
      } else {
        handleTodoSomething(res, IActivityBtnType.Ask)
      }
    }
  })
  // 活动报名之前的校验（权限、时间、点数、邮箱）
  const { run: applyActivityCheck } = useRequest(ActivityService.postActivityCheck, {
    manual: true,
    formatResult: response => response.data.Data,
    onSuccess: res => {
      handleReturnGoOn(res)
    }
  })

  // 活动报名 报名方式：1预约外呼，2自主拨入，3我要报名 4自主入会
  const { run: applyActivitySignup } = useRequest(ActivityService.postActivitySignup, {
    manual: true,
    formatResult: response => response.data,
    onSuccess: res => {
      if (res.Ret !== 200) {
        message.error(res.ErrMsg || res.Msg)
      } else {
        handleTodoSomething(
          res.Data,
          (res.Data?.SignupType === 1 ? IActivityBtnType.Call : IActivityBtnType.SignUp) ||
            (actionType as IActivityBtnType)
        )
        setEmailVisible(false)
      }
    }
  })
  // 取消活动报名
  const { run: applyActivityCancelSignup } = useRequest(ActivityService.postActivityCancelSignup, {
    manual: true,
    onSuccess: res => {
      if (res.data.Ret === 200) {
        message.success('取消成功')
        selfChange && handleSelfChangeBtn(IActivityBtnType.CancelSignUp)
        onChangeSomething &&
          onChangeSomething((item as IActivityTypeListItem).ActivityId || (item as INewestItem).SourceId)
      } else {
        Modal.info({
          title: '提示',
          content: <div dangerouslySetInnerHTML={{ __html: res.data.ErrMsg || res.data.Msg }} className="reset-pm" />,
          okText: '知道了',
          centered: true
        })
      }
    }
  })
  // 预约纪要
  const { run: applyActAppointmentAdd } = useRequest(ActivityService.postActAppointmentAdd, {
    manual: true,
    formatResult: response => response.data.Data,
    onSuccess: res => {
      handleTodoSomething(res, IActivityBtnType.Appointment)
    }
  })
  // 取消预约纪要
  const { run: applyActAppointmentCancel } = useRequest(ActivityService.postActAppointmentCancel, {
    manual: true,
    formatResult: response => response.data.Data,
    onSuccess: res => {
      handleTodoSomething(res, IActivityBtnType.CancelApp)
    }
  })
  // 会议提醒
  const { run: applyActMeetingReminderAdd } = useRequest(ActivityService.postActMeetingReminderAdd, {
    manual: true,
    formatResult: response => response.data.Data,
    onSuccess: res => {
      handleTodoSomething(res, IActivityBtnType.Message)
    }
  })
  // 取消会议提醒
  const { run: applyActMeetingReminderCancel } = useRequest(ActivityService.postActMeetingReminderCancel, {
    manual: true,
    formatResult: response => response.data.Data,
    onSuccess: res => {
      handleTodoSomething(res, IActivityBtnType.CancelMsg)
    }
  })
  // 帮我带问
  const { run: applyActAskAdd } = useRequest(ActivityService.postActAskAdd, {
    manual: true,
    formatResult: response => response.data.Data,
    onSuccess: res => {
      handleTodoSomething(res, IActivityBtnType.Ask)
    }
  })
  // 申请权限
  const { run } = useRequest(MaterialService.postApplyTry, {
    manual: true,
    onSuccess: res => {
      res.data.Ret === 200 ? message.success('提交成功，请等待销售人员与您联系') : message.info(res.data.Msg)
    }
  })
  // 获取易懂链接
  const { run: getYidongUrl } = useRequest(ActivityService.getYidongActivityDetail, {
    manual: true,
    onSuccess: res => {
      res.data.Data?.YidongActivityUrl && window.open(res.data.Data?.YidongActivityUrl)
    }
  })
  // 提交申请权限
  const handleToApply = (hasPermission: number) => {
    if (!login2p.jwt) return
    // HasPermission=2,4,6，已提交过申请的，提示：您已提交过申请，请等待销售与您联系。
    if (
      hasPermission === INewPermissionType.HasApplyQY ||
      hasPermission === INewPermissionType.HasApplyFICC ||
      hasPermission === INewPermissionType.HasApplyPotential
    ) {
      message.info('您已提交过申请，请等待销售与您联系。')
      return
    }
    // HasPermission=3，5，不弹表单，直接提交申请
    if (hasPermission === INewPermissionType.NoApplyQY || hasPermission === INewPermissionType.NoApplyFICC) {
      run({
        ApplyMethod: 1,
        DetailId: (item as IActivityTypeListItem).ActivityId || (item as INewestItem).SourceId,
        TryType: 'Activity'
      })
      return
    }
    // HasPermission=7，弹表单填写，提交申请
    setVisibleApply(true)
  }
  const handleOKApply = () => {
    setVisibleApply(false)
  }

  const subTitle = (hasPermission: number, isResearch: boolean) => {
    if (
      hasPermission === INewPermissionType.HasApplyPotential ||
      hasPermission === INewPermissionType.NoApplyPotential ||
      hasPermission === INewPermissionType.HasApplyFICC ||
      hasPermission === INewPermissionType.NoApplyFICC
    )
      return
    return !isResearch ? (
      <div>
        <p>若想参加可以联系对口销售，申请开通对应的试用权限</p>
      </div>
    ) : null
  }
  const resetTitle = (hasPermission: number, isResearch: boolean) => {
    if (isResearch)
      return hasPermission === INewPermissionType.HasApplyPotential ||
        hasPermission === INewPermissionType.NoApplyPotential
        ? '暂无权限，您可申请开通试用'
        : '暂无权限，点击提交申请，提醒对口销售为你开通试用'
    if (
      hasPermission === INewPermissionType.HasApplyPotential ||
      hasPermission === INewPermissionType.NoApplyPotential ||
      hasPermission === INewPermissionType.HasApplyFICC ||
      hasPermission === INewPermissionType.NoApplyFICC
    ) {
      return '您暂无权限参加此活动，若想参加可以申请开通对应的试用权限'
    }
    return '您暂无权限参加此活动'
  }
  // 其他活动的接口请求返回后的操作
  const handleTodoSomething = (res: IActivitySignupRes, type: IActivityBtnType) => {
    // 1.先判断权限，无权限则弹框
    const result = handleCheckPower(res.HasPermission, res?.IsResearch, res?.IsResearchSpecial)
    if (!result) return
    // 2.做时间判断：预约外呼和我要报名，都需要在活动开始前1小时操作。消息提醒，需要在活动开始前15分钟设置。
    // 3.权限和时间限制都满足时，对限制人数的活动再依次做以下判断 (后端返回的PopupMsg，就不做处理了，没返回就打后端)
    if (
      res.SignupStatus === IActivitySignupType.Overtime ||
      res.SignupStatus === IActivitySignupType.FullStarffed ||
      res.SignupStatus === IActivitySignupType.TwoPeople ||
      res.SignupStatus === IActivitySignupType.BreakPromise
    ) {
      Modal.info({
        title: '提示',
        content: <div dangerouslySetInnerHTML={{ __html: res.PopupMsg }} className="reset-pm" />,
        okText: '知道了',
        centered: true
      })
      return
    }

    // 剩下的就只有成功的啦
    const { title } = resetSuccess(res, type)
    Modal.info({
      title: title,
      content: <div dangerouslySetInnerHTML={{ __html: res.PopupMsg }} className="reset-pm" />,
      okText: '知道了',
      centered: true
    })
    selfChange && handleSelfChangeBtn(type)
    onChangeSomething && onChangeSomething((item as IActivityTypeListItem).ActivityId || (item as INewestItem).SourceId)
    setActionType(undefined)
    setCallType(undefined)
    setEmailInput(undefined)
  }
  const resetSuccess = (res: IActivitySignupRes, type: IActivityBtnType) => {
    const title: {
      [key: string]: string
    } = {
      [IActivityBtnType.Appointment]: '会议纪要预约成功',
      [IActivityBtnType.CancelApp]: '取消预约成功',
      [IActivityBtnType.Ask]: '发送成功',
      [IActivityBtnType.Message]: '设置成功',
      [IActivityBtnType.CancelMsg]: '会议提醒已取消',
      [IActivityBtnType.Call]: '预约成功',
      [IActivityBtnType.CancelCall]: '取消预约成功',
      [IActivityBtnType.SignUp]: '报名成功',
      [IActivityBtnType.CancelSignUp]: '取消报名成功'
    }

    return { title: title[type] }
  }
  // 权限判断
  const handleCheckPower = (HasPermission: INewPermissionType, isResearch: boolean, isResearchSpecial: boolean) => {
    // 如果接口没返回权限则跳过
    if (!HasPermission) return true

    // 1.先判断权限，无权限则弹框
    if (HasPermission !== INewPermissionType.OK) {
      // 列表的按钮点击，无权限时，需要进入详情页

      if (btnGrous !== 'detail' && login2p.userInfo?.IsShowWxPaySet) {
        isSpecial
          ? window.open(`/activity/info/${(item as IActivitySpecialListItem).ActivityId}`)
          : window.open(`/activity/detail/${(item as IActivityTypeListItem).ActivityId}`)
        return false
      }
      if (isResearchSpecial) {
        Modal.info({
          title: '提示',
          content: '签约买方研选套餐才可参与此活动，请联系对口销售',
          okText: '知道了',
          centered: true
        })
        return false
      }
      Modal.confirm({
        title: resetTitle(HasPermission, isResearch),
        content: subTitle(HasPermission, isResearch),
        okText: '提交申请',
        cancelText: '取消',
        centered: true,
        // onCancel: () => {},
        onOk: () => {
          handleToApply(HasPermission)
        }
      })
      return false
    }
    return true
  }
  // 按钮的各种点击事件
  const handleOkTodoSomething = (
    type: IActivityBtnType | IActivitySpecialBtnType,
    e: React.MouseEvent<HTMLElement, MouseEvent>
  ) => {
    e.stopPropagation()
    // 检查是否登录了，未登录进入登录页面
    if (!login2p.jwt) {
      history.push(`/login2p?next=${encodeURIComponent(location.pathname + location.search)}`)
      return
    }
    console.log((item as IActivityTypeListItem)?.IsShowWxPay, '(item as IActivityTypeListItem)?.IsShowWxPay')

    //先简单的检查一下权限
    const powerCheck = handleCheckPower(
      item?.AuthInfo?.HasPermission,
      item?.IsResearch,
      (item as IActivityTypeListItem)?.IsResearchSpecial
    )

    if (!powerCheck) return
    // 易懂同步过来的活动 直接跳转
    if ((item as IActivityTypeListItem)?.IsYidongActivity) {
      item.ActivityId && getYidongUrl(item.ActivityId)
      return
    }

    setActionType(type)

    handleButtonTodoList(type)
  }
  const handleButtonTodoList = (type: IActivityBtnType | IActivitySpecialBtnType) => {
    const todoList: {
      [key: string]: () => void
    } = {
      // 查看详情
      [IActivityBtnType.Detail]: () => {
        item?.YidongActivityUrl && window.open((item as IActivityTypeListItem)?.YidongActivityUrl)
      },
      // 预约纪要
      [IActivityBtnType.Appointment]: () =>
        applyActAppointmentAdd((item as IActivityTypeListItem).ActivityId || (item as INewestItem).SourceId),
      // 取消纪要
      [IActivityBtnType.CancelApp]: () => {
        Modal.confirm({
          title: '提示',
          content: '您要取消预约本场调研的纪要吗？',
          okText: '是',
          cancelText: '否',
          centered: true,
          onOk: () => {
            applyActAppointmentCancel((item as IActivityTypeListItem).ActivityId || (item as INewestItem).SourceId)
          }
        })
      },
      //帮我代问
      [IActivityBtnType.Ask]: () =>
        applyCheckApplyBefore((item as IActivityTypeListItem).ActivityId || (item as INewestItem).SourceId),
      // 消息提醒
      [IActivityBtnType.Message]: () =>
        applyActMeetingReminderAdd((item as IActivityTypeListItem).ActivityId || (item as INewestItem).SourceId),
      // 取消消息提醒
      [IActivityBtnType.CancelMsg]: () =>
        applyActMeetingReminderCancel((item as IActivityTypeListItem).ActivityId || (item as INewestItem).SourceId),
      // 预约外呼
      [IActivityBtnType.Call]: () =>
        applyActivityCheck((item as IActivityTypeListItem).ActivityId || (item as INewestItem).SourceId),
      // 取消预约外呼
      [IActivityBtnType.CancelCall]: () => {
        if (!handleCheckTime(type)) return
        Modal.confirm({
          title: '提示',
          content: '您要取消此次活动预约外呼吗？',
          okText: '是',
          cancelText: '否',
          centered: true,
          onOk: () => {
            applyActivityCancelSignup((item as IActivityTypeListItem).ActivityId || (item as INewestItem).SourceId)
          }
        })
      },
      // 我要报名
      [IActivityBtnType.SignUp]: () => {
        if (
          ((item as IActivityTypeDetail).IsYidongConduct && (item as IActivityTypeDetail).IsCanOutboundCall) ||
          (!(item as IActivityTypeDetail).IsYidongConduct &&
            (item as IActivityTypeListItem).IsLimitPeople === 1 &&
            [1, 2].includes((item as IActivityTypeListItem).ActivityTypeId)) ||
          (!(item as IActivityTypeDetail).IsYidongConduct &&
            (item as IActivityTypeListItem).IsLimitPeople === 1 &&
            (item as IActivityTypeListItem).ActivityTypeId === 3 &&
            !item.IsResearchPoints)
        ) {
          // 公司调研电话会
          setCallVisible(true)
        } else {
          // 报名前再调接口接口检查一下
          applyActivityCheck((item as IActivityTypeListItem).ActivityId || (item as INewestItem).SourceId)
        }
      },
      // 取消报名
      [IActivityBtnType.CancelSignUp]: () => {
        if (!handleCheckTime(type)) return
        Modal.confirm({
          title: '提示',
          content: '您要取消此次活动报名吗？',
          okText: '是',
          cancelText: '否',
          centered: true,
          onOk: () => {
            applyActivityCancelSignup((item as IActivityTypeListItem).ActivityId || (item as INewestItem).SourceId)
          }
        })
      },
      // 行程安排
      [IActivitySpecialBtnType.Scheduling]: () => {
        // eslint-disable-next-line @typescript-eslint/no-extra-semi
        ;(item as IActivitySpecialListItem).TripStatus === 1
          ? setBigImg((item as IActivitySpecialListItem).TripImgLink)
          : setBigImg(
              (item as IActivitySpecialListItem).TripImgLinkFix || (item as IActivitySpecialListItem).TripImgLink
            )
      },
      // 专项调研的我要报名
      [IActivitySpecialBtnType.SpecSignUp]: () =>
        applyActivitySpectialTripAdd((item as IActivitySpecialListItem).ActivityId || (item as INewestItem).SourceId),
      // 专项调研的取消报名
      [IActivitySpecialBtnType.SpecCancelSignUp]: () => {
        // 判断是否在48小时内
        const hourCount = handleDifferHourTime(item.ActivityTime)
        Modal.confirm({
          title: '提示',
          content:
            hourCount > 48 ? '确定要取消报名吗？' : '活动开始前48小时内，取消报名仍会维持扣点，确定要取消报名吗？',
          okText: '确定',
          cancelText: '取消',
          centered: true,
          onOk: () => {
            applyActivitySpectialTripCancel(
              (item as IActivitySpecialListItem).ActivityId || (item as INewestItem).SourceId
            )
          }
        })
      },
      // 感兴趣
      [IActivitySpecialBtnType.Join]: () =>
        applyActivitySpecialSignup((item as IActivitySpecialListItem).ActivityId || (item as INewestItem).SourceId),
      // 不感兴趣
      [IActivitySpecialBtnType.CancelJoin]: () => {
        Modal.confirm({
          title: '提示',
          content: '您要取消此次专项调研的预报名吗？',
          okText: '确定',
          cancelText: '取消',
          centered: true,
          onOk: () => {
            applyActivitySpecialSignup((item as IActivitySpecialListItem).ActivityId || (item as INewestItem).SourceId)
          }
        })
      }
    }
    todoList[type]()
  }
  // 取消时，判断时间
  const handleCheckTime = (type: IActivityBtnType | IActivitySpecialBtnType) => {
    // 研选扣点-设定取消报名截至时间时-没有设定取消报名截至时间时
    if (
      item.IsResearchPoints &&
      ((item as IActivityTypeListItem).CancelDeadline
        ? !isTimeGreaterThanCurrent((item as IActivityTypeListItem).CancelDeadline)
        : (item as IActivityTypeListItem).SiginupDeadline &&
          !isTimeGreaterThanCurrent((item as IActivityTypeListItem).SiginupDeadline))
    )
      return true

    // 非研选扣点通通按照会前1小时
    if (!item.IsResearchPoints && !iswithinOneHour(item.ActivityTime, 3600000)) return true

    Modal.info({
      title: '提示',
      content: '当前时间点已无法取消报名，若想取消，请联系对口销售',
      okText: '知道了',
      centered: true
    })
    return false
  }

  const handleToAsk = (ID: number, value: string) => {
    applyActAskAdd(ID, value || '')
    setVisible(false)
  }
  // 关闭弹框
  const handleOnClose = (e?: React.MouseEvent<HTMLElement, MouseEvent>) => {
    e?.stopPropagation()
    setVisible(false)
    setCallVisible(false)
    setEmailVisible(false)
    setEmailInput(undefined)
  }
  // 报名方式选择
  const handleChangeCallType = (e: RadioChangeEvent) => {
    setCallType(e.target.value)
  }
  // 确认报名方式选择
  const handleToCall = () => {
    callType && applyActivityCheck((item as IActivityTypeListItem).ActivityId || (item as INewestItem).SourceId)
    setCallVisible(false)
  }

  // 专项调研活动的请求后的处理
  const handleTodoSpecial = (res: IActivitySpecialTripAddRes, type: IActivitySpecialBtnType) => {
    if (res.Status === 2 && res.SignupStatus === 1) {
      message.success('取消成功')
      selfChange && handleSelfChangeBtn(type)
      onChangeSomething &&
        onChangeSomething((item as IActivityTypeListItem).ActivityId || (item as INewestItem).SourceId)
      return
    }
    Modal.info({
      title: '提示',
      content: (
        <div>
          <div dangerouslySetInnerHTML={{ __html: res.PopupMsg }} className="reset-pm" />
          {res?.PopupMsg2 && <div dangerouslySetInnerHTML={{ __html: res.PopupMsg2 }} className="reset-pm gray-text" />}
        </div>
      ),
      okText: '知道了',
      centered: true
    })
    if (res.SignupStatus === 1) {
      selfChange && handleSelfChangeBtn(type)
      onChangeSomething &&
        onChangeSomething((item as IActivityTypeListItem).ActivityId || (item as INewestItem).SourceId)
    }
  }

  // 计算相差小时数 时间格式 YYYY-MM-DD hh:mm:ss
  const handleDifferHourTime = (endDate: string) => {
    return Math.floor((new Date(endDate).getTime() - new Date().getTime()) / 3600000)
  }

  const handleToCloseBigImg = () => {
    setBigImg(undefined)
  }

  const formatBtnSize = () => {
    const groupsObj: {
      [key: string]: () => NButtonSizeType
    } = {
      smcard: () => 'small',
      detail: () => 'middle',
      bigcard: () => 'sm-radius'
    }

    return groupsObj[btnGrous]()
  }

  // 按钮变换
  const handleSelfChangeBtn = (type: IActivityBtnType | IActivitySpecialBtnType) => {
    const newItem = JSON.parse(JSON.stringify(actItem))
    const changeActItem: {
      [key: string]: () => void
    } = {
      // 预约纪要
      [IActivityBtnType.Appointment]: () => (newItem.IsAppointment = 1),
      // 取消纪要
      [IActivityBtnType.CancelApp]: () => (newItem.IsAppointment = 0),
      // 消息提醒
      [IActivityBtnType.Message]: () => (newItem.IsCancelMeetingReminder = 1),
      // 取消消息提醒
      [IActivityBtnType.CancelMsg]: () => (newItem.IsCancelMeetingReminder = 0),
      // 预约外呼
      [IActivityBtnType.Call]: () => {
        newItem.IsSignup = 1
        newItem.SignupType = 1
      },
      // 取消预约外呼
      [IActivityBtnType.CancelCall]: () => {
        newItem.IsSignup = 0
        newItem.SignupType = 0
      },
      // 我要报名
      [IActivityBtnType.SignUp]: () => {
        newItem.IsSignup = 1
        newItem.SignupType = 2
      },
      // 取消报名
      [IActivityBtnType.CancelSignUp]: () => {
        newItem.IsSignup = 0
        newItem.SignupType = 0
      },
      // 专项调研的我要报名
      [IActivitySpecialBtnType.SpecSignUp]: () => (newItem.IsTrip = 1),
      // 专项调研的取消报名
      [IActivitySpecialBtnType.SpecCancelSignUp]: () => (newItem.IsTrip = 0),
      // 感兴趣
      [IActivitySpecialBtnType.Join]: () => (newItem.IsSignup = 1),
      // 不感兴趣
      [IActivitySpecialBtnType.CancelJoin]: () => (newItem.IsSignup = 0)
    }
    changeActItem[type]()
    setActItem(newItem)
  }
  // 整理报名前的校验结果
  const handleReturnGoOn = (res: IActivityCheckRes) => {
    // 1.权限
    if (!res.CheckPermission) {
      handleCheckPower(res.HasPermission, res.IsResearch, res?.IsResearchSpecial)
      return
    }
    // 1.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: res.PopupMsg }} className="reset-pm" />,
        okText: '知道了',
        centered: true
      })
      return
    }
    //3.已有归属机构 ?
    if (res.IsNeedBusinessCard) {
      setVisibleUpload(true)
      return
    }
    // 4.邮箱绑定
    if (!res.CheckEmail) {
      setEmailVisible(true)
      return
    }
    // ----3.0 需求 是否是付费活动
    if (res.IsPayActivity) {
      applyActivitySignup(
        (item as IActivityTypeListItem).ActivityId || (item as INewestItem).SourceId,
        actionType === IActivityBtnType.Call ? 1 : callType ? callType : 3
      )
      return
    }
    // 3.研选扣点
    if (!res.CheckPoints) {
      // todo 如果需要付费 需要判断一下（需要加字段，是否需要支付,提示文案里的价格需要替换）
      if (res.IsShowWxPay) {
        Modal.confirm({
          title: '提示',
          content: (
            <div className="reset-pm">
              <p>
                点数不足，您可以通过单场付费
                <span className={styles['nopower-red']}> ¥{res.GoodsList[0].CurrentPrice} </span>
                参与或者联系销售机构充值
              </p>
              <div>
                当前剩余点数：<span className={styles['link-text']}>{res.CompanyPoints}</span>
              </div>
              <div>
                本次会议扣除点数：<span className={styles['link-text']}>{res.ActivityPoints}</span>
              </div>
            </div>
          ),
          okText: '付费报名',
          onOk: () => {
            if (isType === '详情') {
              onNeedToDoSome && onNeedToDoSome()
            } else {
              window.open(`/activity/detail/${(item as IActivityTypeListItem).ActivityId}`)
            }
          },
          width: 520,
          centered: true
        })
        return
      } else {
        // 常规提示（不需要支付的）
        Modal.warning({
          title: '点数不足',
          content: (
            <div className="reset-pm">
              <p>
                <span>您的研选服务点数不足，若想报名，请联系对口销售升级套餐</span>
                {/* <img src={TipsSvg} alt="icon" className={styles['link-tips-icon']} /> */}
              </p>
              <div>
                当前剩余点数：<span className={styles['link-text']}>{res.CompanyPoints}</span>
              </div>
              <div>
                本次会议扣除点数：<span className={styles['link-text']}>{res.ActivityPoints}</span>
              </div>
            </div>
          ),
          okText: '知道了',
          width: 520,
          centered: true
        })
        return
      }
    }

    setResourceCountData({ CompanyPoints: res.CompanyPoints, ActivityPoints: res.ActivityPoints })

    // 研选扣点校验通过时需要弹框扣点提示
    if (res.CheckPoints && item.IsResearchPoints) {
      Modal.confirm({
        title: '确定报名吗？',
        content: (
          <div className="reset-pm">
            <div>
              当前剩余点数：<span className={styles['link-text']}>{res.CompanyPoints}</span>
            </div>
            <div>
              本次会议扣除点数：<span className={styles['link-text']}>{res.ActivityPoints}</span>
            </div>
            <div>{res.CancelPopupMsg}</div>
          </div>
        ),
        okText: '确定',
        onOk: () => {
          applyActivitySignup((item as IActivitySpecialListItem).ActivityId || (item as INewestItem).SourceId, 3)
        },
        width: 520,
        centered: true
      })
      return
    }
    // 都通过校验的话就报名吧
    applyActivitySignup(
      (item as IActivityTypeListItem).ActivityId || (item as INewestItem).SourceId,
      actionType === IActivityBtnType.Call ? 1 : callType ? callType : 3
    )
  }
  // 邮箱填写
  const handleChangeEmail = (e: React.ChangeEvent<HTMLInputElement>) => {
    setEmailInput(e.target.value)
  }

  // 关闭上传名片弹框
  const handleCloseUpload = () => {
    setVisibleUpload(false)
  }

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

  // 邮箱填写后报名
  const handleApplySignUpWithEmail = () => {
    if (!emailInput) return message.error('请输入邮箱地址')
    bindingEmailUse(emailInput)
    // return
    // // 研选扣点校验通过时需要弹框扣点提示
    // if (item.IsResearchPoints) {
    //   Modal.confirm({
    //     title: '确定报名吗？',
    //     content: (
    //       <div className="reset-pm">
    //         <div>
    //           当前剩余点数：<span className={styles['link-text']}>{resourceCountData.CompanyPoints}</span>
    //         </div>
    //         <div>
    //           本次会议扣除点数：<span className={styles['link-text']}>{resourceCountData.ActivityPoints}</span>
    //         </div>
    //       </div>
    //     ),
    //     okText: '确定',
    //     onOk: () => {
    //       applyActivitySignup(
    //         (item as IActivityTypeListItem).ActivityId || (item as INewestItem).SourceId,
    //         item.IsResearchPoints ? 3 : actionType === IActivityBtnType.Call ? 1 : callType ? callType : 3,
    //         emailInput
    //       )
    //     },
    //     width: 520,
    //     centered: true
    //   })
    //   return
    // } else {
    //   // 填完邮箱后没有点数的话再次调用
    //   applyActivityCheck((item as IActivityTypeListItem).ActivityId || (item as INewestItem).SourceId)
    // }
  }

  // 邮箱的填写
  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 {
        setEmailVisible(false)
        // 填完邮箱后再次判断一下最新的权限
        applyActivityCheck((item as IActivityTypeListItem).ActivityId || (item as INewestItem).SourceId)
      }
    }
  })
  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}
      {visible ? (
        <AskAdd
          title={item.ActiveState === IStateStringType.Going ? '实时提问' : '帮我带问'}
          placeholder="请描述您的问题，分析师会代您向专家提问。"
          visible={visible}
          ID={(item as IActivityTypeListItem).ActivityId || (item as INewestItem).SourceId}
          onApply={handleToAsk}
          onCloseModel={handleOnClose}
        />
      ) : null}
      {callVisible ? (
        <div onClick={e => e.stopPropagation()}>
          <Modal title="请选择参会方式" centered open={callVisible} onOk={handleToCall} onCancel={handleOnClose}>
            <Radio.Group onChange={handleChangeCallType} value={callType}>
              <Radio value={1}>预约外呼</Radio>
              {(item as IActivityTypeDetail).IsYidongConduct ? (
                <Radio value={3}>自主入会</Radio>
              ) : (
                <Radio value={2}>自主拨入</Radio>
              )}
            </Radio.Group>
          </Modal>
        </div>
      ) : null}

      <ApplyPermission
        visible={visibleApply}
        detailID={(item as IActivityTypeListItem).ActivityId || (item as INewestItem).SourceId}
        tryType={ITryType.Activity}
        onCloseModel={handleOKApply}
      />
      <Picture visible={!!bigImg} imgSrc={bigImg} onClose={handleToCloseBigImg} />
      {isSpecial ? (
        <>
          <NButton
            className={btnClass ? btnClass : ''}
            size={formatBtnSize()}
            type={'default'}
            onClick={handleOkTodoSomething.bind(this, IActivitySpecialBtnType.Scheduling)}
          >
            行程安排
          </NButton>
          {item.ActiveState !== IStateStringType.End && (
            <>
              {(item as IActivitySpecialListItem).TripStatus === 1 ? (
                <>
                  {!actItem?.IsSignup ? (
                    <NButton
                      className={btnClass ? btnClass : ''}
                      size={formatBtnSize()}
                      type={'primary'}
                      onClick={handleOkTodoSomething.bind(this, IActivitySpecialBtnType.Join)}
                    >
                      感兴趣
                    </NButton>
                  ) : (
                    <NButton
                      className={btnClass ? btnClass : ''}
                      size={formatBtnSize()}
                      type={'primary'}
                      onClick={handleOkTodoSomething.bind(this, IActivitySpecialBtnType.CancelJoin)}
                    >
                      已预报名
                    </NButton>
                  )}
                </>
              ) : (
                <>
                  {item?.ActiveState === IStateStringType.Waitting && (
                    <>
                      {!(actItem as IActivitySpecialListItem)?.IsTrip ? (
                        <NButton
                          className={btnClass ? btnClass : ''}
                          size={formatBtnSize()}
                          type={'primary'}
                          onClick={handleOkTodoSomething.bind(this, IActivitySpecialBtnType.SpecSignUp)}
                        >
                          我要报名
                        </NButton>
                      ) : (
                        <NButton
                          className={btnClass ? btnClass : ''}
                          size={formatBtnSize()}
                          type={'primary'}
                          onClick={handleOkTodoSomething.bind(this, IActivitySpecialBtnType.SpecCancelSignUp)}
                        >
                          取消报名
                        </NButton>
                      )}
                    </>
                  )}
                </>
              )}
            </>
          )}
        </>
      ) : (
        <>
          {item.ActiveState !== IStateStringType.End && (
            <>
              {item.IsShowDetails && (
                <NButton
                  className={btnClass ? btnClass : ''}
                  size={formatBtnSize()}
                  type={'default'}
                  onClick={handleOkTodoSomething.bind(this, IActivityBtnType.Detail)}
                >
                  查看详情
                </NButton>
              )}
              {item.IsShowAppointment && (
                <>
                  {!actItem?.IsAppointment ? (
                    <NButton
                      className={btnClass ? btnClass : ''}
                      size={formatBtnSize()}
                      type={'default'}
                      onClick={handleOkTodoSomething.bind(this, IActivityBtnType.Appointment)}
                    >
                      预约纪要
                    </NButton>
                  ) : (
                    <NButton
                      className={btnClass ? btnClass : ''}
                      size={formatBtnSize()}
                      type={'default'}
                      onClick={handleOkTodoSomething.bind(this, IActivityBtnType.CancelApp)}
                    >
                      取消纪要
                    </NButton>
                  )}
                </>
              )}
              {item.IsShowHelpSsk && (
                <NButton
                  className={btnClass ? btnClass : ''}
                  size={formatBtnSize()}
                  type={'default'}
                  onClick={handleOkTodoSomething.bind(this, IActivityBtnType.Ask)}
                >
                  {item.ActiveState === IStateStringType.Going ? '实时提问' : '帮我带问'}
                </NButton>
              )}
              {item.IsShowMeetingReminder && (
                <>
                  {!actItem?.IsCancelMeetingReminder ? (
                    <>
                      {btnGrous === 'detail' ? (
                        <Tooltip title="会前15分钟推送微信消息提醒">
                          <NButton
                            className={btnClass ? btnClass : ''}
                            size={formatBtnSize()}
                            type={'default'}
                            onClick={handleOkTodoSomething.bind(this, IActivityBtnType.Message)}
                          >
                            消息提醒
                          </NButton>
                        </Tooltip>
                      ) : (
                        <NButton
                          className={btnClass ? btnClass : ''}
                          size={formatBtnSize()}
                          type={'default'}
                          onClick={handleOkTodoSomething.bind(this, IActivityBtnType.Message)}
                        >
                          消息提醒
                        </NButton>
                      )}
                    </>
                  ) : (
                    <NButton
                      className={btnClass ? btnClass : ''}
                      size={formatBtnSize()}
                      type={'default'}
                      onClick={handleOkTodoSomething.bind(this, IActivityBtnType.CancelMsg)}
                    >
                      取消提醒
                    </NButton>
                  )}
                </>
              )}
              {item.IsShowOutboundCall && (
                <>
                  {!actItem?.IsSignup ? (
                    <NButton
                      className={btnClass ? btnClass : ''}
                      size={formatBtnSize()}
                      type={'primary'}
                      onClick={handleOkTodoSomething.bind(this, IActivityBtnType.Call)}
                    >
                      预约外呼
                      {btnGrous === 'detail' && !!(item as IActivityTypeDetail).IsLimitPeople && (
                        <span className="m-l-xs">
                          {(item as IActivityTypeDetail).SignupNum}/{(item as IActivityTypeDetail).LimitPeopleNum}
                        </span>
                      )}
                    </NButton>
                  ) : (
                    <NButton
                      className={btnClass ? btnClass : ''}
                      size={formatBtnSize()}
                      type={'primary'}
                      onClick={handleOkTodoSomething.bind(this, IActivityBtnType.CancelCall)}
                    >
                      取消外呼
                      {btnGrous === 'detail' && !!(item as IActivityTypeDetail).IsLimitPeople && (
                        <span className="m-l-xs">
                          {(item as IActivityTypeDetail).SignupNum}/{(item as IActivityTypeDetail).LimitPeopleNum}
                        </span>
                      )}
                    </NButton>
                  )}
                </>
              )}
              {item.IsShowSignup && (
                <>
                  {!actItem?.IsSignup ? (
                    <NButton
                      className={btnClass ? btnClass : ''}
                      size={formatBtnSize()}
                      type={'primary'}
                      onClick={handleOkTodoSomething.bind(this, IActivityBtnType.SignUp)}
                    >
                      我要报名
                      {btnGrous === 'detail' && !!(item as IActivityTypeDetail).IsLimitPeople && (
                        <span className="m-l-xs">
                          {(item as IActivityTypeDetail).SignupNum}/{(item as IActivityTypeDetail).LimitPeopleNum}
                        </span>
                      )}
                    </NButton>
                  ) : (
                    <NButton
                      className={btnClass ? btnClass : ''}
                      size={formatBtnSize()}
                      type={'primary'}
                      onClick={handleOkTodoSomething.bind(this, IActivityBtnType.CancelSignUp)}
                    >
                      {(actItem as IActivityTypeDetail).SignupType === 1 ? '取消外呼' : '取消报名'}
                      {btnGrous === 'detail' && !!(item as IActivityTypeDetail).IsLimitPeople && (
                        <span className="m-l-xs">
                          {(item as IActivityTypeDetail).SignupNum}/{(item as IActivityTypeDetail).LimitPeopleNum}
                        </span>
                      )}
                    </NButton>
                  )}
                </>
              )}
            </>
          )}
          <UploadInfoModel
            visible={visibleUpload}
            onCloseModel={handleCloseUpload}
            handleSuccess={handleUploadCardSuccess}
          />
        </>
      )}
    </>
  )
}

export default ActivityBtnComponent
