import type { Menu, UserInfo } from '@vben/types'

import { get } from '../http'

// 乐贝交易的菜单id
const menu_id_coin_trade = '1957734936005869570'
// 题库的菜单id
const menu_id_question_bank = '1943169497070133250'
const school_id_xmg = '1938652617362116609'
const provider_id_xmg = '1947926953075937282'
const school_id_qz = '125'
// 黄埔小学
const school_id_hp = '1947919485528707073'
// 财务角色的id
const role_id_finance = '1960274392807198721'

const removeMenus = (menus: Menu[], excludeIds: any[]) => {
  if (!menus?.length) return menus
  if (!excludeIds?.length) return menus
  const newMenus = []
  for (const menu of menus) {
    if (excludeIds.includes(menu.id)) continue
    newMenus.push(menu)
    if (menu.children?.length) {
      menu.children = removeMenus(menu.children, excludeIds)
    }
  }
  return newMenus
}

const initMenus = (user: UserInfo) => {
  if (!user.menus?.length) return
  // 排除的菜单id
  const excludeIds = []
  // 菜单
  if (!user.canBuildQuestion) {
    // 去掉题库菜单
    excludeIds.push(menu_id_question_bank)
  }
  if (!user.canShowCoinTrade) {
    // 去掉题库菜单
    excludeIds.push(menu_id_coin_trade)
  }
  user.menus = removeMenus(user.menus, excludeIds)
}

/**
 * 获取用户信息
 */
const getUserInfo = async () => {
  const user = await get<UserInfo>('/getLoginUser')
  // 用户信息处理
  if (typeof user.personConfig === 'string') {
    user.personConfig = JSON.parse(user.personConfig)
  }
  // 超管
  user.isSuperAdmin = Number(user.adminType) === 1
  // 是否为学校机构的员工
  user.isStaff = !!user.schoolId
  // 是否可以建设题库（暂时是勤智、小码哥的老师）
  user.canBuildQuestion =
    user.isSuperAdmin ||
    user.schoolId === school_id_qz ||
    user.schoolId === school_id_xmg ||
    user.schoolId === school_id_hp
  // 是否为财务人员
  user.isFinance =
    user.isSuperAdmin || user.roles?.some((item) => item.id === role_id_finance)

  // 是否可以显示【乐贝交易】
  user.canShowCoinTrade = user.isSuperAdmin || user.buyerFlag || user.sellerFlag

  // 是否为自己人（小码哥的）
  user.isSelf =
    user.schoolId === school_id_xmg || user.providerId === provider_id_xmg
  // 是否为服务商的员工
  user.isSpStaff = !!user.providerId
  // 是否只是学校的员工
  user.isOnlyStaff = user.isStaff && !user.isSpStaff

  // 是否为公益组织
  user.publicOrgFlag = user.publicOrgFlag || user.isSuperAdmin

  // 菜单
  initMenus(user)
  return user
}

const UserApi = {
  getUserInfo,
}

export default UserApi
