<template>
  <div style="text-align: center; margin-bottom: 40px">
    <span style="font-size: 28px; font-weight: 700; line-height: normal">{{ t('sys.login.welcome') }}</span>
  </div>
  <Form
    class="p-4 enter-x"
    :model="formData"
    :rules="getFormRules"
    ref="formRef"
    v-show="getShow"
    @keypress.enter="handleLogin"
  >
    <FormItem name="account" class="enter-x">
      <Input size="large" v-model:value="formData.account" :placeholder="t('sys.login.userName')" class="fix-auto-fill" />
    </FormItem>
    <FormItem name="password" class="enter-x">
      <InputPassword
        size="large"
        v-model:value="formData.password"
        :placeholder="t('sys.login.password')"
        class="fix-auto-fill"
      />
    </FormItem>

    <!--验证码-->
    <ARow class="enter-x" :style="{ height: '56px' }">
      <ACol :span="12">
        <FormItem name="inputCode" class="enter-x">
          <Input
            size="large"
            v-model:value="formData.inputCode"
            :placeholder="t('sys.login.inputCode')"
            style="min-width: 100px"
          />
        </FormItem>
      </ACol>
      <ACol :span="8">
        <FormItem :style="{ 'text-align': 'right', 'margin-left': '20px' }" class="enter-x">
          <img
            v-if="randCodeData.requestCodeSuccess"
            style="margin-top: 2px; max-width: initial"
            :src="randCodeData.randCodeImage"
            @click="handleChangeCheckCode"
          />
          <img
            v-else
            style="margin-top: 2px; max-width: initial"
            src="../../../../assets/images/checkcode.png"
            @click="handleChangeCheckCode"
          />
        </FormItem>
      </ACol>
    </ARow>

    <ARow class="enter-x" :style="{ height: '46px' }">
      <ACol :span="12">
        <FormItem>
          <!-- No logic, you need to deal with it yourself -->
          <Checkbox v-model:checked="rememberPassword" size="small">
            {{ t('sys.login.rememberPassword') }}
          </Checkbox>
        </FormItem>
      </ACol>
      <ACol :span="12">
        <FormItem :style="{ 'text-align': 'right' }">
          <!-- No logic, you need to deal with it yourself -->
          <Button type="link" size="small" @click="setLoginState(LoginStateEnum.RESET_PASSWORD)">
            {{ t('sys.login.forgetPassword') }}
          </Button>
        </FormItem>
      </ACol>
    </ARow>

    <FormItem class="enter-x login-item">
      <Button class="login-button" size="large" block @click="handleLogin" :loading="loading">
        {{ t('sys.login.loginButton') }}
      </Button>
      <!-- <Button size="large" class="mt-4 enter-x" block @click="handleRegister">
              {{ t('sys.login.registerButton') }}
            </Button> -->
    </FormItem>
    <div v-if="!getSimplifyMode">
      <div class="register-button">
        <a @click="setLoginState(LoginStateEnum.REGISTER)" :style="{ 'text-decoration': 'underline' }">{{
          t('sys.login.registerButton')
        }}</a>
      </div>
      <Divider class="enter-x">{{ t('sys.login.otherSignIn') }}</Divider>
      <div class="flex justify-evenly enter-x" :class="`${prefixCls}-sign-in-way`">
        <a @click="setLoginState(LoginStateEnum.MOBILE)" :title="t('sys.login.mobileSignInFormTitle')">
          <img src="../../../../assets/loginIcons/mobileLogin.png" class="login-icons" />
        </a>
        <a @click="setLoginState(LoginStateEnum.QR_CODE)" :title="t('sys.login.qrSignInFormTitle')">
          <img src="../../../../assets/loginIcons/QRLogin.png" class="login-icons" />
        </a>
        <a title="微信登录">
          <img src="../../../../assets/loginIcons/weixinLogin.png" class="login-icons" />
        </a>
        <a title="钉钉登录">
          <img src="../../../../assets/loginIcons/dingLogin.png" class="login-icons" />
        </a>
        <a title="企业微信登录">
          <img src="../../../../assets/loginIcons/EWLogin.png" class="login-icons" />
        </a>
      </div>
    </div>
  </Form>
  <!-- 第三方登录相关弹框 -->
  <ThirdModal ref="thirdModalRef" />
