<template>
  <section class="login">
    <u-form :model="form" ref="loginForm" label-width="140">
      <u-form-item label="账号" prop="phone" :errory-type="['message']">
        <u-input v-model="form.phone" placeholder="请输入手机号"/>
      </u-form-item>
      <u-form-item label="验证码" prop="vcode">
        <u-input v-model="form.vcode" placeholder="请输入短信验证码"/>
        <u-verification-code ref="vcode" secords="60" @change="v=>tips=v"/>
        <div class="vcode" @tap="$u.debounce(getVCode)">{{ tips }}</div>
      </u-form-item>
    </u-form>
    <div bottom>
      <u-button type="primary" @tap="handleLogin">绑定并登录</u-button>
    </div>
  </section>
</template>

<script>
import {mapActions, mapState} from "vuex";

export default {
  name: "login",
  inject: ['root'],
  computed: {
    ...mapState(['lastPage']),
    rules() {
      return {
        phone: [{required: true, message: "请选择分组"}],
        vcode: [{required: true, message: "请选择快捷回复类型"}],
      }
    }
  },
  data() {
    return {
      form: {},
      tips: ''
    }
  },
  methods: {
    ...mapActions(['getCode']),
    getVCode() {
      if (this.form.phone) {
        this.$http.post("/admin/user/sendCode", null, {
          withoutToken: 1,
          params: {phone: this.form.phone}
        }).then(() => {
          this.$u.toast("验证已发送!")
          this.$refs.vcode?.start()
        })
      } else {
        this.$u.toast("请先填写手机号!")
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(v => {
        if (v) {
          let params = {
            ...this.form, code: this.$route.query?.code, then: res => {
              let last = uni.getStorageSync("lastApp")
              if (last) {
                this.$store.commit("login", [res?.token_type, res?.access_token].join(" ").trim())
                uni.removeStorageSync("lastApp")
                // this.root.getCode(location.origin + last)
                uni.reLaunch({url: "./loading?app=" + last})
              } else this.$u.toast("绑定成功,请重新打开应用页面!")
            }
          }
          this.$store.commit("bindAccount", params)
        }
      })
    }
  },
  created() {
    !this.$route.query?.code && this.getCode()
  },
  mounted() {
    this.$nextTick(() => this.$refs.loginForm?.setRules(this.rules))
  }
}
</script>

<style lang="scss" scoped>
.login {
  border-top: 1px solid #D4D4D4;
  padding: 0 0 208px;
  background: #F5F5F5;
  box-sizing: border-box;
  height: 100%;

  .vcode {
    color: $uni-color-primary;
    cursor: pointer;
  }
}
</style>
