const http = require('http')

const BASE_URL = 'http://localhost:8080/api'

const TOKENS = {
  sales: 'mock-token-mp-21',
  dispatch: 'mock-token-mp-13',
  construction: 'mock-token-mp-15',
}

function formatDate(date) {
  const y = date.getFullYear()
  const m = String(date.getMonth() + 1).padStart(2, '0')
  const d = String(date.getDate()).padStart(2, '0')
  return `${y}-${m}-${d}`
}

const today = formatDate(new Date())
const tomorrowDate = new Date()
tomorrowDate.setDate(tomorrowDate.getDate() + 1)
const tomorrow = formatDate(tomorrowDate)

function request(method, path, token, data) {
  return new Promise((resolve, reject) => {
    const options = {
      hostname: 'localhost',
      port: 8080,
      path: '/api' + path,
      method,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`,
      },
    }
    const req = http.request(options, (res) => {
      let body = ''
      res.on('data', (chunk) => (body += chunk))
      res.on('end', () => {
        try {
          resolve(JSON.parse(body))
        } catch (e) {
          resolve(body)
        }
      })
    })
    req.on('error', reject)
    if (data) req.write(JSON.stringify(data))
    req.end()
  })
}

function countByStatus(tasks, statuses) {
  return tasks.filter(t => statuses.includes(t.status)).length
}

function countByDate(tasks, date) {
  return tasks.filter(t => {
    if (t.planDate === date) return true
    if (t.planDate && t.planEndDate && date >= t.planDate && date <= t.planEndDate) return true
    if (t.scheduleDate === date) return true
    if (t.serviceDate === date) return true
    return false
  }).length
}

async function main() {
  // 销售端：项目总数、待确认(auditing)、进行中(in_progress)
  const projectRes = await request('GET', '/project/list?pageNum=1&pageSize=1', TOKENS.sales)
  const salesTaskRes = await request('GET', '/task/list?pageNum=1&pageSize=100', TOKENS.sales)
  const salesTasks = salesTaskRes.data?.rows || []

  console.log('=== 销售端首页 ===')
  console.log('本月项目:', projectRes.data?.total || 0)
  console.log('待确认 (status=auditing):', countByStatus(salesTasks, ['auditing']))
  console.log('进行中 (status=in_progress):', countByStatus(salesTasks, ['in_progress']))
  console.log('任务状态分布:', salesTasks.reduce((acc, t) => {
    acc[t.status] = (acc[t.status] || 0) + 1
    return acc
  }, {}))

  // 调度端：今日任务、待审核(auditing)、待安排(approved)
  const dispatchMyRes = await request('GET', `/task/my?planDate=${today}`, TOKENS.dispatch)
  const dispatchTasks = dispatchMyRes.data || dispatchMyRes || []

  console.log('\n=== 调度端首页 ===')
  console.log('今日任务 (planDate/scheduleDate/serviceDate = today):', countByDate(dispatchTasks, today), '/', dispatchTasks.length)
  console.log('待审核 (status=auditing):', countByStatus(dispatchTasks, ['auditing']))
  console.log('待安排 (status=approved):', countByStatus(dispatchTasks, ['approved']))
  console.log('任务状态分布:', dispatchTasks.reduce((acc, t) => {
    acc[t.status] = (acc[t.status] || 0) + 1
    return acc
  }, {}))

  // 施工端：已完成(completed)、进行中(in_progress)、待确认(assigned)
  const constructionMyRes = await request('GET', '/task/my', TOKENS.construction)
  const constructionTasks = constructionMyRes.data || constructionMyRes || []

  console.log('\n=== 施工端首页 ===')
  console.log('已完成 (status=completed):', countByStatus(constructionTasks, ['completed']))
  console.log('进行中 (status=in_progress):', countByStatus(constructionTasks, ['in_progress']))
  console.log('待确认 (status=assigned):', countByStatus(constructionTasks, ['assigned']))
  console.log('任务状态分布:', constructionTasks.reduce((acc, t) => {
    acc[t.status] = (acc[t.status] || 0) + 1
    return acc
  }, {}))
}

main().catch(err => {
  console.error('验证失败:', err)
  process.exit(1)
})
