<template>
  <div class="login">
    <img @click="onPath('/')" class="head" src="@/assets/images/head.png" alt="" />
    <div class="login-info flex-row-between">
      <div></div>
      <div class="login-bos">
        <el-form ref="loginRef" :model="loginForm" :rules="loginRules">
          <div class="login-type flex-row-between">
            <div :class="type == 1 ? 'hig' : ''" @click="onType(1)">账户登录</div>
            <div class="border"></div>
            <div :class="type == 2 ? 'hig' : ''" @click="onType(2)">验证码登录</div>
          </div>
          <template v-if="type == 1">
            <el-form-item prop="username">
              <el-input class="login-input" v-model="loginForm.username" placeholder="员工编号/手机号码">
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input class="login-input" type="password" v-model="loginForm.password" placeholder="输入登录密码" @keyup.enter="handleLogin">
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item prop="mobile">
              <el-input :maxlength="11" class="login-input" v-model="loginForm.mobile" placeholder="手机号">
                <template #prefix>
                  <el-icon><Iphone /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="smsCode">
              <el-input :maxlength="6" class="login-input" v-model="loginForm.smsCode" placeholder="验证码">
                <template #prefix>
                  <el-icon><Message /></el-icon>
                </template>
                <template #suffix>
                  <span @click="sendSmsCode" :class="['code', countdown > 0 ? 'disabled' : '']">
                    {{ codeText }}
                  </span>
                </template>
              </el-input>
            </el-form-item>
          </template>
          <el-form-item>
            <el-button class="login-btn" type="primary" :loading="loading" @click.prevent="handleLogin">
              <span v-if="!loading">登录</span>
              <span v-else>登录中...</span>
            </el-button>
          </el-form-item>
          <div class="login-text flex-row-between">
            <div @click="handleForgetPassword">忘记密码?</div>
            <div class="border"></div>
            <div @click="onPath('/breg')">企业注册</div>
            <div @click="onPath('/reg')">个人注册</div>
            <!-- <router-link to="/register" class="register-link">新用户注册</router-link> -->
          </div>
        </el-form>
      </div>
    </div>
    <div class="login-foot flex-column-between">
      <div class="font-bos flex-row-center">
        <div>客户管理</div>
        <div style="margin: 0 10px">|</div>
        <div>供应商合作</div>
        <div style="margin: 0 10px">|</div>
        <div>关于我们</div>
        <div style="margin: 0 10px">|</div>
        <div>帮助中心</div>
        <div style="margin: 0 10px">|</div>
        <div>联系我们</div>
      </div>
      <div class="font-box">CopyRight @ 优易365 2026</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useUserStore } from '@/store/modules/user';
import { smsCode } from '@/api/breg/index';
import { LoginData } from '@/api/types';
import { to } from 'await-to-js';
import { User, Lock, Iphone, Message } from '@element-plus/icons-vue';
import { onPath } from '@/utils/siteConfig';

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

const type = ref<number>(1);
const loading = ref(false);
const timer = ref<any>(null);

const loginRef = ref<ElFormInstance>();
const redirect = ref('/');
const codeText = ref<string>('发送验证码');
const countdown = ref<number>(0);
const loginForm = ref<LoginData>({
  username: import.meta.env.VITE_APP_USERNAME,
  password: import.meta.env.VITE_APP_PASSWORD,
  mobile: '',
  smsCode: '',
  tenantId: '000000',
  rememberMe: false,
  code: '',
  uuid: '',
  clientId: '',
  grantType: 'password'
} as LoginData);

const loginRules: ElFormRules = {
  username: [{ required: true, trigger: 'blur', message: '请输入员工编号/手机号码' }],
  password: [{ required: true, trigger: 'blur', message: '请输入登录密码' }],
  mobile: [{ required: true, trigger: 'blur', message: '请输入手机号' }],
  smsCode: [{ required: true, trigger: 'blur', message: '请输入验证码' }]
};

const onType = (val: number) => {
  type.value = val;
  // 切换登录类型时更新 grantType
  loginForm.value.grantType = val === 1 ? 'password' : 'sms';
};

/**
 * 监听路由变化，获取重定向地址
 */
watch(
  () => router.currentRoute.value,
  (newRoute: any) => {
    redirect.value = newRoute.query && newRoute.query.redirect && decodeURIComponent(newRoute.query.redirect);
  },
  { immediate: true }
);

/**
 * 处理登录
 */
const handleLogin = () => {
  loginRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      // 勾选记住密码时保存到 localStorage
      if (loginForm.value.rememberMe) {
        localStorage.setItem('username', String(loginForm.value.username));
        localStorage.setItem('password', String(loginForm.value.password));
        localStorage.setItem('rememberMe', String(loginForm.value.rememberMe));
      } else {
        localStorage.removeItem('username');
        localStorage.removeItem('password');
        localStorage.removeItem('rememberMe');
      }
      // 调用登录
      const [err] = await to(userStore.login(loginForm.value));
      if (!err) {
        const redirectUrl = redirect.value || '/';
        onPath(redirectUrl);
        loading.value = false;
      } else {
        loading.value = false;
      }
    }
  });
};

