<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 class="code" @click="sendSmsCode">{{ smsCodeText }}</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>
            <!-- <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 { 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 smsCodeText = ref('发送验证码');
const smsCountdown = ref(0);
const loginRef = ref<ElFormInstance>();
const redirect = ref('/');

const loginForm = ref<LoginData>({
  username: '13322331122',
  password: '123456',
  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 sendSmsCode = () => {
  if (smsCountdown.value > 0) return;
  if (!loginForm.value.mobile) {
    ElMessage.warning('请输入手机号');
    return;
  }
  // TODO: 调用发送短信验证码接口
  ElMessage.success('验证码已发送');
  smsCountdown.value = 60;
  const timer = setInterval(() => {
    smsCountdown.value--;
    if (smsCountdown.value > 0) {
      smsCodeText.value = `${smsCountdown.value}s后重发`;
    } else {
      smsCodeText.value = '发送验证码';
      clearInterval(timer);
    }
  }, 1000);
};

/**
 * 忘记密码
 */
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%;
  width: 100%;
  background-image: url('@/assets/images/login/login1.png');
  overflow: auto;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;

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

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

    .login-bos {
      width: 520px;
      height: 510px;
      background: #ffffff;
      border-radius: 30px 30px 30px 30px;
      padding: 90px 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 107px;
        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>
