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

import { Tooltip, message } from 'antd'

import ApplyPermission from './ApplyPermission'
import { EOrderStatus, IArcticleInfo, IOrderPayStatusRes, MaterialService } from 'Material/Material.service'
import { ITryType, INewPermissionType } from './NoPermission'
import ApplyResult from './ApplyResult'
import BuyModel, { PayType } from './BuyModel'
import QRCodeModel from './QRCodeModel'
import UploadInfoModel from './UploadInfoModel'
import { IActivityTypeDetailRes } from 'Activity/Activity.service'
import styles from '../css/NoPermission.module.scss'
import { IColumnDetail } from 'Column/Column.service'

interface IPayProcessModelProps {
  dataInfo: IArcticleInfo | IActivityTypeDetailRes | IColumnDetail
  tryType: ITryType
  open?: boolean // 是否打开支付流程弹框
  applyTrial?: boolean // 是否申请试用
  continuePayFlag?: boolean // 继续支付
  countDownRender?: React.ReactNode
  onRefresh?: () => void // 刷新页面
  parentMethod?: () => void
}
/**支付流程汇总弹框 */
const PayProcessModel: React.FC<IPayProcessModelProps> = props => {
  const { dataInfo, tryType, open, applyTrial, continuePayFlag, countDownRender, parentMethod, onRefresh } = props
  const [visibleApply, setVisibleApply] = useState(false) // 普通申请权限弹框
  const [visibleUpload, setVisibleUpload] = useState(false) // 机构申请试用弹框
  const [visibleBuyCard, setVisibleBuyCard] = useState(false) // 购买畅读卡弹框
  const [visibleOrderCode, setVisibleOrderCode] = useState(false) // 订单二维码弹框
  const [visibleResult, setVisibleResult] = useState(false) // 支付结果弹框
  const [wantBuyGoodsId, setWantBuyGoodsId] = useState(0) // 购买畅读卡的选项
  const [payInfo, setPayInfo] = useState<IOrderPayStatusRes | null>(null) // 支付订单详情
  const payType = dataInfo.GoodsList.length > 1 ? PayType.Card : PayType.Single // 支付类型[1:畅销卡,2:单场活动

  // 报告畅读卡购买,创建订单
  const { data: articleOrderInfo, run: postCreateOrderByArticle } = useRequest(
    MaterialService.postCreateOrderByArticle,
    {
      manual: true,
      formatResult: response => response.data,
      onSuccess: res => {
        // 订单创建成功打开支付二维码弹框
        res.Success ? setVisibleOrderCode(true) : message.error(res.Msg || res.ErrMsg)
      }
    }
  )
  // 报告畅读卡购买,创建订单
  const { data: yanxuanOrderInfo, run: postCreateOrderByYanXuan } = useRequest(
    MaterialService.postCreateOrderByYanXuan,
    {
      manual: true,
      formatResult: response => response.data,
      onSuccess: res => {
        // 订单创建成功打开支付二维码弹框
        res.Success ? setVisibleOrderCode(true) : message.error(res.Msg || res.ErrMsg)
      }
    }
  )
  // 活动报名购买,创建订单
  const { data: activityOrderInfo, run: postCreateOrderByActivity } = useRequest(
    MaterialService.postCreateOrderByActivity,
    {
      manual: true,
      formatResult: response => response.data,
      onSuccess: res => {
        // 订单创建成功打开支付二维码弹框
        res.Success ? setVisibleOrderCode(true) : message.error(res.Msg || res.ErrMsg)
      }
    }
  )
  // 申请试用接口
  const { run: postApplyTry } = useRequest(MaterialService.postApplyTry, {
    manual: true,
    onSuccess: res => {
      res.data.Ret === 200 ? message.success('提交成功，请等待销售人员与您联系') : message.info(res.data.Msg)
    }
  })
  useEffect(() => {
    if (open) {
      // 开启支付流程
      handleOpenBuyModel()
    }
    if (applyTrial) {
      // 申请试用
      handleToAskTry()
    }
    if (tryType === ITryType.Activity && payType === PayType.Single && continuePayFlag) {
      // 继续支付(现在只有活动有继续支付的需求)
      // todo 二维码的倒计时，需要后端返回订单剩余支付时间
      postCreateOrderByActivity(
        dataInfo.GoodsList[0]?.GoodsId,
        (dataInfo as IActivityTypeDetailRes).Detail.ActivityId,
        sessionStorage.getItem('invite_code')
      )
    }
  }, [open, applyTrial, continuePayFlag])
  // 关闭支付结果弹框
  const handleCloseResult = () => {
    // 并刷新页面
    onRefresh && onRefresh()
    setVisibleResult(false)
  }
  // 关闭支付code弹框
  const handleCloseCode = () => {
    // 如果是单场购买，关闭后刷新页面
    if (payType === PayType.Single) {
      onRefresh && onRefresh()
    }
    setVisibleOrderCode(false)
  }
  // 关闭购买畅读卡弹框
  const handleCloseBuy = () => {
    parentMethod && parentMethod()
    setVisibleBuyCard(false)
  }
  // 上传名片成功后,关闭上传名片弹框,并请求创建订单接口
  const handleUploadCardSuccess = () => {
    handleCloseUpload()
    // 调接口获取支付二维码
    if (tryType === ITryType.Article) {
      postCreateOrderByArticle(
        wantBuyGoodsId,
        (dataInfo as IArcticleInfo).Detail.ArticleId,
        sessionStorage.getItem('invite_code')
      )
    }
    // --------
    if (tryType === ITryType.YanxuanSpecial) {
      postCreateOrderByYanXuan(
        wantBuyGoodsId,
        (dataInfo as IColumnDetail).Detail.Id,
        sessionStorage.getItem('invite_code')
      )
    }
    if (tryType === ITryType.Activity) {
      postCreateOrderByActivity(
        wantBuyGoodsId,
        (dataInfo as IActivityTypeDetailRes).Detail.ActivityId,
        sessionStorage.getItem('invite_code')
      )
    }
  }
  // 关闭上传名片弹框
  const handleCloseUpload = () => {
    setVisibleUpload(false)
  }
  // 关闭申请试用弹框
  const handleCloseApply = () => {
    parentMethod && parentMethod()
    setVisibleApply(false)
  }
  // 点击购买畅读卡按钮
  const handleOpenBuyModel = () => {
    // 打开畅读卡弹框
    setVisibleBuyCard(true)
  }
  // 点击支付
  const handleClickPay = (GoodsId: number) => {
    setWantBuyGoodsId(GoodsId)
    // 判断是否需要上传名片
    // if (dataInfo.IsNeedBusinessCard) {
    //   setVisibleUpload(true)
    //   return
    // }
    // 调接口获取支付二维码
    if (tryType === ITryType.Article) {
      postCreateOrderByArticle(
        GoodsId,
        (dataInfo as IArcticleInfo).Detail.ArticleId,
        sessionStorage.getItem('invite_code')
      )
    }
    if (tryType === ITryType.YanxuanSpecial) {
      postCreateOrderByYanXuan(GoodsId, (dataInfo as IColumnDetail).Detail.Id, sessionStorage.getItem('invite_code'))
    }
    if (tryType === ITryType.Activity) {
      postCreateOrderByActivity(
        GoodsId,
        (dataInfo as IActivityTypeDetailRes).Detail.ActivityId,
        sessionStorage.getItem('invite_code')
      )
    }
    setVisibleBuyCard(false)
  }
  // 申请试用
  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 handleDoPayResult = (OrderRes: IOrderPayStatusRes) => {
    setPayInfo(OrderRes)
    switch (OrderRes.OrderStatus) {
      case EOrderStatus.Cancel:
        console.log('已取消')
        setVisibleResult(true)
        setVisibleOrderCode(false)
        break
      case EOrderStatus.WaitPay:
        console.log('待支付')
        break
      case EOrderStatus.Payed:
        setVisibleResult(true)
        setVisibleOrderCode(false)
        break
      case EOrderStatus.Refund:
        console.log('已退款')
        break
      default:
        console.log('未知状态')
        break
    }
  }

  return (
    <>
      <QRCodeModel
        visible={visibleOrderCode}
        codeUrl={
          yanxuanOrderInfo?.Data.CodeUrl || articleOrderInfo?.Data.CodeUrl || activityOrderInfo?.Data.CodeUrl || ''
        }
        orderCode={
          yanxuanOrderInfo?.Data.OrderCode ||
          articleOrderInfo?.Data.OrderCode ||
          activityOrderInfo?.Data.OrderCode ||
          ''
        }
        countDown={
          articleOrderInfo?.Data.PayTimeCountdown ||
          activityOrderInfo?.Data.PayTimeCountdown ||
          yanxuanOrderInfo?.Data.PayTimeCountdown
        }
        onCloseModel={handleCloseCode}
        onSendPayResult={handleDoPayResult}
      />
      <ApplyResult visible={visibleResult} info={payInfo} onCloseModel={handleCloseResult} />
      <BuyModel
        visible={visibleBuyCard}
        goodsList={dataInfo.GoodsList}
        payType={payType}
        onCloseModel={handleCloseBuy}
        handleCheckPay={handleClickPay}
      />
      <UploadInfoModel
        visible={visibleUpload}
        onCloseModel={handleCloseUpload}
        handleSuccess={handleUploadCardSuccess}
      />
      <ApplyPermission
        visible={visibleApply}
        detailID={
          tryType === ITryType.Article
            ? (dataInfo as IArcticleInfo).Detail.ArticleId
            : tryType === ITryType.YanxuanSpecial
            ? (dataInfo as IColumnDetail).Detail.Id
            : (dataInfo as IActivityTypeDetailRes).Detail.ActivityId
        }
        tryType={tryType}
        onCloseModel={handleCloseApply}
      />
    </>
  )
}

export default PayProcessModel
