<template>
  <div class="login-bg" :style="{ backgroundImage: `url(${backgroundImage})` }">
    <a-row>
      <a-col :span="24">
        <div :class="prefixCls">
          <div style="margin:50px">
            <div>
              <img :width="width" :src="logo" alt="jeecg" />
            </div>
          </div>
        </div>
      </a-col>
    </a-row>
    
      <div class="login-box">
        <div class="login-content">
          <div class="login-title">
            {{ showLogin ? `登录 ${title}` : `注册 ${title}` }}
          </div>
          <div class="login-form-box" v-if="showLogin">
            <a-form ref="loginRef" :model="formData" @keyup.enter.native="loginHandleClick">
              <div class="login-account">
                <div class="login-inputClear">
                  <div class="login-label">
                    <span>账 号</span>
                  </div>
                  <a-form-item>
                    <a-input class="auto-fill" style="padding: 0 15px;font-size: 14px;" :placeholder="t('sys.login.userName')" v-model:value="formData.username" />
                  </a-form-item>
                </div>
                <div class="login-inputClear">
                  <div class="login-label">
                    <span>密 码</span>
                  </div>
                  <a-form-item>
                    <a-input class="auto-fill" style="padding: 0 15px;font-size: 14px;" type="password" :placeholder="t('sys.login.password')" v-model:value="formData.password" />
                  </a-form-item>
                </div>
                <div class="login-inputClear">
                  <div class="login-label">
                    <span>验证码</span>
                  </div>
                  <div class="login-code">
                    <a-form-item>
                      <a-input class="auto-fill" style="padding: 0 15px;font-size: 14px; width: 100%;" type="text" :placeholder="t('sys.login.inputCode')" v-model:value="formData.inputCode" />
                    </a-form-item>
                    <div style="margin-left: 20px">
                      <img v-if="randCodeData.requestCodeSuccess" :src="randCodeData.randCodeImage" @click="handleChangeCheckCode" />
                      <img v-else style="margin-top: 2px; max-width: initial" :src="codeImg" @click="handleChangeCheckCode" />
                    </div>
                  </div>
                </div>
                <div class="aui-flex" style="padding-top: 30px">
                  <div class="aui-flex-box">
                    <div class="aui-choice">
                      <a-input class="auto-fill" type="checkbox" v-model:value="rememberMe" />
                      <span style="margin-left: 5px">{{ t('sys.login.rememberMe') }}</span>
                    </div>
                  </div>
                </div>
              </div>
              <div class="aui-formButton">
                <div class="aui-flex">
                  <a-button :loading="loginLoading" class="aui-link-login" type="primary" @click="loginHandleClick">
                    {{ t('sys.login.loginButton') }}</a-button>
                </div>
                <div v-if="isSohoeb2bDomain()" class="register-link" style="text-align: center; margin-top: 20px;">
                  <a-button class="register-button" type="default" @click="handleRegisterClick">
                    没有账号？立即注册
                  </a-button>
                </div>
              </div>
            </a-form>
          </div>
          <div class="login-form-box" v-else>
            <a-form ref="registerRef" :model="registerData">
              <div class="login-account">
                <div class="login-inputClear">
                  <div class="login-label">
                    <span>用户名<span style="color: red">*</span></span>
                  </div>
                  <a-form-item>
                    <a-input class="auto-fill" style="padding: 0 15px;font-size: 14px;" placeholder="请输入用户名" v-model:value="registerData.username" />
                  </a-form-item>
                </div>
                <div class="login-inputClear">
                  <div class="login-label">
                    <span>企业全称<span style="color: red">*</span></span>
                  </div>
                  <a-form-item>
                    <a-input class="auto-fill" style="padding: 0 15px;font-size: 14px;" placeholder="请输入企业全称" v-model:value="registerData.companyName" />
                  </a-form-item>
                </div>
                <div class="login-inputClear">
                  <div class="login-label">
                    <span>邮箱<span style="color: red">*</span></span>
                  </div>
                  <a-form-item>
                    <a-input class="auto-fill" style="padding: 0 15px;font-size: 14px;" type="email" placeholder="请输入邮箱" v-model:value="registerData.email" />
                  </a-form-item>
                </div>
                <div class="login-inputClear">
                  <div class="login-label">
                    <span>手机号码</span>
                  </div>
                  <a-form-item>
                    <a-input class="auto-fill" style="padding: 0 15px;font-size: 14px;" placeholder="请输入手机号码（选填）" v-model:value="registerData.phone" autocomplete="new-phone" />
                  </a-form-item>
                </div>
                <div class="login-inputClear">
                  <div class="login-label">
                    <span>密码<span style="color: red">*</span></span>
                  </div>
                  <a-form-item>
                    <a-input class="auto-fill" style="padding: 0 15px;font-size: 14px;" type="password" placeholder="请输入密码" v-model:value="registerData.password" autocomplete="new-password" />
                  </a-form-item>
                </div>
                <div class="login-inputClear">
                  <div class="login-label">
                    <span>确认密码<span style="color: red">*</span></span>
                  </div>
                  <a-form-item>
                    <a-input class="auto-fill" style="padding: 0 15px;font-size: 14px;" type="password" placeholder="请再次输入密码" v-model:value="registerData.confirmPassword" />
                  </a-form-item>
                </div>
              </div>
              <div class="aui-formButton">
                <div class="aui-flex">
                  <a-button class="aui-link-login" type="primary" @click="handleRegisterSubmit">
                    注册
                  </a-button>
                </div>
                <div class="register-link" style="text-align: center; margin-top: 20px;">
                  <a-button class="register-button" type="default" @click="showLogin = true">
                    已有账号？立即登录
                  </a-button>
                </div>
              </div>
            </a-form>
          </div>
        </div>
      </div>
  </div>

