import { View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { memo, useEffect, useMemo, useState } from 'react'
import classnames from 'classnames'
import styles from '../css/linkBlueTooth.module.scss'
import Popup from './Popup'
import { useBluetooth } from '@/use/contextBlueTooth'
import SearchInput from '@/components/searchInput'

const LinkBlueTooth = () => {
  const { state, init, startScan, connect, disconnect } = useBluetooth()

  useEffect(() => {
    init()
  }, [])

  const [linkStatus, setLinkStatus] = useState(1)
  useEffect(() => {
    if (!state.available) {
      setLinkStatus(1)
    }
    else if (state.available && state.connected?.name) {
      setLinkStatus(3)
    }
    else {
      setLinkStatus(2)
    }
  }, [state.available, state.connected])

  const linkName = useMemo(() => {
    console.log('state linkName', state)
    return state.connected?.localName || ''
  }, [state.connected])

  // 链接设备
  const onLinkListen = (item) => {
    if (!state.connected && !state.connecting) { connect(item) }
  }
  const onFindEven = () => {
    if (!state.discovering && !state.connected && !state.connecting) { startScan() }
  }
  const [popupShow, setPopupShow] = useState(false)
  // 显示设备列表
  const onFindDevice = () => {
    console.log('linkStatus==>', linkStatus)
    if (linkStatus == 1) {
      Taro.showToast({
        title: '请打开蓝牙',
        icon: 'none',
      })
    }
    else {
      setPopupShow(true)
      onFindEven()
    }
  }

  // 断开链接
  const onDisconnect = () => {
    disconnect()
    setPopupShow(false)
  }

  return (
    <>
      <View className={styles.main}>
        <SearchInput title="蓝牙设备" showIcon showBorder={false}>
          <View className={styles.bluetooth_link} onClick={onFindDevice}>
            <View className={classnames(styles.link_status, linkStatus == 3 && styles.link_statused, linkStatus == 2 && styles.link_statused_no)}></View>
            {(linkStatus == 1 && <View className={classnames(styles.link_name, styles.link_name_no)}>请开启蓝牙</View>)
              || (linkStatus == 2 && <View className={classnames(styles.link_name, styles.link_name_no_link)}>未连接设备</View>)
              || (linkStatus == 3 && <View className={classnames(styles.link_name)}>{linkName}</View>)}
          </View>
        </SearchInput>
        <Popup
          state={state}
          show={popupShow}
          onClose={() => setPopupShow(false)}
          onLink={item => onLinkListen(item)}
          onOff={onDisconnect}
          onFind={onFindEven}
        />
      </View>
    </>
  )
}
export default memo(LinkBlueTooth)
