import { useState } from 'react'
import Taro from '@tarojs/taro'
import withLayout from '@/layout'
import { ScrollView, Input } from '@tarojs/components'
import { fetch } from '@/utils/request'
import { API_REGISTER_AGENT } from '@/constants/api'
import { UPDATE_USER_INFO } from '@/constants/user'
import store from '@/store'
import './index.scss'

export default withLayout(() => {

  const [Code, setCode] = useState('')
  const { dispatch } = store

  const ToSubmit = () => {
    if (Code !== '') {
      fetch({ url: `${API_REGISTER_AGENT}?channelCode=${Code}`, method: 'put' }).then(() => {
        Taro.showToast({ title: '绑定成功', icon: 'none', duration: 2000 })
        dispatch({ type: UPDATE_USER_INFO, payload: { personType: 'channel agent' } })
        setTimeout(() => {
          Taro.navigateBack({ delta: 1 })
        }, 1200)
      })
    } else {
      Taro.showToast({
        title: '请输入渠道验证码',
        icon: 'none'
      })
    }
  }

  const CodeChange = (e) => {
    setCode(e.detail.value)
  }

  return (
    <view className='Page toBeAgent'>

      <ScrollView scroll-y>
        <view className='PageContent'>

          <view className='Input'>
            <Input placeholder='请输入渠道验证码 (必填)' onInput={CodeChange}></Input>
          </view>

          <view className='Btn'>
            <text onClick={ToSubmit}>提交</text>
          </view>

        </view>
      </ScrollView>

    </view>
  )
})
