<template>
  <div class="login-container">
    <div class="login-header">
      <div class="logo-box">
        <van-icon name="shield-o" class="logo-icon" />
      </div>
      <div class="title">交通执法通</div>
      <div class="subtitle">移动执法管理平台</div>
    </div>

    <div class="login-content">
      <van-tabs v-model:active="TabActiveName" class="custom-tabs">
        <van-tab title="账号密码" name="a"></van-tab>
        <van-tab title="手机验证码" name="b"></van-tab>
      </van-tabs>

      <van-form @submit="onSubmit" class="form" v-show="TabActiveName == 'a'">
        <van-field v-model="form.userName" name="userName" placeholder="请输入账号" left-icon="manager-o"
          :rules="[{ required: true, message: '请填写用户名' }]" class="custom-field" />
        <van-field v-model="form.password" :type="passwordVisible ? 'text' : 'password'" name="password"
          placeholder="请输入密码" left-icon="lock" :right-icon="passwordVisible ? 'eye-o' : 'closed-eye'"
          @click-right-icon="passwordVisible = !passwordVisible" :rules="[{ required: true, message: '请填写密码' }]"
          class="custom-field" />
        <div class="submit-btn-box">
          <van-button round block type="primary" native-type="submit" :loading="isLoading" loading-type="spinner"
            loading-text="登录中..." class="login-btn">登录</van-button>
        </div>
      </van-form>

      <van-form @submit="onSubmit" class="form" v-show="TabActiveName == 'b'">
        <van-field v-model="form.phone" name="phone" placeholder="请输入手机号" left-icon="phone-o"
          :rules="[{ required: true, message: '请填写手机号' }]" class="custom-field" />
        <div class="code-row">
          <van-field v-model="form.code" center clearable placeholder="请输入验证码"
            :rules="[{ required: true, message: '请输入验证码' }]" class="custom-field code-input-field" />
          <div class="get-code-btn-container">
            <div class="get-code-btn" :class="{ 'disabled': countdown > 0 }" @click="sendCode">
              {{ countdown > 0 ? `${countdown}s后重发` : '获取验证码' }}
            </div>
          </div>
        </div>
        <div class="submit-btn-box">
          <van-button round block type="primary" native-type="submit" :loading="isLoading" loading-type="spinner"
            loading-text="登录中..." class="login-btn">登录</van-button>
        </div>
      </van-form>
    </div>

    <div class="login-footer">
      <div class="agreement">
        登录即表示同意 <span class="link">《用户协议》</span> 和 <span class="link">《隐私政策》</span>
      </div>
      <div class="copyright">
        © 2024 交通执法通 v1.0.0
      </div>
    </div>
  </div>
</template>

<script setup>
import "vant/es/toast/style";
import Base64 from "base-64";
import { login, idCardlogin, getUserOrFjInfo } from "../../api/user.js";
import { encryptAES } from "../../utils/crypto.js";
import { computed, ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { Overlay, Toast } from "vant";
import axios from "axios";
const router = useRouter();
const store = useStore();
const TabActiveName = ref('a')
const count = ref(0);
const passwordVisible = ref(false);
const form = reactive({
  userName: "",
  password: "",
  phone: "",
  code: "",
  type: "02"
});
const countdown = ref(0);
const isLoading = ref(false);
const idCardForm = reactive({
  idCard: "510922199202281887"
});
onMounted(() => {
  _idCardlogin(); // 已屏蔽自动登录
});
//身份证登录
function _idCardlogin() {
  try {
    // let userinfo = JSON.parse(bridge.getLocation());
    let sfzh='510922199202281887'
    Toast.loading({
      message: "登录中...",
      forbidClick: true,
      loadingType: "spinner",
      overlay: true,
      duration: 0,
    });
    isLoading.value = true;
    // form.userName = userinfo.app_sfzh;
    const encryptedIdCard = encryptAES(sfzh);
    idCardlogin({ username: encryptedIdCard }).then((res) => {
        
        if(res){
          const token = res.accessToken;
          store.commit("setToken", token);
           _getUserInfo();
        }
      })
      .catch((err) => {
        Toast.clear();
        isLoading.value = false;
      });
  } catch (error) { }
}
const sendCode = async () => {
  countdown.value = 60;
  const intervalId = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      clearInterval(intervalId);
    }
  }, 1000);
};

// 身份证号格式校验
function validateIdCard(val) {
  return /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(val);
}

