import router from '@/router'
import { ElMessageBox } from 'element-plus'
import { login, logout, getInfo } from '@/api/login'
import { getUserInfo } from '@/api/common'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { isHttp, isEmpty } from '@/utils/validate'
import defAva from '@/assets/images/profile.jpg'
import usePermissionStore from '@/store/modules/permission'

const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    id: '',
    name: '',
    nickName: '',
    avatar: '',
    isSuperAdmin: 0,
    roles: [],
    permissions: [],
    tenants: [], // 新增租户列表
    currentTenant: null, // 新增当前租户
    projectInfo: null, //保存从中台跳转过来的项目信息
    userDetail: null //保存从中台跳转过来的用户信息
  }),
  actions: {
    // 登录
    login(userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid)
          .then(res => {
            setToken(res.data.token)
            this.token = res.data.token
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfo()
          .then(res => {
            const user = res.data.apiLoginUserInfoResponse
            let avatar = user.avatar || ''
            if (!isHttp(avatar)) {
              avatar = isEmpty(avatar) ? defAva : import.meta.env.VITE_APP_BASE_API + avatar
            }

            // 设置租户列表
            this.tenants = res.data.apiLoginTenantResponseList || []

            // 尝试从本地存储获取当前租户，否则使用第一个
            const savedTenant = JSON.parse(localStorage.getItem('' + ''))
            const currentTenant = savedTenant || (this.tenants.length > 0 ? this.tenants[0] : null)

            if (currentTenant) {
              this.currentTenant = currentTenant
              localStorage.setItem('currentTenant', JSON.stringify(currentTenant))
            }

            // 设置角色和权限
            if (currentTenant.roles && currentTenant.roles.length > 0) {
              this.roles = currentTenant.roles
              this.permissions = currentTenant.permissions
            } else {
              this.roles = ['ROLE_DEFAULT']
            }

            this.id = user.userId
            this.name = user.userName
            this.nickName = user.nickName
            this.avatar = avatar
            this.isSuperAdmin = user.isSuperAdmin
            this.userDetail = user //新增的中台用户信息
            /* 初始密码提示 */
            if (res.data.isDefaultModifyPwd) {
              ElMessageBox.confirm('您的密码还是初始密码，请修改密码！', '安全提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              })
                .then(() => {
                  router.push({ name: 'Profile', params: { activeTab: 'resetPwd' } })
                })
                .catch(() => {})
            }
            /* 过期密码提示 */
            if (!res.data.isDefaultModifyPwd && res.isPasswordExpired) {
              ElMessageBox.confirm('您的密码已过期，请尽快修改密码！', '安全提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              })
                .then(() => {
                  router.push({ name: 'Profile', params: { activeTab: 'resetPwd' } })
                })
                .catch(() => {})
            }
            resolve(res)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    //切换租户
    switchTenant(tenant) {
      return new Promise(resolve => {
        this.currentTenant = tenant
        localStorage.setItem('currentTenant', JSON.stringify(tenant))

        // 保存租户ID到专用字段
        localStorage.setItem('selectedTenantId', tenant.apiLoginTenantInfoResponse.tenantBizId)

        // 更新角色和权限
        if (tenant.roles && tenant.roles.length > 0) {
          this.roles = tenant.roles
          this.permissions = tenant.permissions
        } else {
          this.roles = ['ROLE_DEFAULT']
        }

        usePermissionStore()
          .generateRoutes()
          .then(accessRoutes => {
            // 移除旧路由
            const currentRoutes = router.getRoutes()
            currentRoutes.forEach(route => {
              if (route.name && !constantRoutes.some(r => r.name === route.name)) {
                router.removeRoute(route.name)
              }
            })

            // 添加新路由
            accessRoutes.forEach(route => {
              if (!isHttp(route.path)) {
                router.addRoute(route)
              }
            })

            // 刷新工作台页面
            // router.push('/workbench').then(() => {
            //   window.location.reload() // 确保完全刷新
            // })
          })
        router.push('/workbench')
      })
    },
    // 退出系统
    logOut() {
      return new Promise((resolve, reject) => {
        this.token = ''
        this.roles = []
        this.permissions = []
        this.tenants = []
        this.currentTenant = null
        removeToken()
        localStorage.removeItem('currentTenant')
        resolve()
        // logout(this.token).then(() => {
        //   this.token = ''
        //   this.roles = []
        //   this.permissions = []
        //   this.tenants = []
        //   this.currentTenant = null
        //   removeToken()
        //   localStorage.removeItem('currentTenant')
        //   resolve()
        // }).catch(error => {
        //   reject(error)
        // })
      })
    },
    clearRoles() {
      this.roles = []
    },
    setProjectInfo(project) {
      this.projectInfo = project
    }
  }
})

export default useUserStore
