import { defineComponent } from 'vue';
import { useNamespace } from '@ibiz-template/vue-util';
import '@ibiz-template/theme/style/components/common/app-user/app-user.scss';

export const AppUser = defineComponent({
  name: 'AppUser',
  setup() {
    const ns = useNamespace('app-user');
    const { srfusername = '游客' } = ibiz.appData?.context || {};
    return { ns, srfusername };
  },
  methods: {
    async onClick() {
      const res = await ibiz.auth.v7logout();
      if (res.ok) {
        ibiz.message.success('登出成功');
        this.$router.push(
          `/login?ru=${encodeURIComponent(
            window.location.hash.replace('#/', '/'),
          )}`,
        );
      } else {
        ibiz.message.error('登出失败');
      }
    },
    async changePwd() {
      const modal = ibiz.overlay.createModal(
        'ChangePassword',
        {
          dismiss: (result: IData) => {
            modal.dismiss(result);
          },
        },
        {
          width: 'auto',
          placement: 'center',
        },
      );
      modal.present();
      await modal.onWillDismiss();
    },
  },
  render() {
    return (
      <div class={this.ns.b()}>
        <i-dropdown
          class={[
            this.ns.b('avatar'),
            this.ns.is('disabled', ibiz.env.disableLogout),
          ]}
        >
          <span class={this.ns.b('avatar-wrapper')}>
            <i-avatar size='small' src='./assets/img/avatar.png' />
            <span class={this.ns.be('avatar', 'name')}>{this.srfusername}</span>
            <span
              class={[
                this.ns.be('avatar', 'arrow'),
                this.ns.is(
                  'hidden',
                  ibiz.env.disableChangePwd && ibiz.env.disableLogout,
                ),
              ]}
            >
              <i-icon type='ios-arrow-down' />
            </span>
          </span>
          {ibiz.env.disableChangePwd ? null : (
            <i-dropdown-menu slot='list'>
              <i-dropdown-item>
                <i class='ivu-icon ivu-icon-ios-create-outline'></i>
                <span on-click={this.changePwd}>修改密码</span>
              </i-dropdown-item>
            </i-dropdown-menu>
          )}
          {ibiz.env.disableLogout ? null : (
            <i-dropdown-menu slot='list'>
              <i-dropdown-item>
                <i class='ivu-icon ivu-icon-ios-log-out'></i>
                <span on-click={this.onClick}>退出登录</span>
              </i-dropdown-item>
            </i-dropdown-menu>
          )}
        </i-dropdown>
      </div>
    );
  },
});
