<template>
  <div class="login">
    <el-form
      ref="loginRef"
      :model="showAccountLogin ? loginForm : loginSmsForm"
      :rules="showAccountLogin ? loginRules : loginSmsRules"
      class="login-form"
    >
      <h3 class="title">专家库管理集约化平台 - {{ wbjName }}</h3>

      <template v-if="showAccountLogin">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" type="text" size="large" placeholder="账号">
            <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" size="large" placeholder="密码" @keyup.enter="handleLogin">
            <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="captchaEnabled" prop="code">
          <el-input v-model="loginForm.code" size="large" placeholder="验证码" style="width: 63%" @keyup.enter="handleLogin">
            <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" class="login-code-img" @click="getCode" alt="验证码" />
          </div>
        </el-form-item>
        <el-checkbox v-model="loginForm.rememberMe" style="margin: 0 0 25px 0">记住密码</el-checkbox>
      </template>

      <template v-else>
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" type="text" size="large" placeholder="账号">
            <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
          </el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input v-model="loginSmsForm.phonenumber" size="large" placeholder="请输入手机号">
            <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
          </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input v-model="loginSmsForm.smsCode" size="large" placeholder="请输入验证码">
            <template #append>
              <el-button @click="sendSmsCode" :disabled="countdown > 0">
                {{ countdown > 0 ? countdown + 's后重试' : '获取验证码' }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>
      </template>

      <el-form-item style="width: 100%">
        <el-button :loading="loading" size="large" type="primary" style="width: 100%" @click.prevent="handleLogin">
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>

      <!-- 切换按钮 -->
<!--      <el-form-item>
        <el-button type="text" @click="toggleLoginType">
          {{ showAccountLogin ? '使用短信验证码登录' : '使用账号密码登录' }}
        </el-button>
      </el-form-item>-->
    </el-form>

    <div class="el-login-footer">
      <span>Copyright ©</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getCodeImg } from '@/api/login';
import { useUserStore } from '@/store/modules/user';
import { LoginData } from '@/api/types';
import { to } from 'await-to-js';
const userStore = useUserStore();
const router = useRouter();
const route = useRoute();

const tenantList = computed(() => userStore.tenantList);
const wbjKey = computed(() => route.params.wbjKey);
const wbjName = computed(() => tenantList.value.find((item) => item.domain === wbjKey.value)?.companyName || '');

const loginForm = ref<LoginData>({
  username: '',
  password: '',
  rememberMe: false,
  code: '',
  uuid: ''
});
const loginSmsForm = ref({ phonenumber: '', smsCode: '' });

const loginRules: ElFormRules = {
  username: [{ required: true, message: '请输入您的账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入您的密码', trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'change' }]
};
const loginSmsRules: ElFormRules = {
  phonenumber: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  smsCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
};

const codeUrl = ref('');
const captchaEnabled = ref(true);
const loading = ref(false);
const countdown = ref(0);
let timer: any = null;
const loginRef = ref<ElFormInstance>();
const redirect = ref();

const loginUrl = computed(() => `/login/${wbjKey.value}/org`);
const showAccountLogin = ref(false); // ✅ 控制登录方式

const handleLogin = () => {
  loginRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;
    loading.value = true;
    const form = loginForm.value;
    if (showAccountLogin.value) {

      if (form.rememberMe) {
        localStorage.setItem(`${wbjKey.value}_username`, form.username);
        localStorage.setItem(`${wbjKey.value}_password`, form.password);
        localStorage.setItem(`${wbjKey.value}_rememberMe`, String(form.rememberMe));
      } else {
        localStorage.removeItem(`${wbjKey.value}_username`);
        localStorage.removeItem(`${wbjKey.value}_password`);
        localStorage.removeItem(`${wbjKey.value}_rememberMe`);
      }
      const [err] = await to(userStore.login({ wbjKey: wbjKey.value, loginUrl: loginUrl.value, ...form }));
      if (!err) router.push(redirect.value || '/');
      else if (captchaEnabled.value) await getCode();
    } else {
      const { phonenumber, smsCode } = loginSmsForm.value;
      form.clientId = 'aaee710ecebb7d4251f8a7e7d10fad0d'
      form.grantType = 'sms'
      const [err] = await to(userStore.smsLogin({ wbjKey: wbjKey.value, loginUrl: loginUrl.value, phonenumber, smsCode , ...form}));
      if (!err) router.push(redirect.value || '/');
    }
    loading.value = false;
  });
};

const sendSmsCode = async () => {
  const phone = loginSmsForm.value.phonenumber;
  if (!phone) return ElMessage.warning('请输入手机号');
  const [err] = await to(userStore.sendSmsCode({ wbjKey: wbjKey.value, phone }));
  if (!err) {
    ElMessage.success('验证码发送成功');
    countdown.value = 60;
    timer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) clearInterval(timer);
    }, 1000);
  }
};

const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    loginForm.value.uuid = data.uuid;
  }
};

const getLoginData = () => {
  const username = localStorage.getItem(`${wbjKey.value}_username`);
  const password = localStorage.getItem(`${wbjKey.value}_password`);
  const rememberMe = localStorage.getItem(`${wbjKey.value}_rememberMe`);
  loginForm.value.username = username ?? '';
  loginForm.value.password = password ?? '';
  loginForm.value.rememberMe = rememberMe === 'true';
};

const toggleLoginType = () => {
  showAccountLogin.value = !showAccountLogin.value;
};

watch(
  () => router.currentRoute.value,
  (newRoute) => {
    redirect.value = newRoute.query?.redirect;
  },
  { immediate: true }
);

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

<style lang="scss" scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url('@/assets/images/login-background.jpg');
  background-size: cover;
}

.title {
  margin: 0 auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 40px;

    input {
      height: 40px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 40px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial, serif;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 40px;
  padding-left: 12px;
}
.unified-href {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: var(--el-color-primary);
}
h3 {
  font-weight: bold;
}
</style>
