<template>
  <div class="login-wrapper">
    <div class="login-container">
      <div class="login-main">
        <van-tabs v-model:active="appStore.ownApp">
          <van-tab title="水利督查" name="1"></van-tab>
          <van-tab title="水利稽察" name="2"></van-tab>
        </van-tabs>
        <van-form @submit="handleLogin">
          <van-cell-group>
            <van-field
              v-model="form.phone"
              label="手机号码"
              placeholder="请输入手机号码"
              :rules="[{ required: true, message: '请填写手机号码' }]"
            />

            <van-field
              v-model="form.imgCode"
              label="图片验证码"
              placeholder="请输入验证码"
              :rules="[{ required: true, message: '请填写验证码' }]"
            >
              <template #button>
                <van-image
                  width="100"
                  height="40"
                  :src="captchaImage"
                  @click="refreshCaptcha"
                />
              </template>
            </van-field>

            <van-field
              v-model="form.code"
              label="短信验证码"
              placeholder="请输入短信验证码"
              :rules="[{ required: true, message: '请填写短信验证码' }]"
            >
              <template #button>
                <van-button
                  size="small"
                  type="primary"
                  :disabled="countDown > 0"
                  @click="sendSmsCode"
                >
                  {{ countDown > 0 ? `${countDown}秒后重试` : "获取验证码" }}
                </van-button>
              </template>
            </van-field>
          </van-cell-group>

          <div style="margin: 16px">
            <van-button round block type="primary" native-type="submit">
              登录
            </van-button>
          </div>
        </van-form>
      </div>
    </div>
  </div>
</template>
<script setup>
import { nextTick, onBeforeUnmount, onMounted, ref } from "vue";
import { showToast } from "vant";
import { useAppStore } from "@/stores/app";
import { useUserStore } from "@/stores/user";
import { getCaptchaImage } from "@/api/login";
import { useRouter } from "vue-router";
import { sendMessage } from "@/api/login";

const appStore = useAppStore();
const userStore = useUserStore();
const router = useRouter();

// 表单数据
const form = ref({
  phone: "",
  imgCode: "",
  imgCodeId: "",
  code: "",
});

// 图片验证码
const captchaImage = ref(null);
const imgcodeid = ref(null);
const countDown = ref(0);
let countTimer = null;

function refreshCaptcha() {
  getCaptchaImage().then(async (res) => {
    await nextTick();
    imgcodeid.value = res.data.imgCodeId;
    captchaImage.value = "data:image/jpg;base64," + res.data.img;
  });
}
function loginFn() {
  if (window.cordova) {
    window.app.plugin.getUserInfo((res) => {
      let encrypt = new window.JSEncrypt();
      encrypt.setPrivateKey(window.keyUtil.getPrivateKey());
      let access_token = encrypt.decrypt(res.access_token); // access_token
      let refresh_token = encrypt.decrypt(res.refresh_token); // refresh_token
      let userId = encrypt.decrypt(res.userId); // 用户ID
      let userName = encrypt.decrypt(res.userName); // 用户姓名
      let mobile = encrypt.decrypt(res.mobile); // 手机号码
      form.value.phone = mobile;
      // form.value.phone = "13960760931";
      handleLogin();
      // let idCard = encrypt.decrypt(res.idCard) // 身份证号
      // let sex = encrypt.decrypt(res.sex) // 性别
      // let email = encrypt.decrypt(res.email) // 邮箱
      // let avatarUrl = encrypt.decrypt(res.avatarUrl) // 头像
      // let depId = encrypt.decrypt(res.depId) // 科室ID
      // let depName = encrypt.decrypt(res.depName) // 科室名称
      // let orgId = encrypt.decrypt(res.orgId) // 部门ID
      // let orgName = encrypt.decrypt(res.orgName) // 部门名称
    });
  } else {
    console.warn("Cordova 未加载，当前运行在浏览器环境");
  }
}
function sendSmsCode() {
  if (!form.value.phone) {
    showToast("请输入手机号码");
    return;
  }
  if (!form.value.imgCode) {
    showToast("请输入图片验证码");
    return;
  }
  // 倒计时
  sendMessage(form.value.phone, imgcodeid.value, form.value.imgCode).then(
    (res) => {
      if (!res.success) {
        showToast(res.message);
      }
      else{
          countDown.value = 60;
          countTimer = setInterval(() => {
            countDown.value--;
            if (countDown.value <= 0) {
              clearInterval(countTimer);
            }
          }, 1000);
      }
    }
  );
}

// 处理登录
function handleLogin() {
  if (!form.value.phone || !form.value.imgCode || !form.value.code) {
    showToast("请填写完整信息");
    return;
  }
  userStore
    .Login(form.value.phone, form.value.imgCode, form.value.code)
    .then(() => {
      console.log(appStore.ownApp);
      if (appStore.ownApp === "1") {
        router.push("/inspectDC");
      } else {
        router.push("/");
      }
    });
}

onMounted(() => {
  refreshCaptcha();
  loginFn();
});

// 组件卸载时清除定时器
onBeforeUnmount(() => {
  if (countTimer) clearInterval(countTimer);
});
</script>
<style lang="scss" scoped>
.login-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url("@/assets/images/login_background.png");

  .login-container {
    padding: 16px;

    .login-main {
      border-radius: 10px;
      background-color: #fff;
      padding-bottom: 10px;
      overflow: hidden;
    }
  }
}
</style>
