<template>
  <div ref="boxRef">
    <Form
      class="p-4 enter-x form-box"
      :model="formData"
      :rules="getFormRules"
      ref="formRef"
      v-show="getShow"
      @keypress.enter="handleLogin"
    >
      <div>
        <FormItem name="account" class="enter-x">
          <label class="form-title"> {{ t('账号') }}</label>
          <Input
            size="large"
            v-model:value="formData.account"
            :placeholder="t('账号')"
            class="fix-auto-fill"
            style="height: 58px"
            ><template #prefix>
              <IconFontSymbol icon="yonghu-xianxing" class="user-icon" />
            </template>
          </Input>
        </FormItem>
        <FormItem name="password" class="enter-x">
          <label class="form-title"> {{ t('密码') }}</label>
          <InputPassword
            size="large"
            visibilityToggle
            v-model:value="formData.password"
            :placeholder="t('密码')"
            style="height: 58px"
            ><template #prefix>
              <IconFontSymbol icon="mima" class="user-icon" />
            </template>
          </InputPassword>
        </FormItem>
<!--        <FormItem name="code" class="enter-x" v-if="formData.showCaptcha">-->
<!--          <label class="form-title"> {{ t('验证码') }}</label>-->
<!--          <div style="display: flex">-->
<!--            <Input-->
<!--              size="large"-->
<!--              v-model:value="formData.code"-->
<!--              :placeholder="t('验证码')"-->
<!--              class="fix-auto-fill"-->
<!--              style="height: 58px"-->
<!--            />-->
<!--            <img-->
<!--              :src="formData.captchaImg"-->
<!--              style="width: 100%; height: 60px; margin-left: 10px"-->
<!--              @click="getImg"-->
<!--            />-->
<!--          </div>-->
<!--        </FormItem>-->
        <ARow class="enter-x">
          <ACol :span="12">
            <FormItem>
              <!-- No logic, you need to deal with it yourself -->
              <Checkbox v-model:checked="rememberMe" size="small" class="f-16">
                {{ 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)">
            {{ t('忘记密码？') }}
          </Button>
        </FormItem>
      </ACol> -->
        </ARow>

        <FormItem class="enter-x">
          <Button type="primary" class="sub-button" block @click="handleLogin" :loading="loading">
            {{ t('登录') }}
          </Button>
          <!-- <Button size="large" class="mt-4 enter-x" block @click="handleOk">
            {{ t('注册') }}
          </Button> -->
        </FormItem>
        <!-- <ARow class="enter-x">
      <ACol :md="8" :xs="24">
        <Button block @click="setLoginState(LoginStateEnum.MOBILE)">
          {{ t('手机登录') }}
        </Button>
      </ACol>
      <ACol :md="8" :xs="24" class="!my-2 !md:my-0 xs:mx-0 md:mx-2">
        <Button block @click="setLoginState(LoginStateEnum.QR_CODE)">
          {{ t('二维码登录') }}
        </Button>
      </ACol>
      <ACol :md="6" :xs="24">
        <Button block @click="setLoginState(LoginStateEnum.REGISTER)">
          {{ t('注册') }}
        </Button>
      </ACol>
    </ARow> -->

<!--        <a-divider class="enter-x">{{ t('其他登录方式') }}</a-divider>-->
      </div>
      <!-- <div style="height: 1000px; width: 800px" v-else>
      <iframe id="iframeId" style="height: 100%; width: 100%" :src="authorizeUrl"></iframe>
    </div> -->

<!--      <div class="text-center" :class="`${prefixCls}-sign-in-way`">-->
<!--        <WechatOutlined @click="oauthLogin('wechat_enterprise')" class="methods-icon mr-5" />-->
<!--        <DingdingOutlined @click="oauthLogin('dingtalk')" class="methods-icon" />-->
<!--      </div>-->
    </Form>

    <Modal
      v-model:visible="visibleChange"
      title="首次登陆修改密码"
      @ok="handleSubmit"
      width="600px"
      :getContainer="getCustomContainer"
    >
      <div style="padding: 20px">
        <BasicForm @register="register" />
      </div>
    </Modal>
  </div>
</template>
<script lang="ts" setup>
  import { reactive, ref, unref, computed, onMounted } from 'vue';

  import { Checkbox, Form, Input, Row, Col, Button, Modal } from 'ant-design-vue';
  import { WechatOutlined, DingdingOutlined } from '@ant-design/icons-vue';
  // import LoginFormTitle from './LoginFormTitle.vue';

  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 '/@/hooks/web/useDesign';
  import { Base64 } from 'js-base64';
  //import { onKeyStroke } from '@vueuse/core';
  import IconFontSymbol from '/@/components/IconFontSymbol/Index.vue';
  import { getCaptchaImg, getOauthAuthorizeUrl } from '/@/api/system/login';
  import { useRouter } from 'vue-router';
  import { AesEncryption, encryptByBase64 } from '/@/utils/cipher';
  import { useForm } from '/@/components/Form/src/hooks/useForm';
  import { BasicForm, FormSchema } from '/@/components/Form';
  import { firstUpdatePassword } from '/@/api/system/user';
  import { useHeaderSetting } from '/@/hooks/setting/useHeaderSetting';
  // import { nextTick } from 'vue';
  const ACol = Col;
  const ARow = Row;
  const FormItem = Form.Item;
  const InputPassword = Input.Password;
  const { t } = useI18n();
  const { notification, createErrorModal } = useMessage();
  const { prefixCls } = useDesign('login');
  const userStore = useUserStore();

  const { currentRoute } = useRouter();

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

  const formRef = ref();
  // const iframeRef = ref();
  const loading = ref(false);
  const rememberMe = ref(false);
  const boxRef = ref();
  const getCustomContainer = () => boxRef.value;
  const showFlag = ref(false);
  const authorizeUrl = ref('');
  const visibleChange = ref(false);
  const changeToken = ref('');

  const formData = reactive({
    account: 'admin',
    password: 'Qwe123',
    code: '',
    captchaImg: '',
    captchaKey: '',
    showCaptcha: true,
  });
  async function getImg() {
    try {
      let capRes = await getCaptchaImg();
      formData.captchaImg = capRes.imgBase64Data;
      formData.captchaKey = capRes.key;
    } catch (error) {}
  }
  onMounted(async () => {
    formData.showCaptcha = getShowCaptcha.value;
    if (formData.showCaptcha) await getImg();
    //如果是第三方登录跳转回来 会携带token
    if (currentRoute.value.query.token) {
      try {
        loading.value = true;
        const userInfo = await userStore.oauthLogin({
          token: currentRoute.value.query.token as string,
          mode: 'none', //不要默认的错误提示
        });
        if (userInfo) {
          notification.success({
            message: t('登录成功'),
            description: `${t('欢迎回来')}: ${userInfo.name}`,
            duration: 3,
          });
        }
      } catch (error) {
        createErrorModal({
          title: t('错误提示'),
          content:
            (error as unknown as Error).message || t('网络异常，请检查您的网络连接是否正常!'),
          getContainer: () => document.body.querySelector(`.${prefixCls}`) || document.body,
        });
      } finally {
        loading.value = false;
      }
    }
    //如果第三方登录 登录错误 会携带错误信息
    if (currentRoute.value.query.error) {
      createErrorModal({
        title: t('错误提示'),
        content: t(currentRoute.value.query.error as string),
        getContainer: () => document.body.querySelector(`.${prefixCls}`) || document.body,
      });
    }
    const loginInfo = window.localStorage.getItem('USER__LOGIN__INFO__');
    if (loginInfo) {
      formData.account = Base64.decode(JSON.parse(loginInfo).account);
      formData.password = Base64.decode(JSON.parse(loginInfo).password);
    }
  });

  const pwdScore = ref(0);
  const formSchema: FormSchema[] = [
    {
      field: 'newPassword',
      label: t('新密码'),
      component: 'StrengthMeter',
      componentProps: {
        placeholder: t('新密码'),
        onChange: (_, score) => {
          pwdScore.value = score;
        },
      },
      rules: [
        {
          validator: (_, value) => {
            if (!value) {
              return Promise.reject('请输入新密码');
            }
            if (pwdScore.value < 50) {
              return Promise.reject('密码强度设置过低，请至少保证中等强度。');
            }
            return Promise.resolve();
          },
          trigger: 'change',
        },
      ],
      colProps: {
        span: 24,
      },
    },
    {
      field: 'confirmPassword',
      label: t('确认密码'),
      component: 'InputPassword',
      colProps: {
        span: 24,
      },

      dynamicRules: ({ values }) => {
        return [
          {
            required: true,
            validator: (_, value) => {
              if (!value) {
                return Promise.reject(t('密码不能为空'));
              }
              if (value !== values.newPassword) {
                return Promise.reject(t('两次输入的密码不一致!'));
              }
              return Promise.resolve();
            },
          },
        ];
      },
    },
  ];
  const [register, { validate }] = useForm({
    showActionButtonGroup: false,
    schemas: formSchema,
    layout: 'vertical',
  });
  const { validForm } = useFormValid(formRef);

  //onKeyStroke('Enter', handleLogin);

  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN);
  const { getShowCaptcha } = useHeaderSetting();
  async function handleLogin() {
    const data = await validForm();

    //对称加密
    const encryption = new AesEncryption({
      key: '1234567890123456', //MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAILpJXAOe3EwQfZkbIaUsCCa6J8dqTpEbDpHlB8Yu8N9aMhgjoMcbhMp4cVF9nb3inJIWOmYj4y6Tj4XYCVMd3cCAwEAAQ==
    });

    //非对称加密
    //rsa_encrypt(data.password)
    if (!data) return;
    try {
      loading.value = true;
      const userInfo = await userStore.login(
        {
          password: encryptByBase64(encryption.encryptByAES(data.password)),
          userName: data.account,
          deviceType: 0, //pc-0,app-1
          mode: 'none', //不要默认的错误提示
          code: formData.code,
        },
        formData.showCaptcha ? formData.captchaKey : '',
      );
      if (userInfo) {
        notification.success({
          message: t('登录成功'),
          description: `${t('欢迎回来')}: ${userInfo.name}`,
          duration: 3,
        });
        if (
          Number.parseInt(userInfo.pwdExpireDate) > 0 &&
          Number.parseInt(userInfo.pwdExpireDate) <= 5
        ) {
          notification.info({
            message: t('提醒'),
            description: `密码还有 ${userInfo.pwdExpireDate} 天过期，请及时修改密码!`,
            duration: 3,
          });
        }
        if (rememberMe.value) {
          const info = {
            account: Base64.encode(data.account),
            password: Base64.encode(data.password),
          };
          window.localStorage.setItem('USER__LOGIN__INFO__', JSON.stringify(info));
        } else {
          window.localStorage.removeItem('USER__LOGIN__INFO__');
        }
      }
    } catch (error: any) {
      if (error.firstLogin || error.pwdExpireDate <= 0) {
        visibleChange.value = true;
        changeToken.value = error.token;
      } else {
        createErrorModal({
          title: t('错误提示'),
          content:
            (error as unknown as Error).message || t('网络异常，请检查您的网络连接是否正常!'),
          getContainer: () => document.body.querySelector(`.${prefixCls}`) || document.body,
        });
      }
    } finally {
      loading.value = false;
    }
  }

  async function handleSubmit() {
    try {
      const values = await validate();
      // const { passwordOld, passwordNew } = values;

      // TODO custom api
      let res = await firstUpdatePassword(values, changeToken.value);
      if (res) {
        notification.success({
          message: t('修改密码成功,请重新登录!'),
          duration: 3,
        });
        visibleChange.value = false;
      }
    } catch (error) {}
  }

  async function oauthLogin(source: string) {
    showFlag.value = true;
    authorizeUrl.value = await getOauthAuthorizeUrl(source);
    window.location.href = authorizeUrl.value;
  }
