import { CoreConst } from '@ibiz-template/core';
import {
  defineComponent,
  getCurrentInstance,
  onMounted,
  reactive,
  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;
}

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

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

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

    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;

    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;
            if ((ibiz.env as IData).enableSM3) {
              password = ibiz.util.text.sm3(password).toUpperCase();
            }
            const res = await ibiz.auth.v7login(loginData.username, password);
            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 || '登录失败',
            });
            loading.value = false;
          } catch (error) {
            ibiz.notification.error({
              title: (error as IData).response?.data?.message || '登录失败',
            });
            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();
    };

    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='password'
                    value={loginData.password}
                    on-on-change={(evt: InputEvent) => {
                      const { value } = evt.target as HTMLInputElement;
                      loginData.password = value;
                    }}
                    on-on-enter={onClick}
                    placeholder='请输入密码'
                    size='large'
                    password
                  >
                    <i-icon type='ios-unlock' slot='prefix'></i-icon>
                  </i-input>
                </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>
    );
  },
});
