import { ref } from 'vue'

export type AccountStatus = '启用' | '禁用'

export interface PermissionPage {
  module: string
  page: string
  actions: string[]
}

export interface RoleRecord {
  id: number
  name: string
  remark: string
  createdAt: string
  permissions: string[]
  builtIn: boolean
}

export interface AccountRecord {
  id: number
  name: string
  username: string
  phone: string
  roleId: number
  status: AccountStatus
  createdAt: string
  password: string
}

export const permissionCatalog: PermissionPage[] = [
  { module: '首页', page: '工作台', actions: ['查看'] },
  { module: '测试管理', page: '测试列表', actions: ['查看', '新增', '编辑', '删除', '下载'] },
  { module: '测试管理', page: '电池组管理', actions: ['查看', '新增', '编辑', '启用/禁用', '删除'] },
  { module: '测试管理', page: '测试类型管理', actions: ['查看', '新增', '编辑', '启用/禁用', '删除'] },
  { module: '测试管理', page: '数据修订记录', actions: ['查看', '下载'] },
  { module: '测试管理', page: '异常管理', actions: ['查看', '处理', '删除', '下载'] },
  { module: '设备管理', page: '检测柜', actions: ['查看', '新增', '编辑', '启用/禁用', '删除'] },
  { module: '设备管理', page: '采集器', actions: ['查看', '新增', '编辑', '启用/禁用', '删除'] },
  { module: '数据分析', page: '对比报表', actions: ['查看', '新增', '编辑', '删除', '下载'] },
  { module: '数据分析', page: '化成报表', actions: ['查看', '新增', '编辑', '删除', '下载'] },
  { module: '数据分析', page: '拼接报表', actions: ['查看', '新增', '编辑', '删除'] },
  { module: '代办管理', page: '待办列表', actions: ['查看', '新增', '处理', '删除'] },
  { module: '角色与权限', page: '账号管理', actions: ['查看', '新增', '编辑', '启用/禁用', '重置密码', '删除'] },
  { module: '角色与权限', page: '角色管理', actions: ['查看', '新增', '编辑', '删除'] },
]

export function permissionKey(page: string, action: string) {
  return `${page}:${action}`
}

const allPermissions = permissionCatalog.flatMap(item => item.actions.map(action => permissionKey(item.page, action)))
const operatorPermissions = permissionCatalog
  .filter(item => !['账号管理', '角色管理'].includes(item.page))
  .flatMap(item => item.actions.map(action => permissionKey(item.page, action)))
const reviewerPermissions = permissionCatalog
  .flatMap(item => item.actions.filter(action => ['查看', '下载'].includes(action)).map(action => permissionKey(item.page, action)))

const ROLE_STORAGE_KEY = 'battery_detection_roles_v1'
const ACCOUNT_STORAGE_KEY = 'battery_detection_accounts_v1'

const seedRoles: RoleRecord[] = [
  { id: 1, name: '超级管理员', remark: '拥有系统全部页面及操作权限', createdAt: '2025-06-08 03:15', permissions: [...allPermissions], builtIn: true },
  { id: 2, name: '检测室运维', remark: '负责测试、设备、异常和报表的日常操作', createdAt: '2025-06-08 03:15', permissions: [...operatorPermissions], builtIn: false },
  { id: 3, name: '数据审核员', remark: '查看测试与报表，并下载审计数据', createdAt: '2025-06-08 03:15', permissions: [...reviewerPermissions], builtIn: false },
]

const seedAccounts: AccountRecord[] = [
  { id: 1001, name: '系统管理员', username: 'Admin', phone: '13800000001', roleId: 1, status: '启用', createdAt: '2025-06-08 03:15', password: 'Admin@123456' },
  { id: 1002, name: '张工', username: 'zhang.gong', phone: '13800000002', roleId: 2, status: '启用', createdAt: '2026-08-01 09:20', password: 'Zhang@123456' },
  { id: 1003, name: '李工', username: 'li.gong', phone: '13800000003', roleId: 2, status: '启用', createdAt: '2026-08-01 09:28', password: 'Ligong@123456' },
  { id: 1004, name: '王工', username: 'wang.gong', phone: '13800000004', roleId: 3, status: '启用', createdAt: '2026-08-02 10:05', password: 'Wanggong@123' },
  { id: 1005, name: '周工', username: 'zhou.gong', phone: '13800000005', roleId: 2, status: '禁用', createdAt: '2026-08-03 14:16', password: 'Zhougong@123' },
  { id: 1006, name: '陈工', username: 'chen.gong', phone: '13800000006', roleId: 2, status: '启用', createdAt: '2026-08-04 08:42', password: 'Chengong@123' },
]

function load<T>(key: string, fallback: T) {
  try {
    const value = localStorage.getItem(key)
    if (value) return JSON.parse(value) as T
  } catch {
    localStorage.removeItem(key)
  }
  return fallback
}

const roles = ref<RoleRecord[]>(load(ROLE_STORAGE_KEY, seedRoles))
const accounts = ref<AccountRecord[]>(load(ACCOUNT_STORAGE_KEY, seedAccounts))

function persistRoles() { localStorage.setItem(ROLE_STORAGE_KEY, JSON.stringify(roles.value)) }
function persistAccounts() { localStorage.setItem(ACCOUNT_STORAGE_KEY, JSON.stringify(accounts.value)) }
function nowString() {
  const date = new Date()
  const pad = (value: number) => String(value).padStart(2, '0')
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
}

export function useAccessControl() {
  function createAccount(data: Omit<AccountRecord, 'id' | 'createdAt'>) {
    const id = Math.max(1000, ...accounts.value.map(item => item.id)) + 1
    accounts.value.unshift({ ...data, id, createdAt: nowString() })
    persistAccounts()
  }
  function updateAccount(id: number, data: Pick<AccountRecord, 'name' | 'phone' | 'roleId' | 'status'>) {
    const target = accounts.value.find(item => item.id === id)
    if (!target) return false
    Object.assign(target, data)
    persistAccounts()
    return true
  }
  function toggleAccount(id: number) {
    const target = accounts.value.find(item => item.id === id)
    if (!target) return false
    target.status = target.status === '启用' ? '禁用' : '启用'
    persistAccounts()
    return true
  }
  function resetPassword(id: number, password: string) {
    const target = accounts.value.find(item => item.id === id)
    if (!target) return false
    target.password = password
    persistAccounts()
    return true
  }
  function removeAccount(id: number) {
    accounts.value = accounts.value.filter(item => item.id !== id)
    persistAccounts()
  }
  function createRole(data: Pick<RoleRecord, 'name' | 'remark' | 'permissions'>) {
    const id = Math.max(0, ...roles.value.map(item => item.id)) + 1
    roles.value.unshift({ ...data, id, createdAt: nowString(), builtIn: false })
    persistRoles()
    return id
  }
  function updateRole(id: number, data: Pick<RoleRecord, 'name' | 'remark' | 'permissions'>) {
    const target = roles.value.find(item => item.id === id)
    if (!target) return false
    Object.assign(target, data)
    persistRoles()
    return true
  }
  function removeRole(id: number) {
    roles.value = roles.value.filter(item => item.id !== id)
    persistRoles()
  }
  return { accounts, roles, createAccount, updateAccount, toggleAccount, resetPassword, removeAccount, createRole, updateRole, removeRole }
}
