import { defineComponent } from 'vue'
import { CellGroup, Field, Button, CountDown, Row, Col, Toast, Checkbox, Icon } from 'vant'
import ImgCode from '@/components/col-img-code'
import { checkPhone } from '@/helpers/validate'
import request from '@/helpers/request'
import { setLogin, state } from '@/state'
import { removeAuth, setAuth } from '@/helpers/utils'
import styles from './login-cert.module.less'
import topBg from './image-cert/top.png'
import activeButtonIcon from '@common/images/icon_checkbox.png'
import inactiveButtonIcon from './images/icon_checkbox.png'

export default defineComponent({
  name: 'login',
  data() {
    return {
      checked: false,
      username: '',
      password: '',
      smsCode: '',
      countDownStatus: true, // 是否发送验证码
      countDownTime: 1000 * 120, // 倒计时时间
      imgCodeStatus: false
    }
  },
  computed: {
    codeDisable() {
      let status = true
        this.username && this.smsCode && this.checked && (status = false)
      
      return status
    }
  },
  created() {
    document.title = '酷乐秀学院老师入驻'
  },
  mounted() {
    removeAuth()
    const userInfo = sessionStorage.getItem('login-cert-store')
    if(userInfo) {
      const parseUser = JSON.parse(userInfo)
      this.username = parseUser.username;
      this.smsCode = parseUser.smsCode
      sessionStorage.removeItem('login-cert-store')
    }
    this.directNext()
  },
  methods: {
    previewProtocol(type: string) {
      sessionStorage.setItem('login-cert-store', JSON.stringify({
        username: this.username,
        smsCode: this.smsCode,
      }))
      if (type === 'user') {
        this.$router.push({
          path: '/registerProtocol',
          query: {
            showHeader: 1
          }
        })
      } else if (type === 'privacy') {
        this.$router.push({
          path: '/privacyProtocol',
          query: {
            showHeader: 1
          }
        })
      }
    },
    directNext() {
      if (state.user.status === 'login' || state.user.status === 'error') {
        const { returnUrl, isRegister, ...rest } = this.$route.query
        this.$router.replace({
          path: '/teacherCert',
          query: {
            ...rest
          }
        })
      }
    },
    async onLogin() {
      try {
        let res = await request.post('/api-auth/smsLogin', {
            requestType: 'form',
            data: {
              clientId: 'teacher',
              clientSecret: 'teacher',
              phone: this.username,
              smsCode: this.smsCode,
              isSurportRegister: true
            }
          })

        const { authentication } = res.data
        setAuth(authentication.token_type + ' ' + authentication.access_token)

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

        this.directNext()
      } catch {}
    },
    async onSendCode() {
      // 发送验证码
      if (!checkPhone(this.username)) {
        return Toast('请输入正确的手机号码')
      }
      this.imgCodeStatus = true
    },
    onCodeSend() {
      this.countDownStatus = false
      this.$nextTick(() => {
        ;(this.$refs.countDownRef as any).start()
      })
    },
    onFinished() {
      this.countDownStatus = true
      ;(this.$refs.countDownRef as any).reset()
    },
  },
  render() {
    return (
      <div class={styles.login}>
        <img src={topBg} class={styles.topBg} />
        <div class={styles.content}>
          <CellGroup class={styles.cellGroup} 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}
                  // @ts-ignore
                  vSlots={{
                    button: () =>
                      this.countDownStatus ? (
                        <span class={styles.codeText} onClick={this.onSendCode}>
                          发送验证码
                        </span>
                      ) : (
                        <CountDown
                          ref='countDownRef'
                          auto-start={false}
                          time={this.countDownTime}
                          onFinish={this.onFinished}
                          format="ss秒"
                        />
                      )
                  }}
                />
              </Col>
            </Row>
          </CellGroup>
        </div>
        <div class={styles.margin34}>
          <div class={styles.protocol}>
            <Checkbox
              v-model={this.checked}
              v-slots={{
                icon: (props: any) => (
                  <Icon
                    class={styles.boxStyle}
                    name={props.checked ? activeButtonIcon : inactiveButtonIcon}
                    size="15"
                  />
                )
              }}
            >
              我已阅读并同意
            </Checkbox>
            <span class={styles.lastText}>
              <span
                class={styles.protocolText}
                onClick={() => {
                  this.previewProtocol('user')
                }}
              >
                《用户注册协议》
              </span>
              和
              <span
                class={styles.protocolText}
                onClick={() => {
                  this.previewProtocol('privacy')
                }}
              >
                《隐私政策》
              </span>
            </span>
          </div>
          <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>
    )
  }
})