</script>
<style lang="less" scoped>
  .form-box {
    font-size: 16px;
  }

  .f-16 {
    font-size: 16px;
  }

  :deep(.ant-checkbox-inner) {
    border-color: #ced5f2;
    width: 18px;
    height: 18px;
    border-radius: 0;
  }

  :deep(.ant-form-item input[type='checkbox']) {
    width: 18px;
    height: 18px;
  }

  .form-title {
    line-height: 40px;
    color: #999;
  }

  .sub-button {
    height: 60px;
    font-size: 20px;
    border-radius: 16px;
    margin-top: 60px;
  }

  .ant-form label {
    font-size: 16px;
  }

  .user-icon {
    font-size: 26px;
    margin-right: 8px;
    color: #333;
  }

  :deep(.ant-divider-inner-text) {
    color: #333 !important;
    font-size: 14px !important;
  }

  .ant-input-affix-wrapper {
    border-color: #ced5f2;
    border-style: none none solid;
  }

  :deep(.ant-input-password-icon) {
    font-size: 20px;
    color: #707c92;
    margin-right: 8px;
  }

  :deep(.ant-input-affix-wrapper-lg) {
    padding-left: 0;
  }

  .methods-icon {
    width: 30px;
    height: 30px;
    border: 1px solid #f1f1f1;
    border-radius: 50%;
    background: #f1f1f1;
    padding: 5px;
  }

  :deep(.vben-login-sign-in-way .anticon) {
    color: #cdcdcd;
    font-size: 18px;
  }
</style>
