import { CoreConst } from '@ibiz-template/core';
import {
  defineComponent,
  getCurrentInstance,
  onMounted,
  reactive,
  ref,
} from 'vue';
import { clearCookie, setCookie } from 'qx-util';
import { useNamespace, useRoute, useRouter } from '@ibiz-template/vue-util';
import './kq-login-view.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('kq-login-view');

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

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

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

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

    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);
            const res = await ibiz.auth.v7login(
              loginData.username,
              loginData.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?.includes('用户名或密码错误')
                ? '用户名或密码错误'
                : '登录失败',
            });
            loading.value = false;
          } catch (error) {
            ibiz.notification.error({
              title: (error as IData).response?.data?.message?.includes(
                '用户名或密码错误',
              )
                ? '用户名或密码错误'
                : '登录失败',
            });
            loading.value = false;
          }
        }
      });
    };

    const onResetClick = () => {
      loginData.username = '';
      loginData.password = '';
    };

    return () => (
      <div class={ns.b()}>
        <div class={ns.b('box')}>
          <div class={ns.b('box-left')}>
            <div class={ns.b('box-left-top')}>
              <img
                class={ns.b('box-left-top-jh')}
                src='./assets/img/user-login/jh-800.png'
              />
              <div class={ns.b('box-left-top-text')}>
                <div>江苏省检察机关</div>
                <div>一体化考勤管理平台</div>
              </div>
            </div>
            <div class={ns.b('main-content')}>
              <i-form ref={formRef} props={{ model: loginData, rules }}>
                <i-form-item prop='username'>
                  <div class={ns.b('form-label')}>
                    <img src='./assets/img/user-login/usn.svg' />
                    <span class={ns.b('form-label-text')}>用户名</span>
                  </div>
                  <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-input>
                </i-form-item>
                <i-form-item prop='password'>
                  <div class={ns.b('form-label')}>
                    <img src='./assets/img/user-login/psd.svg' />
                    <span class={ns.b('form-label-text')}>密码</span>
                  </div>
                  <i-input
                    type='text'
                    value={loginData.password}
                    on-on-change={(evt: InputEvent) => {
                      const { value } = evt.target as HTMLInputElement;
                      loginData.password = value;
                    }}
                    class={[ns.e('password'), ns.is('show-pwd', showPwd.value)]}
                    on-on-enter={onClick}
                    on-on-click={() => {
                      showPwd.value = !showPwd.value;
                    }}
                    placeholder='请输入密码'
                    size='large'
                    icon={showPwd.value ? 'ios-eye' : 'ios-eye-off'}
                  ></i-input>
                </i-form-item>
                <i-form-item class={ns.b('buttons')}>
                  <i-button loading={loading.value} long on-click={onClick}>
                    登录
                  </i-button>
                  <i-button long on-click={onResetClick}>
                    重置
                  </i-button>
                </i-form-item>
              </i-form>
            </div>
          </div>
          <div class={ns.b('box-right')}>
            <img src='./assets/img/user-login/right.png' />
          </div>
        </div>
      </div>
    );
  },
});
