import { Router, Response, NextFunction } from 'express'
import { authMiddleware, AuthRequest } from '../middleware/auth'
import prisma from '../lib/prisma'

const router = Router()

// 保存（创建或更新）
router.post('/', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const { verifierName, results, remarks, conclusionName, conclusionDate, conclusionResult, conclusionIssues, screenshots, signature1, signature2 } = req.body
    if (!verifierName || !verifierName.trim()) {
      return res.status(400).json({ success: false, error: { code: 'BAD_REQUEST', message: '请输入验收人姓名' } })
    }

    const orgId = req.user!.orgId
    const data = {
      verifierName: verifierName.trim(),
      results: results || {},
      remarks: remarks || {},
      conclusionName: conclusionName || null,
      conclusionDate: conclusionDate || null,
      conclusionResult: conclusionResult || null,
      conclusionIssues: conclusionIssues || null,
      screenshots: screenshots || undefined,
      signature1: signature1 || undefined,
      signature2: signature2 || undefined,
    }

    const record = await prisma.acceptanceTest.upsert({
      where: { orgId_verifierName: { orgId, verifierName: verifierName.trim() } },
      create: { ...data, orgId, createdBy: req.user!.id },
      update: data,
    })

    res.json({ success: true, data: record })
  } catch (err) {
    next(err)
  }
})

// 获取单个验收记录
router.get('/:verifierName', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const record = await prisma.acceptanceTest.findUnique({
      where: {
        orgId_verifierName: { orgId: req.user!.orgId, verifierName: req.params.verifierName },
      },
    })
    if (!record) {
      return res.status(404).json({ success: false, error: { code: 'NOT_FOUND', message: '未找到保存记录' } })
    }
    res.json({ success: true, data: record })
  } catch (err) {
    next(err)
  }
})

// 列表（所有验收记录摘要）
router.get('/', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const records = await prisma.acceptanceTest.findMany({
      where: { orgId: req.user!.orgId },
      select: {
        id: true,
        verifierName: true,
        status: true,
        conclusionResult: true,
        conclusionDate: true,
        updatedAt: true,
        results: true,
      },
      orderBy: { updatedAt: 'desc' },
    })

    const list = records.map((r: any) => {
      const vals = Object.values(r.results as any)
      const pass = vals.filter((v: any) => v === 'pass').length
      const total = vals.length
      const tested = vals.filter((v: any) => v !== 'untested').length
      return {
        id: r.id,
        verifierName: r.verifierName,
        status: r.status,
        conclusionResult: r.conclusionResult,
        conclusionDate: r.conclusionDate,
        updatedAt: r.updatedAt,
        testedCount: tested,
        passCount: pass,
        totalCount: total,
      }
    })

    res.json({ success: true, data: list })
  } catch (err) {
    next(err)
  }
})

// 提交验收报告
router.post('/:verifierName/submit', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const { conclusionResult, conclusionIssues } = req.body
    const record = await prisma.acceptanceTest.findUnique({
      where: {
        orgId_verifierName: { orgId: req.user!.orgId, verifierName: req.params.verifierName },
      },
    })
    if (!record) {
      return res.status(404).json({ success: false, error: { code: 'NOT_FOUND', message: '请先保存再提交' } })
    }

    const updated = await prisma.acceptanceTest.update({
      where: { id: record.id },
      data: {
        status: 'SUBMITTED',
        submittedAt: new Date(),
        conclusionResult: conclusionResult || record.conclusionResult,
        conclusionIssues: conclusionIssues || record.conclusionIssues,
      },
    })

    res.json({ success: true, data: updated })
  } catch (err) {
    next(err)
  }
})

// 删除
router.delete('/:verifierName', authMiddleware, async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    await prisma.acceptanceTest.delete({
      where: {
        orgId_verifierName: { orgId: req.user!.orgId, verifierName: req.params.verifierName },
      },
    })
    res.json({ success: true })
  } catch (err) {
    next(err)
  }
})

export default router
