import { defineComponent } from 'vue'
import { CellGroup, Field, Button, CountDown, Row, Col, Toast } from 'vant'
import ImgCode from '@/components/col-img-code'
import { checkPhone } from '@/helpers/validate'
import request from '@/student/home-layout-orchestra/request-home'
import { setLogin, state } from '@/state'
import { removeAuth, setAuth } from '@/helpers/utils'
import styles from './login.module.less'
import ColHeader from '@/components/col-header'

export default defineComponent({
  name: 'login',
  data() {
    return {
      username: '',
      password: '',
      smsCode: '',
      countDownStatus: true, // 是否发送验证码
      countDownTime: 1000 * 120, // 倒计时时间
      countDownRef: null as any, // 倒计时实例
      imgCodeStatus: false
    }
  },
  computed: {
    codeDisable() {
      let status = true

      this.username && this.smsCode && (status = false)
      return status
    }
  },
  mounted() {
    removeAuth()
    this.directNext()
  },
  methods: {
    directNext() {
      if (state.user.status === 'login' || state.user.status === 'error') {
        const { returnUrl, isRegister, ...rest } = this.$route.query
        this.$router.replace({
          path: '/home',
          query: {
            ...rest
          }
        })
      }
    },
    async onLogin() {
      try {
        const res = await request.post('/api-auth/smsLogin', {
          requestType: 'form',
          data: {
            clientId: 'student',
            clientSecret: 'student',
            phone: this.username,
            smsCode: this.smsCode,
            isSurportRegister: true
          }
        })

        const { authentication } = res.data
        setAuth(authentication.token_type + ' ' + authentication.access_token)
        postMessage({
          api: 'setCache',
          content: {
            key: 'h5-colexiu-token',
            value: authentication.token_type + ' ' + authentication.access_token
          }
        })
        const userCash = await request.get(
          '/api-student/student/queryUserInfo',
          {
            initRequest: true // 初始化接口
          }
        )
        setLogin(userCash.data)
        // 调用原生api去关联账号
        postMessage({
          api: 'bindUserAccount',
          content: { phone: this.username }
        })

        this.directNext()
      } catch {
        //
      }
    },
    async onSendCode() {
      // 发送验证码
      if (!checkPhone(this.username)) {
        return Toast('请输入正确的手机号码')
      }
      this.imgCodeStatus = true
    },
    onCodeSend() {
      this.countDownStatus = false
      this.countDownRef.start()
    },
    onFinished() {
      this.countDownStatus = true
      this.countDownRef.reset()
    }
  },
  render() {
    return (
      <div class={styles.login}>
        <ColHeader border={false} background="transparent" title=" " isBack />
        <div class={styles.loginTitle}>
          您好，
          <br /> 欢迎使用酷乐秀
        </div>
        <CellGroup class={styles.margin34} border={false}>
          <Row style={{ marginBottom: '16px' }}>
            <Col span={24} class={styles.formTitle}>
              手机号
            </Col>
            <Col span={24} class="van-hairline--bottom">
              <Field
                v-model={this.username}
                name="手机号"
                placeholder="请输入您的手机号"
                type="tel"
                maxlength={11}
              />
            </Col>
          </Row>

          <Row>
            <Col span={24} class={styles.formTitle}>
              验证码
            </Col>
            <Col span={24} class="van-hairline--bottom">
              <Field
                v-model={this.smsCode}
                name="验证码"
                placeholder="请输入验证码"
                type="tel"
                maxlength={6}
                v-slots={{
                  button: () =>
                    this.countDownStatus ? (
                      <span class={styles.codeText} onClick={this.onSendCode}>
                        获取验证码
                      </span>
                    ) : (
                      <CountDown
                        ref={this.countDownRef}
                        auto-start={false}
                        time={this.countDownTime}
                        onFinish={this.onFinished}
                        format="ss秒"
                      />
                    )
                }}
              />
            </Col>
          </Row>
        </CellGroup>
        <div class={styles.margin34}>
          <Button
            round
            block
            type="primary"
            disabled={this.codeDisable}
            onClick={this.onLogin}
          >
            登录
          </Button>
        </div>

        {this.imgCodeStatus ? (
          <ImgCode
            v-model:value={this.imgCodeStatus}
            phone={this.username}
            onClose={() => {
              this.imgCodeStatus = false
            }}
            onSendCode={this.onCodeSend}
          />
        ) : null}
      </div>
    )
  }
})