</template>
<script lang="ts" setup name="login-mini">
import { getCodeInfo, registerNew } from '/@/api/sys/user';
import { computed, onMounted, reactive, ref, toRaw } from 'vue';
import codeImg from '/@/assets/images/checkcode.png';
import { useUserStore } from '/@/store/modules/user';
import { useMessage } from '/@/hooks/web/useMessage';
import { useI18n } from '/@/hooks/web/useI18n';
import logoImg from '/@/assets/loginmini/icon/soho_logo.png';
import AdweblogoImg from '/@/assets/loginmini/icon/adweb-logo.png';
import { useDesign } from "/@/hooks/web/useDesign";
import sohoImage from '/@/assets/loginmini/icon/soho-bg.jpg'; // Import the first background image
import adwebImage from '/@/assets/loginmini/icon/adweb-bg.jpg'; // Import the alternative background image
import { useRouter } from 'vue-router';

const { prefixCls } = useDesign('mini-login');
const { notification, createMessage } = useMessage();
const userStore = useUserStore();
const { t } = useI18n();
const randCodeData = reactive<any>({
  randCodeImage: '',
  requestCodeSuccess: false,
  checkKey: null,
});

const router = useRouter();

// TODO:: 待域名申请
const isSohoeb2bDomain = () => window.location.hostname.includes('sohoeb2b');

const backgroundImage = computed(() => {
  if (isSohoeb2bDomain()) {
    return sohoImage; // Use the imported image for this domain
  } else {
    return adwebImage; // Use the imported image for other domains
  }
});

const title = computed(() => {
  if (isSohoeb2bDomain()) {
    return '苏豪通'; // Use the imported image for this domain
  } else {
    return 'AdWeb V3'; // Use the imported image for other domains
  }
});

const width = computed(() => {
  if (isSohoeb2bDomain()) {
    return '233px'; // Use the imported image for this domain
  } else {
    return '300px'; // Use the imported image for other domains
  }
});

const logo = computed(() => {
  if (isSohoeb2bDomain()) {
    return logoImg; // Use the imported image for this domain
  } else {
    return AdweblogoImg; // Use the imported image for other domains
  }
});

