import {FC, useCallback, useEffect, useRef, useState} from "react";
import {Form, Image, Input, View} from "@tarojs/components";
import {Profile} from "@/store";
import {userApi} from "@/api";
import Taro from "@tarojs/taro";
import {regexTel} from "@/utils/regu";
import styles from './check.module.scss'
import code from '@/static/img/vCode.png'
import tel from '@/static/img/tel.png'
import MyButton from "@/components/button/MyButton";

const Bing: FC = () => {
  const form = useRef<HTMLFormElement | null>(null)
  const [loading, setLoading] = useState(false)
  const [codeTime, setCodeTime] = useState(0)
  const {setUser, setToken, setCompany} = Profile.useContainer()
  const [openid, setOpenId] = useState('')
  const [phone_number, setPhone_number] = useState<number | null>()

  useEffect(() => {
    if (codeTime > 0) {
      setTimeout(() => {
        setCodeTime(codeTime - 1)
      }, 1000)
    }
  }, [codeTime])

  Taro.useLoad(() => {
    if (process.env.TARO_ENV === 'h5') {
      setOpenId(localStorage.getItem('openid') || '')
    } else {
      setOpenId(Taro.getStorageSync('openid'))
    }
  })

  async function Submit(data) {
    setLoading(true)
    const value = data.target.value
    if (!regexTel.exec(value.phone_number)) {
      Taro.showToast({title: '手机号错误', icon: 'error'})
      setLoading(false)
      return
    }
    try {
      const res = await userApi.checkout({
        ...value,
        openid,
      })
      if (res) {
        setCompany(res.company)
        setUser(res.user)
        setToken(res.token)
        Taro.switchTab({url: '/pages/home/home'})
      }
    } catch (e) {
    }
    setLoading(false)
  }

  const getCode = useCallback(async () => {
    if (codeTime > 0) return;
    if (!phone_number || !regexTel.exec(String(phone_number))) {
      Taro.showToast({title: '手机号错误', icon: 'error'})
      setLoading(false)
      return
    }

    try {
      await userApi.getCode(phone_number)
      Taro.showToast({title: '请注意查收', icon: "none"})
      setCodeTime(60)
    } catch (e) {
      Taro.showToast({title: '获取短信验证码失败', icon: "error"})
    }
  }, [codeTime, phone_number])

  return (
    <View className={styles.page}>
      <Form onSubmit={Submit} ref={form}>

        <View className={styles.formItem}>
          <View>
            <Image src={tel} className={styles.image}/>
          </View>
          <Input
            type='number'
            name='phone_number'
            placeholder={'请输入手机号'}
            value={phone_number as unknown as string}
            onInput={(e) => setPhone_number(Number(e.detail.value))}/>
        </View>

        <View className={styles.formItem}>
          <View>
            <Image src={code} className={styles.image}/>
          </View>

          <View className='flex align-center flex-1'>
            <Input type='number' name='code' className='flex-1' placeholder='请输入短信验证码'/>
            <View onClick={getCode}>
              {codeTime > 0 ? `${codeTime}` : '获取验证码'}
            </View>
          </View>
        </View>

        <MyButton
          className={styles.submit}
          style={{margin: '30px auto'}}
          formType='submit'
          disabled={loading}
        >
          提交
        </MyButton>
      </Form>
    </View>
  )
}


export default Bing;