// 启动倒计时
const startCountdown = () => {
  countdown.value = 60;
  codeText.value = `${countdown.value}s 后重新发送`;

  timer.value = setInterval(() => {
    countdown.value--;
    if (countdown.value > 0) {
      codeText.value = `${countdown.value}s 后重新发送`;
    } else {
      clearInterval(timer.value);
      timer.value = null;
      codeText.value = '发送验证码';
    }
  }, 1000);
};

/**
 * 发送短信验证码
 */
const sendSmsCode = () => {
  // 防止倒计时期间重复点击
  if (countdown.value > 0) return;

  const phone = loginForm.value.mobile;

  // 1. 基础格式校验
  if (!validateMobile(phone)) {
    ElMessage({
      message: '请输入正确的手机号码',
      type: 'warning'
    });
    return;
  }
  // TODO: 调用发送短信验证码接口
  smsCode({ phonenumber: phone })
    .then((smsRes: any) => {
      if (smsRes.code === 200) {
        ElMessage({
          message: '验证码已发送',
          type: 'success'
        });
        startCountdown(); // 开始倒计时
      } else {
        // 发送短信接口业务失败
        ElMessage.error(smsRes.msg || '发送验证码失败');
      }
    })
    .catch((err: any) => {
      // 发送短信接口网络错误或异常
      ElMessage.error(err.msg || '发送验证码请求异常');
    });
};

// 验证手机号
const validateMobile = (phone: any) => {
  const reg = /^1[3-9]\d{9}$/;
  return reg.test(phone);
};

/**
 * 忘记密码
 */
const handleForgetPassword = () => {
  ElMessage.info('请联系管理员重置密码');
};

/**
 * 获取保存的登录信息
 */
const getLoginData = () => {
  const username = localStorage.getItem('username');
  const password = localStorage.getItem('password');
  const rememberMe = localStorage.getItem('rememberMe');
  if (username && password && rememberMe) {
    loginForm.value.username = username;
    loginForm.value.password = password;
    loginForm.value.rememberMe = Boolean(rememberMe);
  }
};

onMounted(() => {
  getLoginData();
});
</script>

<style lang="scss" scoped>
.login {
  height: 100%;
  min-height: 700px;
  width: 100%;
  background-image: url('@/assets/images/login/login1.png');
  overflow: auto;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 20px 0;

  .head {
    width: 185px;
    height: 90px;
    margin-left: 84px;
    cursor: pointer;
  }

  .login-info {
    width: 100%;
    height: 600px;
    background-image: url('@/assets/images/login/login2.png');
    overflow: hidden;
    background-position: center center;
    background-repeat: no-repeat;
    background-size: cover;
    margin-top: 10px;
    min-width: 1200px;
    padding: 0 5%;

    .login-bos {
      width: 520px;
      height: 420px;
      background: #ffffff;
      border-radius: 30px 30px 30px 30px;
      padding: 40px 85px 0 85px;

      :deep(.el-form-item) {
        margin-bottom: 18px;
      }

      :deep(.el-form-item__error) {
        padding-top: 4px;
      }

      .login-type {
        font-weight: 600;
        font-size: 22px;
        color: #101828;
        padding: 0 67px;
        margin-bottom: 40px;
        div {
          cursor: pointer;
        }
        .hig {
          color: #e7000b;
        }
        .border {
          width: 1px;
          height: 16px;
          background: #e6e8ec;
        }
      }
      .login-input {
        width: 350px;
        height: 50px;
        font-size: 16px;
        .code {
          font-size: 14px;
          color: #e7000b;
          cursor: pointer;
        }
      }
      :deep(.el-input__wrapper) {
        border: none;
        box-shadow: none;
        outline: none;
        background: #f4f6f8;
      }
      :deep(.el-input__prefix) {
        font-size: 18px;
        color: #9ca3af;
      }
      .login-btn {
        width: 350px;
        height: 50px;
        margin-top: 20px;
        font-size: 16px;
        background-color: #c8102e;
        border-color: #c8102e;
        &:hover {
          background-color: #a50d26;
          border-color: #a50d26;
        }
      }
      .login-text {
        font-size: 14px;
        color: #6a7282;
        padding: 0 80px;
        margin-top: 14px;
        div {
          cursor: pointer;
          &:hover {
            color: #c8102e;
          }
        }
        .border {
          width: 1px;
          height: 12px;
          background: #e6e8ec;
        }
        .register-link {
          color: #c8102e;
          text-decoration: none;
          &:hover {
            text-decoration: underline;
          }
        }
      }
    }
  }
  .font-bos {
    width: 100%;
    font-size: 13px;
    color: #999999;
    margin-top: 30px;
  }
  .font-box {
    width: 100%;
    font-size: 13px;
    color: #999999;
    margin-top: 20px;
    text-align: center;
  }
}
</style>
