import { defineStore } from 'pinia'
import type { AdminRole } from '../auth/roles'
import { userService } from '../services/user'
import userManageService from '../services/userManage'
import { isRealMode } from '../auth/authMode'

export type UserAccount = {
  id: string
  name: string
  email: string
  role: AdminRole
  status: '正常' | '冻结'
  managerName: string
}

export type InviteRequest = {
  id: string
  email: string
  role: AdminRole
  status: '待接受' | '已接受' | '已拒绝' | '已过期'
  invitedAt: string
  acceptedAt?: string
  expiredAt?: string
}

export type RoleChangeRequest = {
  id: string
  bizType?: string
  userId: string
  title?: string
  description?: string
  currentValue?: string
  targetValue?: string
  currentRole?: AdminRole
  targetRole?: AdminRole
  reason: string
  status: '待审批' | '已通过' | '已拒绝'
  requestedAt: string
  approvedBy?: string
  decisionAt?: string
  rejectReason?: string
}

const nowIso = () => new Date().toISOString()

export const useUserStore = defineStore('users', {
  state: () => ({
    users: [] as UserAccount[],
    invites: [] as InviteRequest[],
    roleRequests: [] as RoleChangeRequest[]
  }),
  getters: {
    byId: (state) => (id: string) => state.users.find((u) => u.id === id) ?? null,
    pendingRoleRequests: (state) => state.roleRequests.filter((req) => req.status === '待审批')
  },
  actions: {
    init(users: UserAccount[], invites: InviteRequest[], requests: RoleChangeRequest[]) {
      if (this.users.length) return
      this.users = users
      this.invites = invites
      this.roleRequests = requests
    },
    async toggleUserStatus(id: string) {
      const user = this.byId(id)
      if (!user) return
      try {
        if (user.status === '冻结') {
          await userService.unfreezeUser(Number(id))
          user.status = '正常'
        } else {
          await userService.freezeUser(Number(id))
          user.status = '冻结'
        }
      } catch (error) {
        console.error('用户状态变更失败:', error)
        throw error
      }
    },
    addInvite(email: string, role: AdminRole) {
      const invite: InviteRequest = {
        id: `invite-${Date.now()}`,
        email,
        role,
        status: '待接受',
        invitedAt: nowIso()
      }
      this.invites.unshift(invite)
      return invite
    },
    acceptInvite(id: string) {
      const invite = this.invites.find((item) => item.id === id)
      if (!invite || invite.status !== '待接受') return
      invite.status = '已接受'
      invite.acceptedAt = nowIso()
    },
    resendInvite(id: string) {
      const invite = this.invites.find((item) => item.id === id)
      if (!invite) return
      invite.status = '待接受'
      invite.invitedAt = nowIso()
      invite.expiredAt = undefined
    },
    expireInvite(id: string) {
      const invite = this.invites.find((item) => item.id === id)
      if (!invite || invite.status === '已过期') return
      invite.status = '已过期'
      invite.expiredAt = nowIso()
    },
    async requestRoleChange(userId: string, targetRole: AdminRole, reason: string) {
      const user = this.byId(userId)
      if (!user) return null

      // 真实模式：调用后端API发起审批
      if (isRealMode()) {
        try {
          // 将角色代码转换为角色ID
          const roleId = this.getRoleIdByCode(targetRole)
          if (roleId) {
            await userManageService.assignRoles(Number(userId), [roleId], reason)
          } else {
            console.warn('未找到角色ID:', targetRole)
          }
        } catch (error) {
          console.error('调用后端API失败:', error)
          throw error
        }
      }

      // Demo模式或API调用成功后添加到本地store
      const request: RoleChangeRequest = {
        id: `role-${Date.now()}`,
        userId,
        currentRole: user.role as AdminRole,
        targetRole,
        reason,
        status: '待审批',
        requestedAt: nowIso()
      }
      this.roleRequests.unshift(request)
      return request
    },

    // 根据角色代码获取角色ID
    getRoleIdByCode(roleCode: AdminRole): number | null {
      const roleMap: Record<string, number> = {
        super_admin: 1,
        system_admin: 2,
        ops_director: 3,
        ops_manager: 4,
        marketing_director: 5,
        marketing_manager: 6,
        finance_manager: 7,
        risk_manager: 8,
        customer_service_supervisor: 9,
        ops_specialist: 10,
        marketing_specialist: 11,
        finance_specialist: 12,
        risk_specialist: 13,
        customer_service_specialist: 14,
        auditor: 15
      }
      return roleMap[roleCode] || null
    },
    approveRoleChange(id: string, approver: string) {
      const request = this.roleRequests.find((item) => item.id === id)
      if (!request || request.status !== '待审批') return
      request.status = '已通过'
      request.approvedBy = approver
      request.decisionAt = nowIso()
      const user = this.byId(request.userId)
      if (user && request.targetRole) {
        user.role = request.targetRole as AdminRole
      }
    },
    rejectRoleChange(id: string, approver: string, rejectReason: string) {
      const request = this.roleRequests.find((item) => item.id === id)
      if (!request || request.status !== '待审批') return
      request.status = '已拒绝'
      request.approvedBy = approver
      request.decisionAt = nowIso()
      request.rejectReason = rejectReason
    },
    // 设置角色变更请求列表（用于真实模式刷新数据）
    setRoleRequests(requests: RoleChangeRequest[]) {
      this.roleRequests = requests
    },
    // 设置邀请列表（用于真实模式刷新数据）
    setInvites(invites: InviteRequest[]) {
      this.invites = invites
    },
    // P0修复：添加fetchUsers方法用于刷新用户数据
    async fetchUsers() {
      try {
        const response = await userManageService.getUsers()
        if (response && Array.isArray(response)) {
          this.users = response.map((u: any) => ({
            id: String(u.id),
            name: u.name || '',
            email: u.email || '',
            role: u.roleCode || 'ops_specialist',
            status: u.status === 1 ? '正常' : '冻结',
            managerName: u.managerName || ''
          }))
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
      }
    }
  }
})