</template>
<script lang="ts" setup>
  import { reactive, ref, toRaw, unref, computed, onMounted } from 'vue';
  import { Checkbox, Form, Input, Row, Col, Button, Divider } from 'ant-design-vue';
  import ThirdModal from './ThirdModal.vue';
  import {
    useMessage,
    useDesign,
    useRootSetting,
    useUserStore,
    LoginStateEnum,
    useLoginState,
    useFormRules,
    useFormValid
  } from '@jdlinker/func';
  import { getCodeInfo } from '../../../../api/sys/user';
  import { useI18n } from 'vue-i18n';

  const ACol = Col;
  const ARow = Row;
  const FormItem = Form.Item;
  const InputPassword = Input.Password;
  const { t } = useI18n();
  const { notification } = useMessage();
  const { prefixCls } = useDesign('login');
  const userStore = useUserStore();

  const { setLoginState, getLoginState } = useLoginState();
  const { getFormRules } = useFormRules();

  const formRef = ref();
  const thirdModalRef = ref();
  const loading = ref(false);
  const rememberPassword = ref(false);
  const { getSimplifyMode } = useRootSetting();
  const formData = reactive({
    account: '',
    password: '',
    inputCode: ''
  });
  const randCodeData = reactive<any>({
    randCodeImage: '',
    requestCodeSuccess: false,
    checkKey: null
  });

  const { validForm } = useFormValid(formRef);

  //onKeyStroke('Enter', handleLogin);

  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN);

  async function handleLogin() {
    const data = await validForm();
    if (!data) return;
    try {
      loading.value = true;
      const { userInfo } = await userStore.login(
        toRaw({
          password: data.password,
          username: data.account,
          clientType: 1,
          captcha: data.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) {
      console.log('handleLogin....error', error);
      notification.error({
        message: t('sys.api.errorTip'),
        description: error.message || t('sys.api.networkExceptionMsg'),
        duration: 3
      });
      loading.value = false;
      handleChangeCheckCode();
    }
  }
  function handleChangeCheckCode() {
    formData.inputCode = '';
    //TODO 兼容mock和接口，暂时这样处理
    randCodeData.checkKey = 1629428467008; //new Date().getTime();
    getCodeInfo(randCodeData.checkKey).then((res) => {
      randCodeData.randCodeImage = res;
      randCodeData.requestCodeSuccess = true;
    });
  }

  /**
   * 第三方登录
   * @param type
   */
  function onThirdLogin(type) {
    thirdModalRef.value.onThirdLogin(type);
  }

  //初始化验证码
  onMounted(() => {
    handleChangeCheckCode();
  });
</script>
<style lang="less" scoped>
  .margin-auto {
    margin: 10px auto;
    height: 80px;
    width: 80px;
  }
  .JD-Linker {
    height: 30px;
    line-height: 30px;
    margin: 12px auto;
    font-size: 16px;
    font-weight: 500;
    text-align: center;
    color: #999;
  }
  :deep(.ant-input) {
    border-radius: 2px;
  }
  :deep(.ant-input-affix-wrapper) {
    border-radius: 2px;
  }

  .login-item {
    margin-bottom: 5px;
  }

  .login-button {
    width: 100%;
    height: 46px;
    display: block;
    margin: auto;
    border-radius: 2px;
    //box-shadow: 0 2.8px 2.2px 0 rgba(0, 0, 0, 0.02), 0 6.7px 5.3px 0 rgba(0, 0, 0, 0.03), 0 12.5px 10px 0 rgba(0, 0, 0, 0.04), 0 22.3px 17.9px 0 rgba(0, 0, 0, 0.04), 0 41.8px 33.4px 0 rgba(0, 0, 0, 0.05), 0 100px 80px 0 rgba(0, 0, 0, 0.07);
    background-color: @primary-color !important;
    color: #fff;
  }
  .register-button {
    margin: auto;
    text-align: center;
  }
  .login-icons {
    margin: 0 auto;
    width: 35px;
    height: 35px;
  }
</style>
