/* eslint-disable no-plusplus */
import { CoreConst } from '@ibiz-template/core';
import {
  defineComponent,
  getCurrentInstance,
  onMounted,
  reactive,
  Ref,
  ref,
} from 'vue';
import { clearCookie, setCookie } from 'qx-util';
import { useNamespace, useRoute } from '@ibiz-template/vue-util';
import router from '@/router';
import './app-login-extend.scss';

interface LoginData {
  username: string;
  password: string;
  verificationCode: string;
}

const rules = {
  username: [
    {
      required: true,
      message: '请输入账号',
      trigger: 'blur',
    },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur',
    },
    {
      type: 'string',
      min: 6,
      message: '密码长度不能少于6位',
      trigger: 'blur',
    },
  ],
  verificationCode: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'blur',
    },
  ],
};

export default defineComponent({
  setup() {
    const ns = useNamespace('login-extend');

    const loginData = reactive<LoginData>({
      username: '',
      password: '',
      verificationCode: '',
    });

    const formRef = ref<IData | null>(null);

    const instance = getCurrentInstance()!;
    const route = useRoute(instance.proxy);
    const ru = (route.query.ru as string) || '/';

    ibiz.appData = undefined;
    ibiz.orgData = undefined;

    const timer: Ref<ReturnType<typeof setInterval> | null> = ref(null);

    const countdown = ref(0);

    const showPwd = ref(false);

    onMounted(() => {
      setTimeout(() => {
        const el = document.querySelector('.app-loading-x') as HTMLDivElement;
        if (el) {
          el.style.display = 'none';
        }
      }, 300);
    });

    const loading = ref(false);

    const onClick = () => {
      formRef.value!.validate(async (valid: boolean) => {
        if (valid) {
          try {
            loading.value = true;
            clearCookie(CoreConst.TOKEN, true);
            let password = loginData.password;
            let verificationcode = loginData.verificationCode;
            if ((ibiz.env as IData).enableRSA) {
              password = ibiz.util.text.rsa(password);
              verificationcode = ibiz.util.text.rsa(verificationcode);
            }
            const res = await ibiz.net.post('/v7/loginPwd', {
              loginname: loginData.username,
              password,
              verificationcode,
            });
            if (res.ok) {
              const { data } = res;
              if (data && data.token) {
                setCookie(CoreConst.TOKEN, data.token, 0, true);
                const expiredDate =
                  new Date().getTime() + (data.expirein || 7199) * 1000;
                setCookie(CoreConst.TOKEN_EXPIRES, `${expiredDate}`, 0, true);
                router.push({ path: ru });
                return;
              }
            }
            ibiz.notification.error({
              title: res.data?.message?.includes('用户名或密码错误')
                ? '用户名或密码错误'
                : '登录失败',
            });
            loading.value = false;
          } catch (error) {
            ibiz.notification.error({
              title: (error as IData).response?.data?.message?.includes(
                '用户名或密码错误',
              )
                ? '用户名或密码错误'
                : '登录失败',
            });
            loading.value = false;
          }
        }
      });
    };

    const onForget = async () => {
      const modal = ibiz.overlay.createModal(
        'ForgetPassword',
        {
          dismiss: (result: IData) => {
            modal.dismiss(result);
          },
        },
        {
          width: 'auto',
          placement: 'center',
        },
      );
      modal.present();
      await modal.onWillDismiss();
    };

    const standCountdown = () => {
      countdown.value = 60;
      timer.value = setInterval(() => {
        if (countdown.value > 1) {
          countdown.value--;
        } else if (timer.value) {
          countdown.value--;
          clearInterval(timer.value);
          timer.value = null;
        }
      }, 1000);
    };

    const sendVerificationCode = () => {
      const { username } = loginData;
      let { password } = loginData;
      if (!username) {
        ibiz.notification.warning({
          title: '请先输入账号',
        });
        return;
      }
      if (!password) {
        ibiz.notification.warning({
          title: '请先输入密码',
        });
        return;
      }
      if (ibiz.env.enableRSA) {
        password = ibiz.util.text.rsa(password);
      }
      ibiz.net
        .post(`/v7/loginPwd/sendVerificationCode/${username}`, {
          loginname: username,
          password,
        })
        .then((res: IData) => {
          standCountdown();
          if (res.ok) {
            ibiz.notification.success({
              title: '获取验证码成功',
            });
          } else {
            ibiz.notification.error({
              title: res.data?.message || '获取验证码失败',
            });
          }
        })
        .catch((err: IData) => {
          standCountdown();
          ibiz.notification.error({
            title: (err as IData).response?.data?.message || '获取验证码失败',
          });
        });
    };

    return () => (
      <div class={ns.b()}>
        <div class={ns.b('box')}>
          <header class={ns.b('box-header')}>
            <img src='./assets/img/login-header.png' />
          </header>
          <main class={ns.b('box-main')}>
            <img
              class={ns.be('box-main', 'avatar')}
              src='./assets/img/login-avatar.png'
            />
            <div class={ns.b('box-main-content')}>
              <i-form ref={formRef} props={{ model: loginData, rules }}>
                <i-form-item prop='username'>
                  <i-input
                    type='text'
                    value={loginData.username}
                    on-on-change={(evt: InputEvent) => {
                      const { value } = evt.target as HTMLInputElement;
                      loginData.username = value;
                    }}
                    on-on-enter={onClick}
                    placeholder='请输入账号'
                    size='large'
                  >
                    <i-icon type='md-person' slot='prefix'></i-icon>
                  </i-input>
                </i-form-item>
                <i-form-item prop='password'>
                  <i-input
                    type='text'
                    class={[ns.e('password'), ns.is('show-pwd', showPwd.value)]}
                    value={loginData.password}
                    on-on-change={(evt: InputEvent) => {
                      const { value } = evt.target as HTMLInputElement;
                      loginData.password = value;
                    }}
                    on-on-enter={onClick}
                    on-on-click={() => {
                      showPwd.value = !showPwd.value;
                    }}
                    placeholder='请输入密码'
                    size='large'
                    icon={showPwd.value ? 'ios-eye' : 'ios-eye-off'}
                  >
                    <i-icon type='ios-unlock' slot='prefix'></i-icon>
                  </i-input>
                </i-form-item>
                <i-form-item
                  prop='verificationCode'
                  class={ns.e('verification')}
                >
                  <i-input
                    type='number'
                    value={loginData.verificationCode}
                    on-on-change={(evt: InputEvent) => {
                      const { value } = evt.target as HTMLInputElement;
                      loginData.verificationCode = value;
                    }}
                    placeholder='请输入验证码'
                  ></i-input>
                  <i-button
                    class={ns.is('disabled', !!timer.value)}
                    disabled={!!timer.value}
                    on-click={sendVerificationCode}
                  >
                    {countdown.value > 0
                      ? `${countdown.value}秒后重发`
                      : '获取验证码'}
                  </i-button>
                </i-form-item>
                <i-button type='text' on-click={onForget}>
                  忘记密码
                </i-button>
                <i-form-item>
                  <i-button
                    shape='circle'
                    loading={loading.value}
                    long
                    on-click={onClick}
                  >
                    登录
                  </i-button>
                </i-form-item>
              </i-form>
            </div>
          </main>
        </div>
      </div>
    );
  },
});
