<template>
  <LoginFormTitle v-show="getShow" class="enter-x" />
  <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="<% if (enableTranslation) { %>t('sys.login.userName')<% } else { %>'t$t('sys.login.userName')$t$'<% } %>"
        class="fix-auto-fill"
      />
    </FormItem>
    <FormItem name="password" class="enter-x">
      <InputPassword
        size="large"
        visibilityToggle
        v-model:value="formData.password"
        :placeholder="<% if (enableTranslation) { %>t('sys.login.password')<% } else { %>'t$t('sys.login.password')$t$'<% } %>"
      />
    </FormItem>
    <!--验证码-->
    <ARow class="enter-x">
      <ACol :span="12">
        <FormItem name="inputCode" class="enter-x">
          <Input size="large" v-model:value="formData.inputCode" :placeholder="<% if (enableTranslation) { %>t('sys.login.inputCode')<% } else { %>'t$t('sys.login.inputCode')$t$'<% } %>" 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="checkcodePng" @click="handleChangeCheckCode" />
        </FormItem>
      </ACol>
    </ARow>
    <ARow class="enter-x">
      <ACol :span="12">
        <FormItem>
          <!-- No logic, you need to deal with it yourself -->
          <Checkbox v-model:checked="rememberMe" size="small">
            <% if (enableTranslation) { %>{{ t('sys.login.rememberMe') }}<% } else { %>t$t('sys.login.rememberMe')$t$<% } %>
          </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)">
            <% if (enableTranslation) { %>{{ t('sys.login.forgetPassword') }}<% } else { %>t$t('sys.login.forgetPassword')$t$<% } %>
          </Button>
        </FormItem>
      </ACol>
    </ARow>

    <FormItem class="enter-x">
      <Button type="primary" size="large" block @click="handleLogin" :loading="loading">
        <% if (enableTranslation) { %>{{ t('sys.login.loginButton') }}<% } else { %>t$t('sys.login.loginButton')$t$<% } %>
      </Button>
      <!-- <Button size="large" class="mt-4 enter-x" block @click="handleRegister">
        <% if (enableTranslation) { %>{{ t('sys.login.registerButton') }}<% } else { %>t$t('sys.login.registerButton')$t$<% } %>
      </Button> -->
    </FormItem>
    <ARow class="enter-x" :gutter="[16, 16]">
      <ACol :md="8" :xs="24">
        <Button block @click="setLoginState(LoginStateEnum.MOBILE)">
          <% if (enableTranslation) { %>{{ t('sys.login.mobileSignInFormTitle') }}<% } else { %>t$t('sys.login.mobileSignInFormTitle')$t$<% } %>
        </Button>
      </ACol>
      <ACol :md="8" :xs="24">
        <Button block @click="setLoginState(LoginStateEnum.QR_CODE)">
          <% if (enableTranslation) { %>{{ t('sys.login.qrSignInFormTitle') }}<% } else { %>t$t('sys.login.qrSignInFormTitle')$t$<% } %>
        </Button>
      </ACol>
      <ACol :md="8" :xs="24">
        <Button block @click="setLoginState(LoginStateEnum.REGISTER)">
          <% if (enableTranslation) { %>{{ t('sys.login.registerButton') }}<% } else { %>t$t('sys.login.registerButton')$t$<% } %>
        </Button>
      </ACol>
    </ARow>

    <Divider class="enter-x"><% if (enableTranslation) { %>{{ t('sys.login.otherSignIn') }}<% } else { %>t$t('sys.login.otherSignIn')$t$<% } %></Divider>

    <div class="flex justify-evenly enter-x" :class="`${prefixCls}-sign-in-way`">
      <a @click="onThirdLogin('github')" title="github"><GithubFilled /></a>
      <a @click="onThirdLogin('wechat_enterprise')" title="企业微信"> <icon-font class="item-icon" type="icon-qiyeweixin3" /></a>
      <a @click="onThirdLogin('dingtalk')" title="钉钉"><DingtalkCircleFilled /></a>
      <a @click="onThirdLogin('wechat_open')" title="微信"><WechatFilled /></a>
    </div>
  </Form>
  <!-- 第三方登录相关弹框 -->
  <ThirdModal ref="thirdModalRef"></ThirdModal>
</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 {
    GithubFilled,
    WechatFilled,
    AlipayCircleFilled,
    GoogleCircleFilled,
    TwitterCircleFilled,
    DingtalkCircleFilled,
    QuestionCircleFilled,
    createFromIconfontCN
  } from '@ant-design/icons-vue';
  import LoginFormTitle from './LoginFormTitle.vue';
  import ThirdModal from './ThirdModal.vue';

<%_ if (enableTranslation) { _%>
  import { useI18n } from '@/hooks/web/useI18n';
<%_ } _%>
  import { useMessage } from '@/hooks/web/useMessage';

  import { useUserStore } from '@/store/modules/user';
  import { LoginStateEnum, useLoginState, useFormRules, useFormValid } from './useLogin';
  import { useDesign } from '@begcode/components';
  import { getCodeInfo } from '@/api-service/sys/user';
  import checkcodePng from '@/assets/images/checkcode.png';
  //import { onKeyStroke } from '@vueuse/core';

  // begcode-please-regenerate-this-file 如果您不希望重新生成代码时被覆盖，将please修改为don't ！！！

  const ACol = Col;
  const ARow = Row;
  const FormItem = Form.Item;
  const InputPassword = Input.Password;
  const IconFont = createFromIconfontCN({
    scriptUrl: '//at.alicdn.com/t/font_2316098_umqusozousr.js',
  });
<%_ if (enableTranslation) { _%>
  const { t } = useI18n();
<%_ } _%>
  const { notification, createErrorModal } = 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 rememberMe = ref(false);

  const formData = reactive({
    account: 'admin',
    password: 'admin',
    inputCode: '',
  });
  const randCodeData = reactive({
    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,
          captcha: data.inputCode,
          checkKey: randCodeData.checkKey,
          mode: 'none', // 不要默认的错误提示
        }));
      if (userInfo) {
        notification.success({
          message: <% if (enableTranslation) { %>t('sys.login.loginSuccessTitle')<% } else { %>'t$t('sys.login.loginSuccessTitle')$t$'<% } %>,
          description: `<% if (enableTranslation) { %>${t('sys.login.loginSuccessDesc')}<% } else { %>t$t('sys.login.loginSuccessDesc')$t$<% } %>: ${userInfo.firstName}`,
          duration: 3,
        });
      }
    } catch (error) {
      console.log('error', error);
      notification.error({
        message: <% if (enableTranslation) { %>t('sys.api.errorTip')<% } else { %>'t$t('sys.api.errorTip')$t$'<% } %>,
        description: error.message || <% if (enableTranslation) { %>t('sys.api.networkExceptionMsg')<% } else { %>'t$t('sys.api.networkExceptionMsg')$t$'<% } %>,
        duration: 3,
      });
    } finally {
      loading.value = false;
      handleChangeCheckCode();
    }
  }

  function handleChangeCheckCode() {
    formData.inputCode = '';
    //TODO 兼容mock和接口，暂时这样处理
    randCodeData.checkKey = new Date().getTime();
    getCodeInfo(randCodeData.checkKey).then(data => {
      randCodeData.randCodeImage = data;
      randCodeData.requestCodeSuccess = true;
    });
  }

  /**
   * 第三方登录
   * @param type
   */
  function onThirdLogin(type) {
    thirdModalRef.value.onThirdLogin(type);
  }
  //初始化验证码
  onMounted(() => {
    handleChangeCheckCode();
  });
</script>
