import { CoverView, Image, Input, Swiper, SwiperItem, Text, View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import type { Ref } from 'react'
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react'
import classnames from 'classnames'
import Dialog from '../Dialog'
import NormalButton from '../normalButton'
import LayoutBlock from '../layoutBlock'
import IconText from '../iconText'
import IconFont from '../iconfont/iconfont'
import InputX from '../InputX'
import styles from './index.module.scss'
import { formatImgUrl } from '@/common/fotmat'
import { alert, goLink } from '@/common/common'
import CloseBtn from '@/components/closeBtn'
import { getCDNSource } from '@/common/constant'
import { getFilterData } from '@/common/util'
import { BindInvitationInfoApi, GetInvitationInfoApi } from '@/api/user'
// 获取业务员信息
interface Param { invitation_code: string; name: string; phone: string }
interface params {
  onSuccess?: () => void
}
interface SalesManDialogRef {
  show: boolean
  handleChange: (show: boolean) => void
}
const BindSalesManDialog = ({ onSuccess }: params, ref: Ref<SalesManDialogRef>) => {
  const [isError, setError] = useState(false)
  const [show, setShow] = useState(false)
  const [submitData, setSubmitData] = useState({
    invitation_code: '',
  })
  const [salesMan, setSalesMan] = useState<Param | null>(null)
  const { fetchData: GetInvitationInfoFetchData } = GetInvitationInfoApi()
  const getInvitationInfo = async() => {
    const res = await GetInvitationInfoFetchData({ invitation_code: submitData.invitation_code })
    if (res.success) {
      setSalesMan(res.data)
      setError(false)
    }
    else {
      setSalesMan(null)
      setError(true)
    }
  }
  const onInputCode = (e) => {
    const value = e.detail.value.replace(/[\W]/g, '')
    if (value === '') {
      setError(false)
      setSubmitData({ invitation_code: '' })
    }
    else {
      setSubmitData(val => ({ ...val, invitation_code: value }))
    }
  }
  const oncloseEven = () => {
    setSubmitData(val => ({ ...val, invitation_code: '' }))
    setSalesMan(null)
    setError(false)
  }
  const handleChange = (value) => {
    setShow(value)
  }
  const onCloseEven = () => {
    handleChange(false)
  }
  const { fetchData: bindInvitationInfoFetchData } = BindInvitationInfoApi()
  const handleConfirm = async() => {
    if (!submitData.invitation_code) { return alert.error('请输入邀请码') }
    const res = await bindInvitationInfoFetchData({ ...submitData })
    if (!res.success) {
      console.log('res', res)
      setError(true)
    }
    else {
      onCloseEven()
      onSuccess?.()
    }
  }
  const onScanCode = () => {
    Taro.scanCode({
      success: (res) => {
        const val = res.result.match(/InviteCode:([a-zA-Z0-9]{4})/)
        setSubmitData(() => ({ invitation_code: val ? val![1] : '' }))
      },
    })
  }

  // 获取粘贴版内容
  const onClipboardData = () => {
    Taro.getClipboardData({
      success(res) {
        const val = res.data.match(/InviteCode:([a-zA-Z0-9]{4})/)
        if (val) { setSubmitData(e => ({ ...e, invitation_code: val ? val[1] : '' })) }
      },
    })
  }
  useEffect(() => {
    if (show) {
      onClipboardData()
    }
  }, [])

  useEffect(() => {
    if (submitData.invitation_code.length === 4) { getInvitationInfo() }
  }, [submitData])
  useImperativeHandle(
    ref,
    () => {
      return {
        show,
        handleChange,
      }
    },
    [show],
  )
  const onCustomer = async() => {
    const res = await Taro.showModal({
      title: '是否拨打服务热线',
      confirmText: '拨打',
      content: '(0757) 8270 6695',
      cancelText: '取消',
    })
    if (res.confirm) {
      Taro.makePhoneCall({
        phoneNumber: '(0757)82706695',
      })
    }
  }
  return (
    <Dialog show={show} onClose={onCloseEven} onChange={handleChange} >
      <View className={styles.inviteCodeDialog}>
        <View className={styles.background}>
          <View className={styles.left}>
            <View className={styles.title}>陆盈商城服务</View>
            <View className={styles.description}>欢迎使用！填写邀请码</View>
          </View>
          <View className={styles.right}>
            <View className={styles.iconContainer}>

              <Image className={styles.icon} src={getCDNSource('/user/inviteCode.png')} mode="widthFix" />
            </View>
          </View>
        </View>
        <View className={styles.content}>

          <LayoutBlock circle>
            <View className={styles.inputCode}>
              <Input
                className={isError ? styles.error : ''}
                alwaysEmbed
                cursorSpacing={150}
                maxlength={4}
                value={submitData.invitation_code}
                placeholder="请输入邀请码"
                onInput={onInputCode}
                type="text"
              />
              <View className={styles.close_btn}>
                {submitData.invitation_code && <CloseBtn styleObj={{ backgroundColor: '#ccc', color: '#fff' }} onClose={oncloseEven} />}
              </View>
              <View className={styles.scan_code} onClick={() => onScanCode()}>
                <IconFont name="icon-gongnengtubiao-saomiao" size={48} color="#c2c3c5"></IconFont>
              </View>
            </View>
            {(salesMan && !isError) ? <View className={styles.salesMan}>邀请人：{salesMan?.name} {salesMan?.phone}</View> : null}
            {(submitData.invitation_code && isError) ? <View className={classnames(styles.salesMan, styles.error)}>邀请码错误</View> : null}
            <View className={styles.tipsGroup}>
              <View className={styles.tips}>1、联系自己的专属客户经理获取邀请码</View>
              <View className={styles.tips} onClick={onCustomer}><View>2、私聊客服进行获取-</View><IconText svg iconSize={24} text="联系客服" direction="right" iconName="icon-rukou" textCustomStyle={{ color: '#337FFF', fontSize: '24rpx', padding: '0' }} color="#337FFF"></IconText></View>
            </View>
          </LayoutBlock>
          <View className={styles.bottomBar}>
            <NormalButton type="primary" customTextClassName={styles.bottomBar__text} customClassName={styles.bottomBar__button} customStyles={{ width: '100%' }} onClick={handleConfirm}>
              确定
            </NormalButton>
          </View>
        </View>
      </View>
    </Dialog>
  )
}

export default forwardRef(BindSalesManDialog)