// 身份证登录提交
function onIdCardSubmit() {
  Toast.loading({
    message: "登录中...",
    forbidClick: true,
    loadingType: "spinner",
    overlay: true,
    duration: 0,
  });
  isLoading.value = true;
  const encryptedIdCard = encryptAES(idCardForm.idCard);
  idCardlogin({ username: encryptedIdCard })
    .then((res) => {
      const token = res.jwtToken;
      _getUserInfo();
      store.commit("setToken", token);
    })
    .catch((err) => {
      Toast.clear();
      isLoading.value = false;
    });
}
//手动登录
const onSubmit = (e) => {
  if (TabActiveName.value === 'a') {
    // 设置 localStorage 以通过路由守卫
    const mockToken = "mock_token_for_dev";
    const mockUser = {
      deptName: "交警支队一大队",
      userName: "测试用户",
      deptList: [],
      id: "999999",
      idEntityCard: "420100000000000000",
      mobile: "13800138000",
      inDustRialId: "",
      sex: "1",
    };
    window.localStorage.setItem('token', mockToken);
    window.localStorage.setItem('userInfo', JSON.stringify(mockUser));
    store.commit("userStatus", mockUser);
    store.commit("setToken", mockToken);
    setTimeout(() => {
      router.replace("/Home");
    }, 300);
  } else {
    Toast.fail("手机号登录功能暂未开放");
  }
};
//获取用户信息
function _getUserInfo() {
  getUserOrFjInfo({}).then((res) => {
    store.commit("userStatus", res);
    window.localStorage.setItem('userInfo', JSON.stringify(res));
    setTimeout(() => {
      isLoading.value = false;
      router.replace("/Home");
      Toast.clear();
    }, 1e3);
  });
}
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background-color: #f7faff;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow-x: hidden;

  .login-header {
    height: 38vh;
    background: linear-gradient(to bottom right, #2563eb, #1d4ed8);
    border-bottom-left-radius: 100px;
    border-bottom-right-radius: 100px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #fff;
    padding-bottom: 30px;

    .logo-box {
      width: 84px;
      height: 84px;
      background: #fff;
      border-radius: 24px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 20px;
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);

      .logo-icon {
        font-size: 46px;
        color: #2563eb;
      }
    }

    .title {
      font-size: 34px;
      font-weight: 800;
      letter-spacing: 2px;
      margin-bottom: 12px;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .subtitle {
      font-size: 16px;
      opacity: 0.85;
      letter-spacing: 1px;
    }
  }

  .login-content {
    margin: 40px 32px 0;
    z-index: 1;

    .custom-tabs {
      margin-bottom: 35px;
      background-color: #f1f4fb;
      border-radius: 12px;
      padding: 6px;

      :deep(.van-tabs__nav) {
        background-color: transparent;
      }

      :deep(.van-tab) {
        border-radius: 10px;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        color: #8c96ab;
        font-size: 15px;
        height: 44px;
        line-height: 44px;
      }

      :deep(.van-tab--active) {
        background-color: #fff;
        color: #2563eb;
        font-weight: 600;
        box-shadow: 0 4px 12px rgba(37, 102, 255, 0.08);
        border: 1px solid #2563eb;
      }

      :deep(.van-tabs__line) {
        display: none;
      }

      :deep(.van-tabs__wrap) {
        height: 44px;
      }
    }

    .form {
      .custom-field {
        margin-bottom: 24px;
        background-color: #fff;
        border: 1px solid #f0f3f8;
        border-radius: 16px;
        padding: 14px 20px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.03);

        &::after {
          display: none;
        }

        :deep(.van-field__left-icon) {
          margin-right: 16px;
          color: #b0b8c8;
          font-size: 24px;
        }

        :deep(.van-field__right-icon) {
          color: #b0b8c8;
          font-size: 22px;
        }

        :deep(.van-field__control) {
          font-size: 17px;
          color: #333;

          &::placeholder {
            color: #b0b8c8;
            font-weight: 400;
          }
        }
      }

      .submit-btn-box {
        margin-top: 45px;

        .login-btn {
          height: 54px;
          background: #2563eb;
          border: none;
          border-radius: 14px;
          font-size: 20px;
          font-weight: 600;
          box-shadow: 0 8px 25px rgba(37, 102, 235, 0.35);
          letter-spacing: 2px;
        }
      }

      .code-row {
        display: flex;
        gap: 12px;
        align-items: flex-start;

        .code-input-field {
          flex: 1;
        }

        .get-code-btn-container {
          height: 54px;
          display: flex;
          align-items: center;
        }

        .get-code-btn {
          height: 54px;
          line-height: 54px;
          padding: 0 16px;
          border: 1px solid #2563eb;
          border-radius: 14px;
          color: #2563eb;
          font-size: 15px;
          font-weight: 500;
          white-space: nowrap;
          background: #fff;
          transition: all 0.2s;
          cursor: pointer;

          &:active {
            background: #f0f4ff;
          }

          &.disabled {
            color: #b0b8c8;
            border-color: #f0f3f8;
            cursor: not-allowed;
          }
        }
      }
    }
  }

  .login-footer {
    margin-top: auto;
    padding: 40px 20px 30px;
    text-align: center;

    .agreement {
      font-size: 14px;
      color: #8c96ab;
      margin-bottom: 16px;

      .link {
        color: #3e7bff;
        font-weight: 500;
      }
    }

    .copyright {
      font-size: 13px;
      color: #b0b8c8;
      letter-spacing: 0.5px;
    }
  }
}
</style>
