<template>
  <view class="login_home">
    <nut-row>
      <nut-col :span="24" class="login_tiitle">
        <div class="title">你好，</div>
        <div class="title">欢迎登录鱼测云</div>
      </nut-col>

      <nut-popup
        v-model:visible="show"
        position="bottom"
        :closeable="false"
        :overlay="false"
        round
        :style="{ height: '83%' }"
      >
        <nut-config-provider :theme-vars="themeVars">
          <nut-form
            label-position="top"
            :show-error-line="false"
            :show-error-message="false"
            ref="loginRef"
            :style="{ border: '0px !important' }"
          >
            <nut-form-item label="手机号" class="itemLabel">
              <nut-input
                v-model="loginForm.phonenumber"
                type="number"
                placeholder="请输入手机号"
                max-length="11"
              />
            </nut-form-item>
            <nut-form-item label="验证码" class="itemLabel">
              <nut-input
                v-model="loginForm.code"
                type="number"
                placeholder="请输入验证码"
                max-length="6"
              >
                <template #right>
                  <view
                    :class="btnContent.canClick ? 'code' : 'disabled'"
                    @click="getCode()"
                    >{{ btnContent.content }}
                  </view>
                </template>
              </nut-input>
            </nut-form-item>
            <view :style="{ padding: '0 16px', marginTop: '20px' }">
              <nut-button
                block
                type="primary"
                size="large"
                :style="{ fontWeight: 'bold', fontSize: '14px !important' }"
                @click="login"
                :loading="isLoading"
                >登录</nut-button
              >
            </view>
          </nut-form>
        </nut-config-provider>
      </nut-popup>
      <!-- 弹出层提示 -->
      <nut-toast
        :msg="state.msg"
        v-model:visible="state.show"
        :type="state.type"
      />
    </nut-row>
  </view>
</template>
<script setup lang="ts" name="Login">
import { loginFormType, contentBtnType } from "./types";
import { stateType } from "@/utils/types";
import validatePhone from "@/utils/validate";
import { loginSms, smsCode } from "@/api/login";
import Taro from "@tarojs/taro";
// 已阅读参数
const store: any = inject("store");
const show = ref(true);
const loginForm: loginFormType = reactive({
  phonenumber: "",
  code: "",
  identity: false,
});
const themeVars = ref({
  formItemLabelFontSize: "15px",
  cellBorderRadius: "0px",
  cellBoxShadow: "0px",
  checkboxLabelMarginLeft: "0px",
  checkboxMarginRight: "2px",
});
const btnContent: contentBtnType = reactive({
  content: "获取验证码",
  totalTime: 60,
  canClick: true,
});
const state: stateType = reactive({
  msg: "",
  type: "text",
  center: true,
  show: false,
});
const isLoading = ref(false);
/** -----------------method start----------------- */
/** 验证码读秒 */
function setTime() {
  if (!btnContent.canClick) return; // 如果是false 直接return出去
  btnContent.canClick = false;
  btnContent.content = btnContent.totalTime + "s后重新发送";
  let clock = window.setInterval(() => {
    btnContent.totalTime--;
    btnContent.content = btnContent.totalTime + "s后重新发送";
    if (btnContent.totalTime < 0) {
      window.clearInterval(clock);
      btnContent.content = "重新发送";
      btnContent.totalTime = 60;
      btnContent.canClick = true; // 这里重新开启
    }
  }, 1000);
}
/** 获取验证码 */
function getCode() {
  if(!btnContent.canClick){
    return
  }
  const v_phone_res = validatePhone(loginForm.phonenumber);
  if (v_phone_res == 1) {
    state.msg = "手机号不能为空";
    state.show = true;
  } else if (v_phone_res == 2) {
    state.msg = "手机号格式不正确";
    state.show = true;
  } else {
    smsCode(loginForm.phonenumber).then((res: any) => {
      state.msg = "发送成功";
      state.show = true;
      setTime();
    });
  }
}
/** 手机号码登录 */
function login() {
  const v_phone_res = validatePhone(loginForm.phonenumber);
  if (v_phone_res == 1) {
    state.msg = "手机号不能为空";
    state.show = true;
    return;
  } else if (v_phone_res == 2) {
    state.msg = "手机号格式不正确";
    state.show = true;
    return;
  }
  if (!loginForm.code) {
    state.msg = "请输入验证码";
    state.show = true;
    return;
  }
  if (loginForm.code.length != 6) {
    state.msg = "验证码为6位数字";
    state.show = true;
    return;
  }
  isLoading.value = true
  loginSms(loginForm.phonenumber, loginForm.code).then((res: any) => {
    if (res.code == 200) {
      // 存储 token
      if (res.data.access_token) {
        Taro.setStorageSync("Access-Token", res.data.access_token);
        Taro.setStorageSync("X-Access-Token", res.data.access_token);
      }
      
      Taro.setStorageSync(
        "ReTime",
        res.data.createdTime
          ? formatDate(new Date(res.data.createdTime))
          : formatDate(new Date())
      );
      Taro.setStorageSync("UserName", res.data.userName || loginForm.phonenumber);
      Taro.setStorageSync("Phone", loginForm.phonenumber);
      Taro.setStorageSync("LoginType", "1");
      Taro.setStorageSync("UserId", res.data.userId || "");
      Taro.setStorageSync("UnLogin", 2);
      store.updateLoginStatus(0);
      store.updateUnLogin(2);
      store.updateRootUserId(res.data.userId || "");
      store.updateUserId(res.data.userId || "");
      store.updateRootUserName(res.data.userName || loginForm.phonenumber);
      state.msg = "登录成功";
      state.show = true;
      Taro.switchTab({
        url: "/pages/main/home",
      });
      return;
    } else {
      state.msg = res.msg || "登录失败";
      state.show = true;
    }
  }).finally(()=>{
    isLoading.value = false
  })
}
Taro.useDidShow(() => {
  if (!Taro.getStorageSync("Access-Token")) {
    Taro.clearStorageSync();
  } else {
    Taro.switchTab({
      url: "/pages/main/home",
    });
  }
});
/** -----------------method end------------------- */
</script>
<style lang="scss">
.login_home {
  height: 100%;
  width: 100%;
  background-size: 100% 100%;
  position: fixed;
  margin: 0;
  background: linear-gradient(90deg, #74dce2 0%, #ddf7f2 100%);

  font-size: 32px;
  font-family: "PingFang SC";
  font-weight: 400;

  .login_tiitle {
    padding: 20px !important;

    .title {
      font-size: 46px;
      color: #000;
      font-family: "PingFang SC";
      font-weight: 800;
    }
  }

  .itemLabel {
    color: #000;
    font-family: "PingFang SC";
    font-weight: 400;
  }

  .code {
    color: #09b8c2;
  }

  .disabled {
    color: #ccc;
  }

  .container {
    display: flex;
  }

  .agrBottom {
    position: fixed;
    bottom: 8%;
  }
}
</style>
