<template>
  <view style="position: relative">
    <view class="bg-header">
      <u-image
        src="../../static/img/background.png"
        width="100%"
        height="100%"
      />
    </view>
    <view class="logo">
      <u-image
        src="../../static/img/logo.png"
        width="100%"
        height="240rpx"
        mode="aspectFit"
      />
      <view class="logo-detail">培训系统</view>
    </view>

    <view class="container">
      <view class="content">
        <u-form :model="data.formData" ref="form" label-width="150">
          <u-form-item
            prop="phone"
            left-icon="../../static/img/icon_user.png"
            :left-icon-style="data.leftIconStyle"
          >
            <u-input v-model="data.formData.phone" placeholder="请输入手机号"
          /></u-form-item>
          <view class="yanzhenma">
            <u-form-item
              prop="code"
              left-icon="../../static/img/icon_yanzhenma.png"
              :left-icon-style="data.leftIconStyle"
              ><u-input
                v-model="data.formData.code"
                placeholder="请输入验证码"
                :disabled="data.codeDisabled"
              />
            </u-form-item>
            <u-verification-code
              seconds="60"
              ref="uCode"
              @change="codeChange"
            ></u-verification-code>
            <view @tap="getCode" :disabled="data.codeDisabled" class="code">
              {{ data.tips }}
            </view>
          </view>
        </u-form>
        <view class="footer">
          <u-button @click="submit" type="primary">登录</u-button>
          <view class="register">
            <text style="border-bottom: 1rpx solid #05a8ff" @tap="toRegister"
              >立即注册</text
            >
          </view>
        </view>
      </view>
    </view>
    <view v-if="hideshow" class="bg-footer">
      <u-image
        src="../../static/img/mask_group.png"
        width="100%"
        height="100%"
      />
    </view>
  </view>
</template>

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

const globalStore = useStudentStore();
const form = ref();
const uniA: any = uni;
const data = reactive({
  formData: {
    phone: "",
    code: "",
  },
  rules: {
    phone: [
      {
        required: true,
        message: "请输入手机号",
        trigger: ["blur"],
      },
      {
        // 自定义验证函数，见上说明
        validator: (rule: any, value: any, callback: any) => {
          return uniA.$u.test.mobile(value);
        },
        message: "手机号码不正确",
        // 触发器可以同时用blur和change
        trigger: ["blur"],
      },
    ],
    code: [
      {
        required: true,
        message: "请输入验证码",
        trigger: ["blur"],
      },
    ],
  },
  tips: "",
  codeDisabled: true,
  flag: true, // 判断5分钟内是否失效
  codeValue: "",
  type: 0,
  leftIconStyle: {
    width: "40rpx",
    height: "40rpx",
    display: "flex",
  },
});

const uCode = ref();
const showHeight = ref();
const hideshow = ref(true);
const docmHeight = document.documentElement.clientHeight;

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

onLoad((options: any) => {
  // 判断是否在微信浏览器
  let en: any = window.navigator.userAgent.toLowerCase();
  // 匹配en中是否含有MicroMessenger字符串
  if (en.match(/MicroMessenger/i) != "micromessenger") {
    // return "普通浏览器";
    return uni.reLaunch({ url: "/pages/prompt/index" });
  }
  if (options?.type) {
    data.type = options?.type;
  }
  window.onresize = () => {
    return (() => {
      showHeight.value = document.body.clientHeight;
    })();
  };
});

watch(
  () => showHeight.value,
  () => {
    if (docmHeight > showHeight.value) {
      hideshow.value = false;
    } else {
      hideshow.value = true;
    }
  }
);

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

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

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

const toRegister = () => {
  uni.navigateTo({ url: "/pages/login/register" });
};

const submit = () => {
  form.value.validate(async (valid: boolean) => {
    if (valid) {
      if (!data.flag) return toast("验证码失效");
      if (data.formData.code != data.codeValue) return toast("验证码不正确");
      if (data.type) {
        const state = {
          type: data.type,
          parmeters: {
            NeedUpDateFields: [
              "FName",
              "FSex",
              "FMobile",
              "FDuties",
              "FRemark",
              "FOPENID",
              "FWorkUnit",
            ],
            IsDeleteEntry: "false",
            Model: {
              FName: globalStore.infoData.FNAME, //姓名
              FSex: globalStore.infoData.FSEX, //性别0男1女
              FMobile: data.formData.phone, //手机
              FDuties: globalStore.infoData.FDUTIES, //职务
              FOPENID: globalStore.openId, //openid
              FWorkUnit: globalStore.infoData.FWORKUNIT1, //工作单位
              FRemark: "", //备注
              FSTUDENTID: globalStore.infoData.FSTUDENTID,
            },
          },
        };
        const { data: res }: any = await register(state);
        if (res.code == 200) {
          globalStore.setInfoData(res.data[0]);
          uni.navigateBack();
          toast("修改成功");
        }
      } else {
        const state = {
          Phone: data.formData.phone,
          OpenId: globalStore.openId,
        };
        const { data: res }: any = await loginCode(state);
        if (res.code == 200) {
          globalStore.setInfoData(res.data[0]);
          uni.reLaunch({ url: "/pages/home/index" });
          toast("登录成功");
          // 修改手机号的
        }
      }
    }
  });
};
</script>

<style lang="scss" scoped>
.container {
  position: absolute;
  top: 500rpx;
  left: 12%;
  z-index: 99;
  width: 568rpx;
  .content {
    width: 568rpx;
    height: 372rpx;
    .yanzhenma {
      display: flex;
      align-items: center;
      margin-top: 48rpx;
      .u-form-item {
        width: 392rpx;
      }
    }

    :deep(.u-form-item) {
      position: relative;
      // margin-bottom: 48rpx;
      background: #ffffff;
      padding: 6rpx 36rpx 0;
      box-shadow: 0rpx 8rpx 100rpx 0rpx rgba(0, 0, 0, 0.05);
      border-radius: 16rpx;
      height: 80rpx;
    }
    :deep(.u-form-item__message) {
      padding-left: 0 !important;
      margin-top: 20rpx;
    }
    .footer {
      height: 84rpx;
      margin-top: 64rpx;
      .u-btn {
        width: 100%;
        height: 100%;
        background-color: #04a7ff;
      }

      .register {
        text-align: center;
        font-size: 26rpx;
        margin: 20rpx 0;
        color: #07a9ff;
      }
    }
  }
}
</style>
