<template>
  <div :class="prefixCls" class="login-background-img">
    <AppLocalePicker class="absolute top-4 right-4 enter-x xl:text-gray-600" :showText="false" />
    <AppDarkModeToggle class="absolute top-3 right-7 enter-x" />
    <div class="aui-logo" v-if="!getIsMobile">
      <div
        ><h3><img :src="logoImg" alt="jeecg" /></h3
      ></div>
    </div>
    <div v-else class="aui-phone-logo">
      <img :src="logoImg" alt="jeecg" />
    </div>

    <div v-show="type === 'login'">
      <div class="aui-content">
        <div class="aui-container">
          <div class="aui-form">
            <div class="aui-image">
              <div class="aui-image-text"><img :src="adTextImg" /></div>
            </div>
            <div class="aui-formBox">
              <div class="aui-formWell">
                <div class="aui-flex aui-form-nav investment_title">
                  <div class="aui-flex-box" :class="activeIndex === 'accountLogin' ? 'activeNav on' : ''" @click="loginClick('accountLogin')">{{
                    t('sys.login.signInFormTitle')
                  }}</div>
                  <div class="aui-flex-box" :class="activeIndex === 'phoneLogin' ? 'activeNav on' : ''" @click="loginClick('phoneLogin')">{{
                    t('sys.login.mobileSignInFormTitle')
                  }}</div>
                </div>
                <!--                <div class="aui-form-box" style="height: 180px">-->
                <div class="aui-form-box" style="min-height: 240px; padding-bottom: 16px">
                  <!-- 账号登录 -->
                  <a-form ref="loginRef" :model="formData" v-if="activeIndex === 'accountLogin'" @keyup.enter.native="loginHandleClick">
                    <div class="aui-account">
                      <!-- 租户ID -->
                      <div class="aui-inputClear">
                        <i class="icon icon-tenant"></i>
                        <a-input
                          class="fix-auto-fill"
                          :placeholder="t('sys.login.tenantId')"
                          v-model:value="formData.tenantId"
                          @blur="onTenantBlur"
                        />
                      </div>
                      <!-- 用户名 -->
                      <div class="aui-inputClear">
                        <i class="icon icon-zhangHao"></i>
                        <a-input class="fix-auto-fill" :placeholder="t('sys.login.userName')" v-model:value="formData.username" />
                      </div>
                      <!-- 密码 -->
                      <div class="aui-inputClear">
                        <i class="icon icon-password"></i>
                        <a-input class="fix-auto-fill" type="password" :placeholder="t('sys.login.password')" v-model:value="formData.password" />
                      </div>
                      <!-- 图形验证码 -->
                      <div class="aui-inputClear">
                        <i class="icon icon-code"></i>
                        <a-input class="fix-auto-fill" :placeholder="t('sys.login.inputCode')" v-model:value="formData.inputCode" />
                        <div class="aui-code">
                          <img v-if="randCodeData.requestCodeSuccess" :src="randCodeData.randCodeImage" @click="handleChangeCheckCode" />
                          <img v-else :src="codeImg" @click="handleChangeCheckCode" style="margin-top: 2px; max-width: initial" />
                        </div>
                      </div>
                      <!-- 记住我 & 忘记密码 -->
                      <div class="aui-flex">
                        <div class="aui-flex-box">
                          <div class="aui-choice">
                            <a-input type="checkbox" v-model:value="rememberMe" />
                            <span style="margin-left: 5px">{{ t('sys.login.rememberMe') }}</span>
                          </div>
                        </div>
                        <div class="aui-forget">
                          <a @click="forgetHandelClick">{{ t('sys.login.forgetPassword') }}</a>
                        </div>
                      </div>
                    </div>
                  </a-form>

                  <!-- 手机登录 -->
                  <a-form ref="phoneFormRef" :model="phoneFormData" v-else @keyup.enter.native="loginHandleClick">
                    <div class="aui-account phone">
                      <!-- 公司编号（租户ID）-->
                      <div class="aui-inputClear">
                        <i class="icon icon-tenant"></i>
                        <a-input
                          class="fix-auto-fill"
                          :placeholder="t('sys.login.tenantId')"
                          v-model:value="phoneFormData.tenantId"
                          @blur="onTenantBlur"
                        />
                      </div>
                      <!-- 手机号 -->
                      <div class="aui-inputClear">
                        <i class="icon icon-mobile"></i>
                        <a-input class="fix-auto-fill" :placeholder="t('sys.login.mobile')" v-model:value="phoneFormData.mobile" />
                      </div>
                      <!-- 短信验证码 -->
                      <div class="aui-inputClear">
                        <i class="icon icon-code"></i>
                        <a-input class="fix-auto-fill" maxlength="6" :placeholder="t('sys.login.smsCode')" v-model:value="phoneFormData.smscode" />
                        <div v-if="showInterval" class="aui-code" @click="getLoginCode">
                          <a>{{ t('component.countdown.normalText') }}</a>
                        </div>
                        <div v-else class="aui-code">
                          <span class="aui-get-code code-shape">
                            {{ t('component.countdown.sendText', [unref(timeRuning)]) }}
                          </span>
                        </div>
                      </div>
                    </div>
                  </a-form>
                </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 class="aui-flex">
                    <a class="aui-linek-code aui-flex-box" @click="codeHandleClick">
                      {{ t('sys.login.qrSignInFormTitle') }}
                    </a>
                  </div>
                  <div class="aui-flex">
                    <a class="aui-linek-code aui-flex-box" @click="registerHandleClick">
                      {{ t('sys.login.registerButton') }}
                    </a>
                  </div>
                </div>
              </div>

              <!-- 第三方登录 -->
              <a-form @keyup.enter.native="loginHandleClick">
                <div class="aui-flex aui-third-text">
                  <div class="aui-flex-box aui-third-border">
                    <span>{{ t('sys.login.otherSignIn') }}</span>
                  </div>
                </div>
                <div class="aui-flex" :class="`${prefixCls}-sign-in-way`">
                  <div class="aui-flex-box"
                    ><a @click="onThirdLogin('github')"><GithubFilled /></a
                  ></div>
                  <div class="aui-flex-box"
                    ><a @click="onThirdLogin('wechat_enterprise')"><icon-font type="icon-qiyeweixin3" /></a
                  ></div>
                  <div class="aui-flex-box"
                    ><a @click="onThirdLogin('dingtalk')"><DingtalkCircleFilled /></a
                  ></div>
                  <div class="aui-flex-box"
                    ><a @click="onThirdLogin('wechat_open')"><WechatFilled /></a
                  ></div>
                </div>
              </a-form>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 忘记/注册/二维码 -->
    <div v-show="type === 'forgot'" :class="`${prefixCls}-form`"><MiniForgotpad ref="forgotRef" @go-back="goBack" @success="handleSuccess" /></div>
    <div v-show="type === 'register'" :class="`${prefixCls}-form`"><MiniRegister ref="registerRef" @go-back="goBack" @success="handleSuccess" /></div>
    <div v-show="type === 'codeLogin'" :class="`${prefixCls}-form`"><MiniCodelogin ref="codeRef" @go-back="goBack" @success="handleSuccess" /></div>

    <ThirdModal ref="thirdModalRef" />
    <CaptchaModal @register="captchaRegisterModal" @ok="getLoginCode" />
  </div>