const rememberMe = ref<string>('0');
//账号登录表单字段
const formData = reactive<any>({
  inputCode: '',
  username: '',
  password: '',
});
const loginRef = ref();
const loginLoading = ref<boolean>(false);

const showLogin = ref(true); // Add this to control form visibility

const registerData = reactive({
  username: '',
  companyName: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: ''
});

/**
 * 获取验证码
 */
function handleChangeCheckCode() {
  formData.inputCode = '';

  randCodeData.checkKey = 1629428467008;
  getCodeInfo(randCodeData.checkKey).then((res) => {
    randCodeData.randCodeImage = res;
    randCodeData.requestCodeSuccess = true;
  });
}

/**
 * 账号或者手机登录
 */
async function loginHandleClick() {
  // if (unref(activeIndex) === 'accountLogin') {
  //   accountLogin();
  // } else {
  //   //手机号登录
  // }
  accountLogin();
}

async function accountLogin() {
  if (!formData.username) {
    createMessage.warn(t('sys.login.accountPlaceholder'));
    return;
  }
  if (!formData.password) {
    createMessage.warn(t('sys.login.passwordPlaceholder'));
    return;
  }
  try {
    loginLoading.value = true;
    const { userInfo } = await userStore.login(
      toRaw({
        password: formData.password,
        username: formData.username,
        captcha: formData.inputCode,
        checkKey: randCodeData.checkKey,
        mode: 'none', //不要默认的错误提示
      })
    );
    if (userInfo) {
      notification.success({
        message: t('sys.login.loginSuccessTitle'),
        description: `${t('sys.login.loginSuccessDesc')}: ${userInfo.realname}`,
        duration: 3,
      });
    }
  } catch (error) {
    notification.error({
      message: t('sys.api.errorTip'),
      description: error.message || t('sys.login.networkExceptionMsg'),
      duration: 3,
    });
    handleChangeCheckCode();
  } finally {
    loginLoading.value = false;
  }
}

function handleRegisterClick() {
  Object.assign(registerData, {
    username: '',
    companyName: '',
    email: '',
    phone: '',
    password: '',
    confirmPassword: ''
  });
  showLogin.value = false;
}

async function handleRegisterSubmit() {
  // Validate required fields
  if (!registerData.username) {
    createMessage.warn('用户名不能为空');
    return;
  }
  if (!registerData.companyName) {
    createMessage.warn('企业全称不能为空');
    return;
  }
  if (!registerData.email) {
    createMessage.warn('邮箱不能为空');
    return;
  }
  if (!registerData.password) {
    createMessage.warn('密码不能为空');
    return;
  }
  if (!registerData.confirmPassword) {
    createMessage.warn('请再次输入密码');
    return;
  }

  // Validate email format
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(registerData.email)) {
    createMessage.warn('请输入有效的邮箱地址');
    return;
  }

  // Validate password match
  if (registerData.password !== registerData.confirmPassword) {
    createMessage.warn('两次输入的密码不一致');
    return;
  }

  // Validate password strength (optional)
  if (registerData.password.length < 8) {
    createMessage.warn('密码长度至少为8位');
    return;
  }

  registerNew(registerData)
  .then(response => {
    console.log(response)
    if (response.data.code === 200) {
    
      createMessage.success(response.data.message || '注册成功');
      showLogin.value = true; // Switch back to login form
    } else {
      createMessage.error(response.data.message || '注册失败，请稍后重试');
    }
  })
  .catch(error => {
    if (error.response && error.response.data) {
      createMessage.error(error.response.data.message || '注册失败，请稍后重试');
    } else {
      createMessage.error(error.message || '注册失败，请稍后重试');
    }
  });
}

onMounted(() => {
  //加载验证码
  handleChangeCheckCode();
});
</script>

