<template>
  <view class="register-container">
    <view class="gradient"></view>
    <u-card :show-head="false" margin="0" border-radius="24">
      <template #body>
        <view class="body">
          <view class="title">学员注册</view>
          <u-form :model="data.formData" ref="form" label-width="0">
            <u-form-item label="" prop="FName"
              ><u-input
                v-model="data.formData.FName"
                placeholder="请输入学员姓名"
            /></u-form-item>
            <u-form-item label="" prop="FSex">
              <u-radio-group v-model="data.formData.FSex">
                <u-radio
                  v-for="(item, index) in data.radioList"
                  :key="index"
                  :name="item.name"
                >
                  {{ item.name }}
                </u-radio>
              </u-radio-group>
            </u-form-item>
            <u-form-item label="" prop="FWorkUnit"
              ><u-input
                v-model="data.formData.FWorkUnit"
                placeholder="选择工作单位"
            /></u-form-item>
            <u-form-item label="" prop="FDuties"
              ><u-input
                v-model="data.formData.FDuties"
                placeholder="请输入单位职务"
            /></u-form-item>
            <u-form-item label="" prop="FMobile"
              ><u-input
                v-model="data.formData.FMobile"
                placeholder="请输入手机号码"
            /></u-form-item>
            <u-form-item label="" prop="code"
              ><u-input
                v-model="data.formData.code"
                placeholder="请输入验证码"
                :disabled="data.codeDisabled"
              />
              <template #right>
                <u-verification-code
                  seconds="60"
                  @start="start"
                  ref="uCode"
                  @change="codeChange"
                ></u-verification-code>
                <view @tap="getCode" :disabled="data.codeDisabled" class="code">
                  {{ data.tips }}
                </view>
              </template>
            </u-form-item>
          </u-form>

          <view class="footer">
            <u-button @click="submit" size="medium" type="primary"
              >注册并登录</u-button
            >
            <view
              style="
                text-align: end;
                font-size: 26rpx;
                margin: 20rpx 0;
                color: #07a9ff;
              "
            >
              <text style="border-bottom: 1rpx solid #05a8ff" @tap="toLogin"
                >已有账号</text
              >
            </view>
          </view>
        </view>
      </template>
    </u-card>
  </view>
</template>

<script setup lang="ts">
import { toast, decrypt } from "@/utils/util";
import { register, verification } from "@/api/login";
import { useStudentStore } from "@/stores/modules/studentStore";

const form = ref();
const globalStore = useStudentStore();
const uCode = ref();
const uniA: any = uni;
const data = reactive({
  formData: {
    FMobile: "",
    code: "",
    FName: "",
    FDuties: "",
    FSex: "男",
    FWorkUnit: "",
    FOPENID: globalStore.openId, //openid
    FSTUDENTID: 0,
  },
  selectShow: false,
  radioList: [
    {
      name: "男",
    },
    {
      name: "女",
    },
  ],
  rules: {
    FMobile: [
      {
        required: true,
        message: "请输入手机号",
        trigger: ["blur"],
      },
      {
        // 自定义验证函数，见上说明
        validator: (rule: any, value: any, callback: any) => {
          return uniA.$u.test.mobile(value);
        },
        message: "手机号码不正确",
        // 触发器可以同时用blur和change
        trigger: ["blur"],
      },
    ],
    FName: [
      {
        required: true,
        message: "请输入学员姓名",
        trigger: ["blur"],
      },
    ],
    FDuties: [
      {
        required: true,
        message: "请输入单位职务",
        trigger: ["blur"],
      },
    ],
    FWorkUnit: [
      {
        required: true,
        message: "请输入工作单位",
        trigger: ["blur"],
      },
    ],
    code: [
      {
        required: true,
        message: "请输入验证码",
        trigger: ["blur"],
      },
    ],
  },
  tips: "",
  codeDisabled: true,
  flag: true,
  codeValue: "",
});

watch(
  () => data.formData.FMobile,
  (newVal: string) => {
    if (newVal && uniA.$u.test.mobile(newVal)) {
      data.codeDisabled = false;
    } else data.codeDisabled = true;
  }
);

const toLogin = () => {
  uni.navigateTo({
    url: "/pages/login/index",
  });
};

const getCode = async () => {
  if (data.codeDisabled || uniA.$u.test.mobile(data.formData.code))
    return toast("手机号为空或手机号格式不正确");
  if (uCode.value.canGetCode) {
    // 模拟向后端请求验证码
    const { data: res }: any = await verification(data.formData.FMobile);
    let timer: ReturnType<typeof setTimeout>;
    uni.showLoading({
      title: "正在获取验证码",
    });
    if (res.code == 200) {
      data.codeValue = decrypt(res.data);
      setTimeout(() => {
        uni.hideLoading();
        clearTimeout(timer);
        timer = setTimeout(() => {
          data.flag = false;
        }, 300000);
        // 这里此提示会被this.start()方法中的提示覆盖
        toast("验证码已发送");
        // 通知验证码组件内部开始倒计时
        uCode.value.start();
      }, 1000);
    } else uni.hideLoading();
  } else {
    toast("倒计时结束后再发送");
  }
};

const codeChange = (text: string) => {
  data.tips = text;
};
const start = () => {};

onReady(() => {
  form.value.setRules(data.rules);
});

const submit = () => {
  let state = {
    type: 1,
    parmeters: {
      NeedUpDateFields: [
        "FName",
        "FSex",
        "FMobile",
        "FDuties",
        "FRemark",
        "FOPENID",
        "FWorkUnit",
      ],
      IsDeleteEntry: "false",
      Model: data.formData,
    },
  };
  form.value.validate(async (valid: boolean) => {
    if (valid) {
      if (!data.flag) return toast("验证码失效");
      if (data.formData.code != data.codeValue) return toast("验证码不正确");
      data.formData.FSex = data.formData.FSex === "男" ? "0" : "1";
      const { data: res }: any = await register(state);
      if (res.code == 200) {
        globalStore.setInfoData(res.data[0]);
        uni.reLaunch({ url: "/pages/home/index" });
        toast("注册成功");
      } else {
        data.formData.FSex = data.formData.FSex === "0" ? "男" : "女";
      }
    }
  });
};
</script>

<style lang="scss" scoped>
.gradient {
  width: 100%;
  height: 400rpx;
  background: linear-gradient(to bottom, #91cefd, #d3ecfe);
}

.register-container {
  position: relative;
  width: 100%;
  background-color: #ffffff;
  .u-card {
    position: absolute;
    top: 220rpx;
    left: 32rpx;
    width: 92%;
    // padding: 0 32rpx;
  }
  .body {
    .title {
      height: 62rpx;
      font-size: 44rpx;
      font-weight: 500;
      color: #222222;
      line-height: 52rpx;
      margin-top: 60rpx;
      margin-bottom: 48rpx;
      color: #222222;
    }
  }

  .footer {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 30rpx;
    .u-btn {
      width: 100%;
      height: 96rpx;
      background: #05a8ff;
      border-radius: 16rpx;
      opacity: 1;
    }
  }
}
</style>
