import LoginApi from '@/pages/login/login-api.ts'
import Colls from '@/common/utils/colls.ts'
import { useAppSettingStore } from '@/common/app/app-setting-store.ts'
import { useAppUserStore } from '@/common/app/app-user-store.ts'
import Utils from '@/common/utils'
import type { R } from '@/common/utils/http-util.ts'
import { MenuCategory } from '@/common/app/constants.ts'
import AppApi from '@/common/app/app-api.ts'

const home = {
  'id': '-1',
  'sn': 'menus',
  'pid': '0',
  'title': '首页',
  'icon': 'home-3-line',
  'tier': 1,
  'breadcrumb': [
    '首页',
  ],
  'menuCategory': MenuCategory.Page,
  'freeze': null,
  'sort': 0,
  'routeName': 'home',
  'path': '/home',
}

export function reloadUserInfo() {
  const appSettingStore = useAppSettingStore()
  const appUserStore = useAppUserStore()
  return LoginApi.my()
    .then(({data}) => {
      const menuTree = Utils.clone(Colls.toTree(data.menus))
      data.menus.unshift(home)
      menuTree.unshift(home)
      appSettingStore.$patch({
        menus: data.menus, menuTree,
        theme: data.setting?.theme ?? 'light',
        collectedMenus: data.setting?.collectedMenus ?? [],
        logo: data.setting?.logo,
        language: data.setting?.language ?? 'zh',
      })
      appUserStore.$patch({
        userId: data.id,
        nickname: data.nickname,
        avatar: data.avatar,
        tenantId: data.tenantId,
        tenantName: data.tenantName,
        roles: data.roles,
        currentCustomerId: data.currentCustomerId,
        identities: data.identities,
        currentIdentity: data.currentIdentity,
        hasCaiGou: data.hasCaiGou,
        isCaiGou: data.isCaiGou,
        hasChanFei: data.hasChanFei,
        isChanFei: data.isChanFei,
        hasSiJi: data.hasSiJi,
        isSiJi: data.isSiJi,
        hasXiaoNa: data.hasXiaoNa,
        isXiaoNa: data.isXiaoNa,
        hasYunShu: data.hasYunShu,
        isYunShu: data.isYunShu,
        isAdmin: data.isAdmin,
      })
    })
}

export function hasPermission(resSn?: string) {
  const appSettingStore = useAppSettingStore()
  const res = appSettingStore.menus.find(it => it.sn === resSn)
  return res != null
}

export function changeIdentity(id: string) {
  return AppApi.changeIdentity(id)
    .then(reloadUserInfo)
}

export function saveFile(r: Promise<R<{ content: Blob, filename: string }>>, defaultName: string = '下载的文件') {
  return r.then(res => {
    const blobURL = window.URL.createObjectURL(res.data.content)
    const tempLink = document.createElement('a')
    try {
      tempLink.style.display = 'none'
      tempLink.href = blobURL
      tempLink.setAttribute('download', decodeURI(res.data.filename ?? defaultName))
      if (typeof tempLink.download === 'undefined') {
        tempLink.setAttribute('target', '_blank')
      }
      document.body.appendChild(tempLink)
      tempLink.click()
      return Promise.resolve()
    } catch (e) {
      console.log('下载失败', e)
      return Promise.reject()
    } finally {
      if (tempLink != null) document.body.removeChild(tempLink)
      if (blobURL != null) window.URL.revokeObjectURL(blobURL)
    }
  })
}
