import { reject } from 'lodash-es'
import useRouteStore from './route'
import useMenuStore from './menu'
import { doLogin, getConfig, getInfo, getUserMenus } from '@/api/system/login'
import { changePwd } from '@/api/system/user'
import type { Menu } from '@/global'
import { getPrivateKey, privateStr, setPrivateKey } from '@/utils/auth'

const useUserStore = defineStore(
  // 唯一ID
  'user',
  {
    state: () => ({
      username: localStorage.username || '', // 账户
      token: localStorage.token || '', // token
      id: '', // 用户id
      name: '', // 姓名
      deptId: '', // 部门id
      deptName: '', // 部门名称
      avatar: '', // 头像
      attr1: '', // 备用属性
      tenantId: '', // 租户id
      publicKey: localStorage.publicKey || '', // 公钥
      privateKey: getPrivateKey() || '', // 私钥
      roleList: [] as string[], // 角色id集合
      roleNames: [] as string[], // 角色名称集合
      roleTips: [] as string[], // 角色标签集合
      systems: [] as Menu.menu[], // 子系统权限
      menus: [] as Menu.menu[], // 菜单权限
      btns: [] as Menu.menu[], // 按钮权限
      isLogout: 0, // 是否被退出登录
    }),
    getters: {
      isLogin: (state) => {
        let retn = false
        if (state.token) {
          retn = true
        }
        return retn
      },
      // 是否已获取用户信息
      hasUserInfo: (state) => {
        if (state.roleList && state.roleList.length > 0) {
          return true
        }
        else {
          return false
        }
      },
      getPublicKey: (state) => {
        return state.publicKey
      },
      getPrivateKey: (state) => {
        return state.privateKey
      },
      getMenus: (state): Menu.menu[] => {
        return state.menus
      },
      getBtns: (state): Menu.menu[] => {
        return state.btns
      },
    },
    actions: {
      // 获取项目基础配置
      getBaseConfig() {
        return new Promise<any>((resolve, reject) => {
          getConfig().then((res) => {
            this.publicKey = res.data.publicKey
            localStorage.setItem('publicKey', res.data.publicKey)
            // 保存私钥
            setPrivateKey(privateStr)
            this.privateKey = privateStr
            this.isLogout = 0
            resolve(res.data)
          }).catch((e) => {
            reject(e)
          })
        })
      },
      // 登录
      login(data: {
        username: string
        password: string
        kaptcha: string
        sid: string
      }) {
        return new Promise<void>((resolve, reject) => {
          doLogin(data).then((res) => {
            localStorage.setItem('token', res.data.token)
            this.username = res.data.username
            this.token = res.data.token
            this.isLogout = 0
            resolve()
          }).catch((error) => {
            reject(error)
          })
        })
      },
      // 注销
      logout() {
        return new Promise<void>((resolve) => {
          const routeStore = useRouteStore()
          const menuStore = useMenuStore()
          localStorage.removeItem('username')
          localStorage.removeItem('token')
          localStorage.removeItem('nameId')
          localStorage.removeItem('depId')
          this.username = ''
          this.token = ''
          this.roleList = []
          this.roleNames = []
          routeStore.removeRoutes()
          menuStore.setActived(0)
          resolve()
        })
      },
      // 获取用户信息
      getUserInfo() {
        return new Promise<any>((resolve) => {
          getInfo().then((res) => {
            if (res.data.roleIds && res.data.roleIds.length > 0) {
              this.roleList = res.data.roleIds
              this.roleNames = res.data.roleNames
              this.roleTips = res.data.roleTips
              localStorage.setItem('nameId', res.data.id)
              localStorage.setItem('depId', res.data.deptId)
            }
            else {
              reject('该用户无角色')
            }
            if (res.data.deptId) {
              this.deptId = res.data.deptId
              this.deptName = res.data.deptName
            }
            else {
              reject('该用户无组织机构')
            }
            this.id = res.data.id
            this.username = res.data.account
            this.name = res.data.name
            resolve(res.data)
          }).catch(() => {
            reject('获取用户信息错误')
          })
        })
      },
      // 获取菜单按钮权限
      getPermissions(currentSystem?: { name: string; code: string }) {
        const params = {
          resourceType: '',
          parentCode: '',
        }
        if (currentSystem) {
          params.parentCode = currentSystem.code // 子系统code
        }
        return new Promise<Menu.menu[]>((resolve) => {
          getUserMenus(params).then((response) => {
            const data = response.data
            const menus = [] // 仅菜单
            const btns = [] // 非菜单
            if (data.menus && data.menus.length > 0) {
              const allmenus = [...data.menus]
              this.menus = allmenus
              for (const menu of allmenus) { // 遍历菜单，获取所有的权限项
                if (menu.resourceType === '02' || menu.resourceType === '03') { // 将是菜单的放入menus
                  const menu_tmp = {
                    url: menu.url,
                    name: menu.name,
                    icon: menu.icon,
                  }
                  menus.push(menu_tmp)
                }
                const btn_tmp = {
                  url: menu.url,
                  name: menu.name,
                  icon: menu.icon,
                }
                btns.push(btn_tmp)
              }
            }
            this.menus = menus
            this.btns = btns
            resolve(btns)
          })
        })
      },
      // 修改密码
      editPassword(data: {
        oldPwd: string
        newPwd: string
      }) {
        return new Promise<object>((resolve) => {
          changePwd(data).then((response) => {
            resolve(response)
          })
        })
      },
      // 被退出登录
      toLogout() {
        this.isLogout += 1
      },
    },
  },
)

export default useUserStore