</template>

<script lang="ts" setup>
  // （保持你原有的 import & setup 逻辑不变，仅在 handleChangeCheckCode 和 onTenantBlur 中使用 phoneFormData.tenantId）
  import { getCaptcha, getCodeInfo } from '/@/api/sys/user';
  import { reactive, ref, toRaw, unref, onMounted } 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 { SmsEnum } from '/@/views/sys/login/useLogin';
  import ThirdModal from '/@/views/sys/login/ThirdModal.vue';
  import MiniForgotpad from './MiniForgotpad.vue';
  import MiniRegister from './MiniRegister.vue';
  import MiniCodelogin from './MiniCodelogin.vue';
  import logoImg from '/@/assets/loginmini/icon/jeecg_logo.png';
  import adTextImg from '/@/assets/loginmini/icon/jeecg_ad_text.png';
  import { AppLocalePicker, AppDarkModeToggle } from '/@/components/Application';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { useAppInject } from '/@/hooks/web/useAppInject';
  import { GithubFilled, WechatFilled, DingtalkCircleFilled, createFromIconfontCN } from '@ant-design/icons-vue';
  import CaptchaModal from '@/components/jeecg/captcha/CaptchaModal.vue';
  import { useModal } from '@/components/Modal';
  import { ExceptionEnum } from '@/enums/exceptionEnum';

  const IconFont = createFromIconfontCN({ scriptUrl: '//at.alicdn.com/t/font_2316098_umqusozousr.js' });
  const { prefixCls } = useDesign('mini-login');
  const { notification, createMessage } = useMessage();
  const userStore = useUserStore();
  const { t } = useI18n();
  const { getIsMobile } = useAppInject();
  const [captchaRegisterModal, { openModal: openCaptchaModal }] = useModal();

  const randCodeData = reactive({ randCodeImage: '', requestCodeSuccess: false, checkKey: null });
  const rememberMe = ref('0');
  const activeIndex = ref('accountLogin');
  const type = ref('login');

  const formData = reactive({ tenantId: '', username: 'admin', password: '123456', inputCode: '' });
  const phoneFormData = reactive({ tenantId: '', mobile: '', smscode: '' });

  const loginRef = ref(),
    phoneFormRef = ref(),
    thirdModalRef = ref(),
    codeRef = ref(),
    forgotRef = ref(),
    registerRef = ref();
  const showInterval = ref(true),
    timeRuning = ref(60),
    timer = ref(null),
    loginLoading = ref(false);

  function handleChangeCheckCode() {
    const tid = activeIndex.value === 'accountLogin' ? formData.tenantId : phoneFormData.tenantId;
    localStorage.setItem('tenantId', tid || '');
    formData.inputCode = '';
    randCodeData.checkKey = Date.now() + Math.random().toString(36).slice(-4);
    getCodeInfo(randCodeData.checkKey).then((res) => {
      randCodeData.randCodeImage = res;
      randCodeData.requestCodeSuccess = true;
    });
  }

  function onTenantBlur() {
    handleChangeCheckCode();
  }

  function loginClick(val: string) {
    activeIndex.value = val;
  }

  async function loginHandleClick() {
    if (activeIndex.value === 'accountLogin') await accountLogin();
    else await phoneLogin();
  }

  async function accountLogin() {
    if (!formData.tenantId) {
      createMessage.warn(t('sys.login.tenantIdPlaceholder'));
      return;
    }
    if (!formData.username) {
      createMessage.warn(t('sys.login.accountPlaceholder'));
      return;
    }
    if (!formData.password) {
      createMessage.warn(t('sys.login.passwordPlaceholder'));
      return;
    }
    localStorage.setItem('tenantId', formData.tenantId);
    try {
      loginLoading.value = true;
      const { userInfo } = await userStore.login(
        toRaw({
          tenantId: formData.tenantId,
          username: formData.username,
          password: formData.password,
          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 (e: any) {
      notification.error({ message: t('sys.api.errorTip'), description: e.message || t('sys.login.networkExceptionMsg'), duration: 3 });
      handleChangeCheckCode();
    } finally {
      loginLoading.value = false;
    }
  }

  async function phoneLogin() {
    if (!phoneFormData.tenantId) {
      createMessage.warn(t('sys.login.tenantPlaceholder'));
      return;
    }
    if (!phoneFormData.mobile) {
      createMessage.warn(t('sys.login.mobilePlaceholder'));
      return;
    }
    if (!phoneFormData.smscode) {
      createMessage.warn(t('sys.login.smsPlaceholder'));
      return;
    }
    localStorage.setItem('tenantId', phoneFormData.tenantId);
    try {
      loginLoading.value = true;
      const { userInfo }: any = await userStore.phoneLogin({
        tenantId: phoneFormData.tenantId,
        mobile: phoneFormData.mobile,
        captcha: phoneFormData.smscode,
        mode: 'none',
      });
      if (userInfo) {
        notification.success({
          message: t('sys.login.loginSuccessTitle'),
          description: `${t('sys.login.loginSuccessDesc')}: ${userInfo.realname}`,
          duration: 3,
        });
      }
    } catch (e: any) {
      notification.error({ message: t('sys.api.errorTip'), description: e.message || t('sys.login.networkExceptionMsg'), duration: 3 });
    } finally {
      loginLoading.value = false;
    }
  }

  async function getLoginCode() {
    if (!phoneFormData.mobile) {
      createMessage.warn(t('sys.login.mobilePlaceholder'));
      return;
    }
    const res = await getCaptcha({ mobile: phoneFormData.mobile, smsmode: SmsEnum.FORGET_PASSWORD }).catch((err) => {
      if (err.code === ExceptionEnum.PHONE_SMS_FAIL_CODE) openCaptchaModal(true, {});
    });
    if (res) {
      const COUNT = 60;
      if (!timer.value) {
        timeRuning.value = COUNT;
        showInterval.value = false;
        timer.value = setInterval(() => {
          if (timeRuning.value > 0) timeRuning.value--;
          else {
            showInterval.value = true;
            clearInterval(timer.value);
            timer.value = null;
          }
        }, 1000);
      }
    }
  }

  function onThirdLogin(t: string) {
    thirdModalRef.value.onThirdLogin(t);
  }
  function forgetHandelClick() {
    type.value = 'forgot';
    setTimeout(() => forgotRef.value.initForm(), 300);
  }
  function goBack() {
    activeIndex.value = 'accountLogin';
    type.value = 'login';
    localStorage.removeItem('tenantId');
  }
  function handleSuccess(v: any) {
    Object.assign(formData, v);
    Object.assign(phoneFormData, { mobile: '', smscode: '' });
    type.value = 'login';
    activeIndex.value = 'accountLogin';
    handleChangeCheckCode();
  }
  function registerHandleClick() {
    type.value = 'register';
    setTimeout(() => registerRef.value.initForm(), 300);
  }
  function codeHandleClick() {
    type.value = 'codeLogin';
    setTimeout(() => codeRef.value.initFrom(), 300);
  }

  onMounted(() => {
    localStorage.removeItem('tenantId');
    handleChangeCheckCode();
  });
</script>

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

  /* 登录按钮：调小高度、左右内边距和上下外边距 */
  .aui-link-login {
    height: 40px; /* 从42px→40px */
    padding: 10px 24px; /* 左右内边距从35px→24px */
    margin: 20px 0 8px; /* 上外边距从35px→20px，下外边距不变 */
    font-size: 14px;
    border-radius: 8px;
    flex: 1;
    color: #fff;
  }

  /* 手机端 logo：向右、向下微调，尺寸也略微减少 */
  .aui-phone-logo {
    position: absolute;
    left: 16px; /* 从10px→16px，和内容区边距对齐 */
    top: 1rem; /* 从0.45rem→1rem，避免和暗黑切换按钮冲突 */
    width: 48px; /* 从60px→48px */
    z-index: 4;
  }
</style>

<!--  :deep(.ant-input:focus) {-->
<!--    box-shadow: none;-->
<!--  }-->

<!--  /* 针对「手机登录」下面所有 .aui-inputClear 做 flex 布局 */-->
<!--  :deep(.aui-account.phone .aui-inputClear) {-->
<!--    display: flex !important;-->
<!--    align-items: center !important;-->
<!--    padding-left: 0 !important; /* 取消原来的 padding-left */-->
<!--  }-->

<!--  /* 图标本身不再绝对定位，而是正常流，和输入框分开 */-->
<!--  :deep(.aui-account.phone .aui-inputClear i) {-->
<!--    position: static !important;-->
<!--    margin-right: 8px !important;-->
<!--    font-size: 18px; /* 根据需要调节 icon 大小 */-->
<!--  }-->

<!--  /* 输入框撑满剩余空间 */-->
<!--  :deep(.aui-account.phone .aui-inputClear .ant-input) {-->
<!--    flex: 1 !important;-->
<!--    padding-left: 0 !important; /* 取消 ant 自带的内左边距 */-->
<!--  }-->

<!--  .aui-get-code {-->
<!--    float: right;-->
<!--    position: relative;-->
<!--    z-index: 3;-->
<!--    background: #fff;-->
<!--    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;-->
<!--  }-->

<!--  /* 登录按钮：调小高度、左右内边距和上下外边距 */-->
<!--  .aui-link-login {-->
<!--    height: 40px; /* 从42px→40px */-->
<!--    padding: 10px 24px; /* 左右内边距从35px→24px */-->
<!--    margin: 20px 0 8px; /* 上外边距从35px→20px，下外边距不变 */-->
<!--    font-size: 14px;-->
<!--    border-radius: 8px;-->
<!--    flex: 1;-->
<!--    color: #fff;-->
<!--  }-->

<!--  /* 手机端 logo：向右、向下微调，尺寸也略微减少 */-->
<!--  .aui-phone-logo {-->
<!--    position: absolute;-->
<!--    left: 16px; /* 从10px→16px，和内容区边距对齐 */-->
<!--    top: 1rem; /* 从0.45rem→1rem，避免和暗黑切换按钮冲突 */-->
<!--    width: 48px; /* 从60px→48px */-->
<!--    z-index: 4;-->
<!--  }-->

<!--  /* 如果整个表单区还需要“提”起来，去掉固定高度，改为最小高度+内边距 */-->
<!--  //.aui-form-box {-->
<!--  //  /* style="height: 180px" 改成： */-->
<!--  //  min-height: 240px;-->
<!--  //  padding: 16px 0 8px;-->
<!--  //}-->

<!--  .top-3 {-->
<!--    top: 0.45rem;-->
<!--  }-->
<!--</style>-->

<!--<style lang="less">-->
<!--  /* 暗黑模式 */-->
<!--  @dark-bg: #293146;-->

<!--  html[data-theme='dark'] & {-->
<!--    background-color: @dark-bg !important;-->
<!--    background-image: none !important;-->
<!--  }-->
<!--  html[data-theme='dark'] &::before {-->
<!--    background-image: url(/@/assets/svg/login-bg-dark.svg) !important;-->
<!--  }-->

<!--  html[data-theme='dark'] .aui-inputClear {-->
<!--    background-color: #232a3b !important;-->
<!--  }-->
<!--  html[data-theme='dark'] .ant-input,-->
<!--  html[data-theme='dark'] .ant-input-password {-->
<!--    background-color: #232a3b !important;-->
<!--  }-->
<!--  html[data-theme='dark'] .ant-btn:not(.ant-btn-link):not(.ant-btn-primary) {-->
<!--    border: 1px solid #4a5569 !important;-->
<!--  }-->
<!--  html[data-theme='dark'] .aui-formBox {-->
<!--    background-color: @dark-bg !important;-->
<!--  }-->
<!--  html[data-theme='dark'] .aui-inputClear input,-->
<!--  html[data-theme='dark'] .aui-input-line input,-->
<!--  html[data-theme='dark'] .aui-choice {-->
<!--    color: #c9d1d9 !important;-->
<!--  }-->
<!--  html[data-theme='dark'] .aui-third-text span {-->
<!--    background-color: @dark-bg !important;-->
<!--  }-->
<!--  html[data-theme='dark'] .aui-form-nav .aui-flex-box {-->
<!--    color: #c9d1d9 !important;-->
<!--  }-->
<!--  html[data-theme='dark'] .aui-formButton .aui-linek-code {-->
<!--    background: @dark-bg !important;-->
<!--    color: #fff !important;-->
<!--  }-->
<!--  html[data-theme='dark'] .aui-code-line {-->
<!--    border-left: none !important;-->
<!--  }-->
<!--  html[data-theme='dark'] .ant-checkbox-inner,-->
<!--  html[data-theme='dark'] .aui-success h3 {-->
<!--    border-color: #c9d1d9;-->
<!--  }-->
<!--  html[data-theme='dark'] &-sign-in-way .anticon {-->
<!--    font-size: 22px !important;-->
<!--    color: red !important;-->
<!--    cursor: pointer !important;-->
<!--    &:hover {-->
<!--      color: @primary-color !important;-->
<!--    }-->
<!--  }-->

<!--  input.fix-auto-fill,-->
<!--  .fix-auto-fill input {-->
<!--    -webkit-text-fill-color: #c9d1d9 !important;-->
<!--    box-shadow: inherit !important;-->
<!--  }-->
<!--  .ant-divider-inner-text {-->
<!--    font-size: 12px !important;-->
<!--    color: @text-color-secondary !important;-->
<!--  }-->
<!--  .aui-third-login a {-->
<!--    background: transparent;-->
<!--  }-->
<!--</style>-->
<!--<style scoped lang="less">-->
<!--  /* 1. 手动输入文本：针对 Affix Wrapper 中的真实 <input> */-->
<!--  :deep(.ant-input-affix-wrapper input.ant-input) {-->
<!--    font-size: 40px !important;-->
<!--    color: #111 !important;-->
<!--  }-->

<!--  /* 2. 占位符文本 */-->
<!--  :deep(.ant-input-affix-wrapper input.ant-input::placeholder),-->
<!--  :deep(.ant-input-affix-wrapper input.ant-input::-webkit-input-placeholder),-->
<!--  :deep(.ant-input-affix-wrapper input.ant-input:-ms-input-placeholder) {-->
<!--    color: #aaa !important;-->
<!--  }-->

<!--  /* 3. Chrome 自动填充后的文本 & 背景 */-->
<!--  :deep(.ant-input-affix-wrapper input:-webkit-autofill) {-->
<!--    -webkit-text-fill-color: #111 !important;-->
<!--    box-shadow: 0 0 0 1000px #fff inset !important;-->
<!--    transition: background-color 5000s ease-in-out 0s;-->
<!--  }-->
<!--</style>-->
