import { useRoute, useRouter } from 'vue-router';
import { Message } from '@arco-design/web-vue';
import { sysMenu } from '@/api/user';

import { AESDecode } from '../utils/crypto';
import { UserState } from '../store/modules/user/types';
import { AppState } from '../store/modules/app/types';
import { useUserStore, useAppStore } from '../store';

export default function useSilenceAuth() {
  const router = useRouter();
  const route = useRoute();
  const appStore = useAppStore();
  const userStore = useUserStore();

  function registSilenceAuthEvent() {
    window.electron.onSilenceAuthority((authKey: string) => {
      window.api.logger(`app onSilenceAuthority => authKey:${authKey}`);
      silenceAuthorityHandle(authKey);
    });
  }

  function silenceAuthorityHandle(authKey: string) {
    if (!authKey) return;

    if (authKey.startsWith('trd://launcher')) {
      silenceLauncher();
      return;
    }

    if (authKey.startsWith('trd://download')) {
      silenceDownload(authKey);
      return;
    }

    window.api.logger(`error authKey data`, 'error');
  }
  // 打开工具登录界面
  function silenceLauncher() {
    if (route.name === 'Login') return;

    router.push({ name: 'Login' });
  }

  interface AuthData {
    user: Partial<UserState>;
    apiUrl: string;
    actionSession: AppState['actionSession'];
    downloadSet: AppState['downloadSet'];
  }

  // 静默登录下载
  async function silenceDownload(authKey: string) {
    const paramData = authKey.replace('trd://download/?q=', '');
    let authData: AuthData | null = null;
    try {
      authData = JSON.parse(AESDecode(paramData));
    } catch (error) {
      window.api.logger(`authData: 解析错误！`);
    }
    if (!authData) return;
    window.api.logger(`authData: ${JSON.stringify(authData)}`);

    // 防止重复执行
    if (authData.actionSession === appStore.actionSession) {
      window.api.logger(`[warning] 重复的actionSession！`);
      return;
    }
    // 有任务在进行，不做任何处理
    if (appStore.downloadTaskRunning) {
      window.api.logger(`[warning] 当前有任务正在进行！`);
      return;
    }

    // console.log(authData);
    const user = authData.user;
    if (!user || !user.accessToken) return;

    // 登录人切换警告
    if (userStore.id && userStore.id !== user.id) {
      Message.warning('登录人信息改变！');
      window.api.logger(`[warning] 登录人信息改变！`);
    }

    appStore.setInfo({
      domain: authData.apiUrl,
      actionSession: authData.actionSession || '',
      downloadSet: authData.downloadSet || null,
    });

    user.privilegeId = '';
    userStore.setInfo(user);

    const menuRes = await sysMenu();
    const validMenu = menuRes.privileges.find(
      (item) => item.url === 'ScoreManage'
    );
    if (!validMenu) {
      userStore.resetInfo();
      appStore.setInfo({
        actionSession: '',
        downloadSet: null,
      });
      recoverSystemDomain();
      Message.error('您没有权限！');
      return;
    }
    userStore.setInfo({ privilegeId: validMenu.id });
    await updateSystemDomain(authData.apiUrl);

    if (route.name === 'TrackExport') {
      window.api.logger(`TrackExport 页面刷新`);
      window.location.reload();
      return;
    }

    window.api.logger(`进入 TrackExport 页面`);
    router.push({ name: 'TrackExport' });
  }

  async function updateSystemDomain(domain: string) {
    await window.db.updateDict({ key: 'domain', val: domain });
  }

  async function recoverSystemDomain() {
    const domain = await window.db.getDict('domain');
    appStore.setInfo({
      domain,
    });
  }

  return {
    registSilenceAuthEvent,
    silenceAuthorityHandle,
  };
}
