<template>
  <h-form id="formLogin" layout="vertical" class="user-layout-login" ref="form" :model="modelRef">
    <h-alert
      v-if="loginError"
      type="error"
      show-icon
      style="margin-bottom: 24px"
      :message="errorMsg"
    />
    <h-form-item v-show="loginInfo?.LA_ENABLE_TENANT == 1" v-bind="validateInfos.tenant">
      <img src="~@/assets/login-localhost.png" alt="" class="login-loaclhost" />
      <h-select
        size="large"
        v-model:value="modelRef.tenant"
        :placeholder="t('login.selectTenant')"
        style="width: 100%"
        :options="tenantOptions"
        :filter-option="filterOption"
        class="tenantselect"
      >
        <template #suffixIcon>
          <caret-down-outlined class="login-select-creatdown-icon" />
        </template>
      </h-select>
    </h-form-item>
    <!-- 账号 -->
    <h-form-item
      name="username"
      :rules="[
        { required: true, message: t('login.usernameErrorMsg') },
        { validator: handleUsernameOrEmail, trigger: ['change', 'blur'] },
      ]"
    >
      <h-input
        size="large"
        v-model:value="modelRef.username"
        :placeholder="t('login.inputUsername')"
        style="width: 100%"
        readonly
        @focus="e => e.target.removeAttribute('readonly')"
      >
        <template #prefix>
          <img class="login-input-user" src="~@/assets/login-user.png" />
        </template>
      </h-input>
    </h-form-item>
    <!-- 密码 -->
    <h-form-item
      name="password"
      :rules="[
        {
          required: true,
          message: t('login.inputUserPwd'),
        },
        { asyncValidator: handlePassWord, trigger: ['change', 'blur'] },
      ]"
    >
      <h-input-password
        v-model:value="modelRef.password"
        size="large"
        :placeholder="t('login.inputUserPwd')"
        style="width: 100%"
      >
        <template #prefix>
          <img class="login-input-password" src="~@/assets/login-password.png" />
        </template>
      </h-input-password>
    </h-form-item>
    <!-- 验证码 -->
    <h-row v-show="showVerifyCode && loginInfo?.SECURITY_CAPTCHA == 1" :gutter="16">
      <h-col class="gutter-row" :span="16">
        <h-form-item
          name="code"
          :rules="[
            { required: true, message: t('login.codeErrorMsg') },
            { asyncValidator: handleInputCode, trigger: ['change', 'blur'] },
          ]"
        >
          <h-input
            v-model:value="verifyCode"
            size="large"
            type="text"
            :placeholder="t('login.inputCode')"
            @change="changeCode"
            autocomplete="off"
          ></h-input>
        </h-form-item>
      </h-col>
      <h-col class="gutter-row" :span="8">
        <h-image
          :width="104"
          :height="42"
          :preview="false"
          :src="loginCodeInfo.src"
          @click="getLoginCodeData"
        />
      </h-col>
    </h-row>
    <!-- </h-tab-pane> -->

    <!-- <h-tab-pane key="tab2" tab="手机号登录">
        <h-form-item v-bind="validateInfos.mobile">
          <h-input
            v-model:value="modelRef.mobile"
            size="large"
            type="text"
            placeholder="手机号"
          >
            <template #prefix>
              <mobile-outlined class="prefixIcon" />
            </template>
          </h-input>
        </h-form-item>

        <h-row :gutter="16">
          <h-col class="gutter-row" :span="16">
            <h-form-item v-bind="validateInfos.captcha">
              <h-input
                v-model:value="modelRef.captcha"
                size="large"
                type="text"
                placeholder="验证码"
              >
                <template #prefix>
                  <mail-outlined class="prefixIcon" />
                </template>
              </h-input>
            </h-form-item>
          </h-col>
          <h-col class="gutter-row" :span="8">
            <h-button
              class="getCaptcha"
              tabindex="-1"
              :disabled="smsSendBtn"
              @click.stop.prevent="getCaptcha"
            >
              {{ (!smsSendBtn && '获取验证码') || time + ' s' }}
            </h-button>
          </h-col>
        </h-row>
      </h-tab-pane> -->
    <!-- </h-tabs> -->

    <h-form-item>
      <!-- <h-checkbox
        v-model:checked="modelRef.rememberMe"
        v-show="loginInfo?.showNextAutomaticLogin"
      >
        记住密码
      </h-checkbox> -->
      <!-- 七天免登录设置 -->

      <h-checkbox
        v-model:checked="modelRef.isValid"
        v-show="loginInfo?.LA_WHETHER_ENABLE_LOGIN_FREE == 1"
        class="sevenFreeLogin"
      >
        {{ loginInfo?.LA_LOGIN_FREE_DAYS }}{{ t('login.freeLogin') }}
      </h-checkbox>

      <template v-if="loginInfo?.LA_SHOW_FORGOTTEN_PASSWORD == 1">
        <h-tooltip placement="top">
          <template #title>
            <span>{{ t('login.forgetPwdTip') }}</span>
          </template>
          <a class="forge-password" style="float: right">{{ t('login.forgetPwd') }}</a>
          <!-- <router-link to="/user/recover" class="forge-password" style="float: right">
            忘记密码
          </router-link> -->
        </h-tooltip>
      </template>
    </h-form-item>

    <h-form-item style="margin-top: 24px">
      <h-button
        v-if="disableSubmit"
        size="large"
        type="primary"
        html-type="submit"
        class="login-button"
        :disabled="true"
      >
        {{ t('login.loginText') }}
      </h-button>
      <h-button
        v-else
        size="large"
        type="primary"
        html-type="submit"
        :loading="loginBtn"
        class="login-button"
        @click="submit"
      >
        {{ t('login.loginText') }}
      </h-button>
    </h-form-item>

    <!-- 注册账户入口 -->
    <!-- <div class="user-login-other">
      <span>其他登录方式</span>
      <a>
        <alipay-circle-outlined class="item-icon" />
      </a>
      <a>
        <taobao-circle-outlined class="item-icon" />
      </a>
      <a>
        <weibo-circle-outlined class="item-icon" />
      </a>
      <router-link class="register" to="/user/register">注册账户</router-link>
    </div> -->
  </h-form>
