<!-- @format -->

<template>
  <view class="container">
    <u-alert
      type="warning"
      :show-icon="true"
      title="第一次用微信登录需要绑定用户，如果没有账号请先到登录页进行注册。"
    ></u-alert>
    <u-form ref="uForm" :model="form" labelWidth="160" labelPosition="top">
      <u-form-item :required="true" label="用户名" prop="name">
        <u-input placeholder="请输入用户名" v-model="form.name"></u-input>
      </u-form-item>
      <u-form-item :required="true" label="密码" prop="password">
        <u-input
          type="password"
          placeholder="请输入密码"
          v-model="form.password"
        >
        </u-input>
      </u-form-item>
      <u-form-item>
        <u-button type="primary" @click="onSubmit">绑定</u-button>
      </u-form-item>
    </u-form>
  </view>
</template>
<script>
import { wxBindUser } from "@/api/login";
export default {
  data() {
    return {
      form: {
        openid: null,
        name: null,
        password: null,
        unionid: null,
      },
      rules: {
        name: [
          {
            required: true,
            message: "用户名不能为空",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "密码不能为空",
            trigger: "blur",
          },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              if (value.trim().length < 8) {
                callback(new Error("密码长度不能低于8位"));
              } else {
                callback();
              }
            },
            // 触发器可以同时用blur和change
            trigger: ["change", "blur"],
          },
        ],
      },
    };
  },
  onReady() {
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    this.$refs.uForm.setRules(this.rules);
  },
  onLoad(options) {
    this.form.openid = options.openid;
    this.form.unionid = options.unionId;
  },
  methods: {
    onSubmit() {
      this.$refs.uForm.validate().then(async (res) => {
        try {
          uni.showLoading({
            title: "提交中....",
          });
          await wxBindUser(this.form);
          uni.showToast({
            title: "绑定完成,请重新登录",
            //将值设置为 success 或者直接不用写icon这个参数
            icon: "success",
            //显示持续时间为 2秒
            duration: 2000,
          });
          uni.navigateBack({
            delta: 1,
          });
        } catch (error) {
        } finally {
        }
      });
    },
  },
};
</script>
<style lang="scss">
.container {
  height: 100vh;
  background: rgb(248, 249, 250);
  padding: 30rpx;
}
</style>
