import { Teleport, defineComponent, reactive, ref } from 'vue'
import styles from './index.module.less'
import { Button, CountDown, Field, Toast } from 'vant'
import iconPhone from './images/icon-phone.png'
import iconPassword from './images/icon-password.png'
import { checkPhone, setAuth } from '@/helpers/utils'
import request from '@/helpers/request'
import { setLogin, state } from '@/state'
import MImgCode from '@/components/col-img-code'
import { nextTick } from 'process'

type loginType = 'PWD' | 'SMS'
export default defineComponent({
  name: 'login-model',
  props: {
    /** 是否支持短信验证码注册 */
    isRegister: {
      type: Boolean,
      default: false
    }
  },
  emits: ['close', 'confirm'],
  setup(props, { emit }) {
    const countDownRef = ref()
    const state = reactive({
      loginType: 'PWD' as loginType,
      imgCodeStatus: false,
      username: '',
      password: '',
      smsCode: '',
      countDownStatus: true,
      countDownTime: 1000 * 120 // 倒计时时间
    })

    const onLogin = async () => {
      try {
        if (!checkPhone(state.username)) {
          return Toast('请输入正确的手机号码')
        }
        if (state.loginType === 'PWD') {
          const { data } = await request.post('/api-auth/usernameLogin', {
            requestType: 'form',
            data: {
              username: state.username,
              password: state.password,
              clientId: 'student',
              clientSecret: 'student'
            }
          })
          setAuth(
            data.authentication.token_type +
              ' ' +
              data.authentication.access_token
          )
        } else {
          const { data } = await request.post('/api-auth/smsLogin', {
            requestType: 'form',
            data: {
              clientId: 'student',
              clientSecret: 'student',
              phone: state.username,
              smsCode: state.smsCode,
              isSurportRegister: props.isRegister
            }
          })
          setAuth(
            data.authentication.token_type +
              ' ' +
              data.authentication.access_token
          )
        }

        const userCash = await request.get(
          '/api-student/student/queryUserInfo',
          {
            initRequest: true // 初始化接口
          }
        )
        setLogin(userCash.data)

        emit('confirm', true)
      } catch (e: any) {
        //
        console.log(e)
      }
    }

    const onSendCode = () => {
      // 发送验证码
      if (!checkPhone(state.username)) {
        return Toast('请输入正确的手机号码')
      }
      state.imgCodeStatus = true
    }

    const onCodeSend = () => {
      state.countDownStatus = false
      nextTick(() => {
        console.log(countDownRef.value, 'countDownRef.value')
        countDownRef.value.start()
      })
    }
    const onFinished = () => {
      state.countDownStatus = true
      countDownRef.value.reset()
    }
    return () => (
      <div class={styles.loginModel}>
        <i class={styles.iconClose} onClick={() => emit('close')}></i>
        <div class={styles.loginSection}>
          <div class={styles.fieldSection}>
            <Field
              v-model={state.username}
              placeholder="请输入手机号"
              autocomplete="off"
              border={false}
              type="tel"
              maxlength={11}
            >
              {{
                'left-icon': () => <img src={iconPhone} class={styles.icon} />
              }}
            </Field>

            {state.loginType === 'PWD' ? (
              <Field
                v-model={state.password}
                placeholder="请输入密码"
                autocomplete="off"
                border={false}
                type="password"
              >
                {{
                  'left-icon': () => (
                    <img src={iconPassword} class={styles.icon} />
                  )
                }}
              </Field>
            ) : (
              <Field
                v-model={state.smsCode}
                placeholder="请输入验证码"
                autocomplete="off"
                maxlength={6}
                type="tel"
                border={false}
              >
                {{
                  'left-icon': () => (
                    <img src={iconPassword} class={styles.icon} />
                  ),
                  button: () =>
                    state.countDownStatus ? (
                      <span class={styles.codeText} onClick={onSendCode}>
                        获取验证码
                      </span>
                    ) : (
                      <CountDown
                        ref={(el: any) => (countDownRef.value = el)}
                        auto-start={false}
                        time={state.countDownTime}
                        onFinish={onFinished}
                        format="ss秒"
                      />
                    )
                }}
              </Field>
            )}
          </div>

          <div class={styles.btnGroup}>
            <Button round block color="#2DC7AA" onClick={onLogin}>
              登录
            </Button>

            <span
              class={styles.btnText}
              onClick={() => {
                if (state.loginType === 'PWD') {
                  state.countDownStatus = true
                  state.loginType = 'SMS'
                } else {
                  state.loginType = 'PWD'
                }
              }}
            >
              {state.loginType === 'PWD' ? '验证码登录' : '密码登录'}
            </span>
          </div>
        </div>

        {state.imgCodeStatus ? (
          <Teleport to={'body'}>
            <MImgCode
              v-model:value={state.imgCodeStatus}
              phone={state.username}
              onClose={() => {
                state.imgCodeStatus = false
              }}
              onSendCode={onCodeSend}
            />
          </Teleport>
        ) : null}
      </div>
    )
  }
})