<style lang="less" scoped>
  @import '/@/assets/loginmini/style/home.less';
  @import '/@/assets/loginmini/style/base.less';

  :deep(.ant-input:focus) {
    box-shadow: none;
  }
  .aui-get-code {
    float: right;
    position: relative;
    z-index: 3;
    background: #ffffff;
    color: #1573e9;
    border-radius: 100px;
    padding: 5px 16px;
    margin: 7px;
    border: 1px solid #1573e9;
    top: 12px;
  }

  .aui-get-code:hover {
    color: #1573e9;
  }

  .code-shape {
    border-color: #dadada !important;
    color: #aaa !important;
  }

  :deep(.jeecg-dark-switch){
    position:absolute;
    margin-right: 10px;
  }
  .aui-link-login{
    height: 42px;
    padding: 10px 15px;
    font-size: 14px;
    border-radius: 8px;
    margin-top: 35px;
    margin-bottom: 8px;
    flex: 1;
    color: #fff;
  }
  .aui-phone-logo{
    position: absolute;
    margin-left: 10px;
    width: 60px;
    top:2px;
    z-index: 4;
  }
  .top-3{
    top: 0.45rem;
  }
  .login-bg{
    width: 100%;
    height: 100vh;
    z-index: -1;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
  }
  .login-form-box {
    width: 350px;
    margin: 0 auto;
  }
</style>

<style lang="less">
#app{
  background-color: rgba(251, 251, 251, 1);
}
@prefix-cls: ~'@{namespace}-mini-login';
@dark-bg: #293146;

html[data-theme='dark'] {
  .@{prefix-cls} {
    background-color: @dark-bg !important;
    background-image: none;

    &::before {
      background-image: url(/@/assets/svg/login-bg-dark.svg);
    }
    .aui-inputClear{
      background-color: #232a3b !important;
    }
    .ant-input,
    .ant-input-password {
      background-color: #232a3b !important;
    }

    .ant-btn:not(.ant-btn-link):not(.ant-btn-primary) {
      border: 1px solid #4a5569 !important;
    }

    &-form {
      background: @dark-bg !important;
    }

    .app-iconify {
      color: #fff !important;
    }
    .aui-inputClear input,.aui-input-line input,.aui-choice{
      color: #c9d1d9 !important;
    }

    .aui-formBox{
      background-color: @dark-bg !important;
    }
    .aui-third-text span{
      background-color: @dark-bg !important;
    }
    .aui-form-nav .aui-flex-box{
      color: #c9d1d9 !important;
    }

    .aui-formButton .aui-linek-code{
      background:  @dark-bg !important;
      color: white !important;
    }
    .aui-code-line{
      border-left: none !important;
    }
    .ant-checkbox-inner,.aui-success h3{
      border-color: #c9d1d9;
    }
    //update-begin---author:wangshuai ---date:20230828  for：【QQYUN-6363】这个样式代码有问题，不在里面，导致表达式有问题------------
    &-sign-in-way {
      .anticon {
        font-size: 22px !important;
        color: #888 !important;
        cursor: pointer !important;

        &:hover {
          color: @primary-color !important;
        }
      }
    }
    //update-end---author:wangshuai ---date:20230828  for：【QQYUN-6363】这个样式代码有问题，不在里面，导致表达式有问题------------
  }
  
  .ant-divider-inner-text {
    font-size: 12px !important;
    color: @text-color-secondary !important;
  }
  .aui-third-login a{
    background: transparent;
  }
}
.auto-fill {
  width: 100%;
  height: 36px;
  opacity: 1;
  border-radius: 8px;
  background: rgba(227, 236, 250, 1);
  border: 1px solid rgba(216, 224, 240, 1);
  box-shadow: 0px 1px 2px  rgba(184, 200, 224, 0.22);

}

.register-link a {
  color: #1573e9;
  text-decoration: none;
  font-size: 14px;
}

.register-link a:hover {
  text-decoration: underline;
}

.register-button {
  width: 100%;
  height: 42px;
  border-radius: 8px;
  margin-top: 15px;
  background: #fff;
  border: 1px solid #1573e9;
  color: #1573e9;
  font-size: 14px;
}

.register-button:hover {
  background: #f0f7ff;
  border-color: #115cbf;
  color: #115cbf;
}

</style>
