import {
  oidcClientComputed,
  oidcClientMethods,
} from '@state/modules/oidc-client';
import { i18nComputed, i18nMethods } from '@state/modules/i18n';
import { utilsAppMethods } from '@state/modules/utils/app';
import Vue from 'vue';
import { mapGetters } from 'vuex';
import { Component, Mixins, Watch } from 'vue-property-decorator';
import MDrawer from '@components/m-drawer.vue';
import { applyDicts } from '@/plugins/i18n';
import WebsocketsPlugin from '@plugins/websockets';
import { messageReceive } from '@utils/broadcast';
import ReportDialog from '../../report-dialog/index.vue';
import { CollapsedProfileApi } from '@openapi/idm';
import ActivityRecorderPlugin from '@/recruits/plugins/activity-recorder';
import ConfirmActiveModal from '@/recruits/components/dialogs/ConfirmActiveModal.vue';

const сollapsedProfileApi = new CollapsedProfileApi();

Vue.use(WebsocketsPlugin);
Vue.use(ActivityRecorderPlugin);

const oidcClientMixin = Vue.extend({
  computed: {
    ...oidcClientComputed,
  },
  methods: {
    ...oidcClientMethods,
  },
});

const i18nMixin = Vue.extend({
  computed: {
    ...i18nComputed,
  },
  methods: {
    ...i18nMethods,
  },
});
const utilsMixin = Vue.extend({
  methods: {
    ...utilsAppMethods,
  },
});

@Component({
  components: {
    MDrawer,
    ReportDialog,
    ConfirmActiveModal,
  },
  computed: {
    ...mapGetters('mfeContainer', ['mfeModuleLoading']), 
  },  
})
export default class LayoutMain extends Mixins(
  oidcClientMixin,
  i18nMixin,
  utilsMixin
) {
  public drawer = false;
  hideUserTooltip = false;
  private defaultBackgroundCssDefinition = () => ({
    'redesigned-background': false,
    'white-background': false,
  });

  public backgroundCss = this.defaultBackgroundCssDefinition();

  @Watch('$route', { immediate: true })
  private routeWatcher(to: { name: string }): void {
    switch (to.name) {
      case 'list-of-recruits':
      case 'list-of-lists':
      case 'statements':
      case 'recruit-personal':
      case 'recruit-details':
      case 'recruit-documents':
      case 'recruit-history':
      case 'recruit-pf-requests':
        this.backgroundCss = {
          ...this.defaultBackgroundCssDefinition(),
          'redesigned-background': true,
        };
        break;
      case 'cards':
        this.backgroundCss = {
          ...this.defaultBackgroundCssDefinition(),
          'white-background': true,
        };
        break;
      default:
        this.backgroundCss = this.defaultBackgroundCssDefinition();
    }
  }

  private created(): void {
    if (this.isLoggedIn) {
      this.init().finally(() => {
        if (this.$route.path === '/') {
          const prevUrl = window.localStorage.getItem('prev_url');

          console.log('rourer', this.$router);
          if (prevUrl) {
            window.localStorage.removeItem('prev_url');

            this.$router.push({
              path: prevUrl,
            });
          } else {
            this.$router.push({
              // Стартовый раздел по умолчанию
              name: 'start',
            });
          }
        }
      });
    } else {
      this.loginOidcClient();
    }
  }

  private beforeMount() {
    function isPathNameInclude(string: string) {
      return window.location.pathname.indexOf(string) !== -1;
    }
    // Это костыль для редиректа на разные методы входа для front-idm-micro
    if (!this.isLoggedIn) {
      if (
        !isPathNameInclude('statements') &&
        !isPathNameInclude(`${process.env.VUE_APP_PROJECT_PATH}/start`)
      ) {
        if (isPathNameInclude('admin')) {
          sessionStorage.setItem('additionalUrlPath', '/admin');
        } else {
          sessionStorage.removeItem('additionalUrlPath');
        }
      }
    }
    this.subscribeReportHotkeyEvent();
  }

  private beforeDestroy() {
    this.unsubscribeReportHotkeyEvent();
  }

  get organizationName(): string {
    return this.$store.getters['idm/organizations/organizationName'] || '';
  }

  initAcessController() {
    const user = this.$store.state.oidcClient.currentUser;
    const hide = localStorage.getItem('userHiderInfo');
    if (hide) this.hideUserTooltip = !!hide;
    this.$AC.init(user);
  }

  private init(): Promise<void> {
    return new Promise((resolve, reject) => {
      this.initAcessController();

      applyDicts([
        'Account',
        'Solution',
        'Petition',
        'Resource',
        'Organization',
        'Department',
      ]);

      this.dispatchLocale({
        locale: this.locale,
      });

      this.$emit('changeLoadCount', 1);

      сollapsedProfileApi
        .getCollapsedProfile()
        .then(({ data }) => {
          if (data.lang) {
            this.dispatchLocale({
              locale: data.lang,
            });
          }

          if (data.colorScheme) {
            this.dispatchTheme({
              theme: data.colorScheme,
            });
          }

          if (data.timezone) {
            this.dispatchTimezone({
              timezone: data.timezone,
            });
          }

          window.addEventListener('storage', messageReceive);
          this.$emit('changeLoadCount', -1);
          resolve();
        })
        .catch(() => {
          this.$emit('changeLoadCount', -1);
          reject();
        });
    });
  }

  private openProfilePage(): void {
    this.$router.push({
      name: 'profile',
    });
  }

  private signIn(): void {
    this.loginOidcClient();
  }

  private signOut(): void {
    this.logoutOidcClient();
  }

  private toggleDrawer(): void {
    this.drawer = !this.drawer;
  }

  private subscribeReportHotkeyEvent() {
    window.addEventListener('keydown', this.onReportHotkeysKeydownEventHandler);
  }

  private unsubscribeReportHotkeyEvent() {
    window.removeEventListener(
      'keypress',
      this.onReportHotkeysKeydownEventHandler
    );
  }

  private onReportHotkeysKeydownEventHandler(e: KeyboardEvent) {
    if (e.ctrlKey && e.key === 'Enter') {
      // Ctrl-Enter pressed
      (this.$refs.reportDialog as any).show();
    }
  }

  handlerFormHideUserInfo() {
    this.hideUserTooltip = !this.hideUserTooltip;
    localStorage.setItem('userHiderInfo', this.hideUserTooltip ? '' : '1');
  }
}
