/**
 * 给全部员工对应上正确的社保和公积金账户
 * 逻辑：按员工所在城市的账户匹配，回退到默认账户
 */
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()

async function main() {
  // 1. 查所有账户（按城市分组）
  const accounts = await prisma.socialAccount.findMany({
    select: { id: true, name: true, type: true, city: true, isDefault: true },
  })
  console.log('=== 全部账户 ===')
  for (const a of accounts) {
    console.log(`${a.type} | ${a.name} | ${a.city} | default=${a.isDefault} | ${a.id}`)
  }

  // 按城市+类型建索引
  const socialByCity: Record<string, string> = {}
  const housingByCity: Record<string, string> = {}
  let defaultSocial: string | null = null
  let defaultHousing: string | null = null

  for (const a of accounts) {
    if (a.type === 'SOCIAL') {
      if (a.isDefault) defaultSocial = a.id
      if (a.city) socialByCity[a.city] = a.id
    } else {
      if (a.isDefault) defaultHousing = a.id
      if (a.city) housingByCity[a.city] = a.id
    }
  }

  // 2. 查所有部门
  const depts = await prisma.department.findMany({
    select: { id: true, name: true, level: true, parentId: true, socialAccountId: true, housingAccountId: true },
  })
  console.log('\n=== 部门账户关联（修改前）===')
  for (const d of depts) {
    console.log(`${d.name} | level=${d.level} | social=${d.socialAccountId || '无'} | housing=${d.housingAccountId || '无'}`)
  }

  // 3. 查所有员工及其部门和城市
  const employees = await prisma.employee.findMany({
    select: { id: true, name: true, department: true, departmentId: true, city: true, dept: true },
  })
  console.log(`\n=== 员工总数: ${employees.length} ===`)

  // 4. 为每个员工找到根部门，检查是否有账户
  // 如果根部门没有账户，按员工城市匹配账户，更新根部门
  const rootDeptMap = new Map<string, { name: string; city: string; empCount: number }>()

  for (const emp of employees) {
    // 向上找根部门
    let dept: any = emp.dept
    if (!dept && emp.departmentId) {
      dept = await prisma.department.findUnique({ where: { id: emp.departmentId } })
    }
    while (dept && dept.level > 0 && dept.parentId) {
      dept = await prisma.department.findUnique({ where: { id: dept.parentId } })
    }
    if (dept) {
      const existing = rootDeptMap.get(dept.id)
      if (existing) {
        existing.empCount++
      } else {
        rootDeptMap.set(dept.id, { name: dept.name, city: emp.city || '', empCount: 1 })
      }
    }
  }

  console.log('\n=== 根部门及员工城市 ===')
  for (const [deptId, info] of rootDeptMap) {
    const dept = await prisma.department.findUnique({ where: { id: deptId }, select: { socialAccountId: true, housingAccountId: true } })
    console.log(`${info.name} | 员工数=${info.empCount} | 员工城市=${info.city || '无'} | social=${dept?.socialAccountId || '无'} | housing=${dept?.housingAccountId || '无'}`)
  }

  // 5. 为没有账户的根部门按员工城市匹配账户
  let updated = 0
  for (const [deptId, info] of rootDeptMap) {
    const dept = await prisma.department.findUnique({ where: { id: deptId }, select: { socialAccountId: true, housingAccountId: true, name: true } })

    let socialId = dept?.socialAccountId || null
    let housingId = dept?.housingAccountId || null

    // 社保账户
    if (!socialId) {
      if (info.city && socialByCity[info.city]) {
        socialId = socialByCity[info.city]
      } else if (defaultSocial) {
        socialId = defaultSocial
      }
    }

    // 公积金账户
    if (!housingId) {
      if (info.city && housingByCity[info.city]) {
        housingId = housingByCity[info.city]
      } else if (defaultHousing) {
        housingId = defaultHousing
      }
    }

    if ((socialId && !dept?.socialAccountId) || (housingId && !dept?.housingAccountId)) {
      await prisma.department.update({
        where: { id: deptId },
        data: {
          ...(socialId && !dept?.socialAccountId ? { socialAccountId: socialId } : {}),
          ...(housingId && !dept?.housingAccountId ? { housingAccountId: housingId } : {}),
        },
      })
      console.log(`[更新] 根部门 ${dept?.name} → social=${socialId || '无'} housing=${housingId || '无'}`)
      updated++
    }
  }

  console.log(`\n更新了 ${updated} 个根部门的账户关联`)

  // 6. 验证：重新查每个员工是否有账户
  let noSocial = 0
  let noHousing = 0
  let hasBoth = 0
  for (const emp of employees) {
    let dept: any = emp.dept
    if (!dept && emp.departmentId) {
      dept = await prisma.department.findUnique({ where: { id: emp.departmentId } })
    }
    while (dept && dept.level > 0 && dept.parentId) {
      dept = await prisma.department.findUnique({ where: { id: dept.parentId } })
    }

    let socialId = dept?.socialAccountId || null
    let housingId = dept?.housingAccountId || null

    // 回退到默认
    if (!socialId) socialId = defaultSocial
    if (!housingId) housingId = defaultHousing

    if (socialId && housingId) {
      hasBoth++
    } else {
      if (!socialId) noSocial++
      if (!housingId) noHousing++
      console.log(`[缺失] ${emp.name} | social=${socialId ? '有' : '无'} housing=${housingId ? '有' : '无'} | city=${emp.city || '无'} | dept=${dept?.name || '无'}`)
    }
  }

  console.log(`\n=== 验证结果 ===`)
  console.log(`有社保+公积金: ${hasBoth}`)
  console.log(`缺社保: ${noSocial}`)
  console.log(`缺公积金: ${noHousing}`)
}

main().then(() => process.exit(0)).catch(e => { console.error(e); process.exit(1) })