</template>

<script lang="ts">
import { defineComponent, ref, watch, reactive } from 'vue';
import { useI18n } from '@crami/locale';
import { CaretDownOutlined } from '@ant-design/icons-vue';

export default defineComponent({
  name: 'LoginForm',
  components: {
    CaretDownOutlined,
  },
  props: [
    'loginMode',
    'currentLoginMode',
    'isLoginError',
    'loginErrorMsg',
    'loginInfo',
    'validateInfos',
    'modelRef',
    'tenantOptions',
    'filterOption',
    'showCode',
    'loginCodeInfo',
    'getLoginCodeData',
    'loginBtn',
    'handleSubmit',
  ],

  setup(props) {
    const { t } = useI18n();

    // 错误校验内容不共享
    const loginError = ref(false);
    const errorMsg = ref('');

    watch(
      () => [props.isLoginError, props.loginErrorMsg],
      ([isLoginError, loginErrorMsg]) => {
        if (props.loginMode === props.currentLoginMode) {
          loginError.value = isLoginError;
          errorMsg.value = loginErrorMsg;
        }
      },
    );

    // 验证码初次是否展示不共享，展示内容共享
    const showVerifyCode = ref(true);
    const verifyCode = ref('');
    watch(
      // 监听 props.loginCodeInfo.key 只是为了确保能监听到改变
      () => [props.showCode, props.loginCodeInfo.key],
      () => {
        if (props.loginMode === props.currentLoginMode) {
          // 初次切换过来时校验码输入值为空
          if (!showVerifyCode.value) {
            verifyCode.value = '';
          }
          // 只有当form出错时才展示验证码，当请求成功后 isLoginError 会变为false
          // if (loginError.value) {
          //   showVerifyCode.value = showCode;
          // }
        }
      },
    );

    // 输入验证码时同步到Login
    const changeCode = () => {
      props.modelRef.code = verifyCode.value;
    };

    // 同步其它tab表单的最新验证码
    watch(
      () => props.modelRef.code,
      (val: any) => {
        if (showVerifyCode.value) {
          verifyCode.value = val;
        }
      },
    );

    // 控制登录 button 是否可点击
    const disableSubmit = ref(true);

    watch(
      props.modelRef,
      modelRef => {
        if (modelRef.username && modelRef.password && modelRef.tenant) {
          // 判断是否显示验证码
          if (showVerifyCode.value && props.loginInfo?.SECURITY_CAPTCHA == 1) {
            // 当显示验证码时，判断验证码是否填写
            if (modelRef.code) {
              disableSubmit.value = false;
            } else {
              disableSubmit.value = true;
            }
          } else {
            disableSubmit.value = false;
          }
        } else {
          disableSubmit.value = true;
        }
      },
      { immediate: true },
    );

    //============修改校验方式===========
    const form = ref();
    //登陆方式
    const state = reactive({
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
    });
    //登陆方式校验
    const handleUsernameOrEmail = (_rule: any, value: any) => {
      return new Promise(resolve => {
        const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
        if (regex.test(value)) {
          state.loginType = 0;
        } else {
          state.loginType = 1;
        }
        resolve(state.loginType);
      });
    };

    //密码校验
    const handlePassWord = (rule, value, callback) => {
      return new Promise((res, reject) => {
        if (value === '') {
          // rule.message = t('login.inputUserPwd');
          callback(false);
          reject();
        } else {
          res(true);
        }
      });
    };
    //验证码校验
    const handleInputCode = (rule, value, callback) => {
      return new Promise((res, reject) => {
        if (value === '') {
          // rule.message = t('login.codeErrorMsg');
          callback(false);
          reject();
        } else {
          res(true);
        }
      });
    };
    //提交
    const submit = e => {
      const rules = [];
      if (props.loginInfo?.LA_ENABLE_TENANT == 1) {
        rules.push('tenant');
      }
      rules.push('username');
      rules.push('password');
      if (showVerifyCode.value && props.loginInfo?.SECURITY_CAPTCHA == 1) {
        rules.push('code');
      }
      //点击完登录按钮更新验证码
      props.getLoginCodeData();
      props.handleSubmit(e, rules);
    };

    return {
      t,
      form,
      loginError,
      errorMsg,
      showVerifyCode,
      verifyCode,
      changeCode,
      disableSubmit,
      submit,
      handleUsernameOrEmail,
      handlePassWord,
      handleInputCode,
    };
  },
});
</script>
<style lang="less" scoped>
.tenantselect {
  :deep(.ant-select-selector) {
    .ant-select-selection-placeholder {
      margin-left: 27px;
    }
    .ant-select-selection-item {
      margin-left: 27px;
    }
  }
}
</style>
