import { Router } from 'express'
import { query, withTransaction } from '../config/database.js'
import { sendSuccess, sendError } from '../middleware/error.js'
import type { AuthRequest } from '../middleware/auth.js'

const router = Router()

// T-160: 门店自动分级算法
router.post('/auto-grade', async (req: AuthRequest, res) => {
  try {
    const gradeMonth = (req.query.month as string) || new Date().toISOString().slice(0, 8) + '01'

    const storesResult = await query(`
      SELECT
        ds.store_code, ds.store_name, ds.region,
        COALESCE(s.received, 0) AS revenue,
        COALESCE(t.revenue_target, 0) AS revenue_target,
        COALESCE(s.theoretical_margin_pct, 0) AS margin_pct,
        COALESCE(s.member_bill_share_pct, 0) AS member_pct,
        COALESCE(s.risk_level, '绿色') AS risk_level
      FROM analytics.dim_store ds
      LEFT JOIN analytics.mv_store_risk_rating s
        ON s.store_code = ds.store_code
      LEFT JOIN analytics.v3_store_monthly_target t
        ON t.store_code = ds.store_code AND date_trunc('month', t.month) = date_trunc('month', $1::date)
      WHERE ds.close_date IS NULL
      ORDER BY ds.store_code
    `, [gradeMonth])

    await withTransaction(async (client) => {
      for (const store of storesResult.rows) {
        const achievement = Number(store.revenue_target) > 0
          ? (Number(store.revenue) / Number(store.revenue_target) * 100)
          : 0

        const marginScore = Math.min(Number(store.margin_pct) / 50 * 100, 100)
        const achievementScore = Math.min(achievement, 100)
        const memberScore = Math.min(Number(store.member_pct) / 50 * 100, 100)
        const riskScore = store.risk_level === '红色' ? 30 : store.risk_level === '黄色' ? 60 : 100

        const overallScore = (achievementScore * 0.4 + marginScore * 0.25 + memberScore * 0.15 + riskScore * 0.2)

        let grade = 'B'
        if (overallScore >= 85) grade = 'A'
        else if (overallScore >= 70) grade = 'B'
        else if (overallScore >= 50) grade = 'C'
        else grade = 'D'

        await client.query(`
          INSERT INTO analytics.v3_store_grade (grade_month, store_code, store_name, region, grade, revenue_achievement_pct, overall_score, reason)
          VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
          ON CONFLICT (grade_month, store_code) DO UPDATE SET
            grade = EXCLUDED.grade,
            revenue_achievement_pct = EXCLUDED.revenue_achievement_pct,
            overall_score = EXCLUDED.overall_score,
            reason = EXCLUDED.reason
        `, [gradeMonth, store.store_code, store.store_name, store.region, grade,
             achievement.toFixed(2), overallScore.toFixed(2),
             `达成率${achievement.toFixed(1)}% 综合分${overallScore.toFixed(1)}`])
      }
    })

    const gradeResult = await query(`
      SELECT grade, count(*) AS cnt FROM analytics.v3_store_grade WHERE grade_month = $1 GROUP BY grade ORDER BY grade
    `, [gradeMonth])

    sendSuccess(res, { month: gradeMonth, distribution: gradeResult.rows, total: storesResult.rows.length })
  } catch (err: any) {
    sendError(res, err.message)
  }
})

// 获取门店分级列表（含风险等级详情）
router.get('/grades', async (req: AuthRequest, res) => {
  try {
    const gradeMonth = (req.query.month as string) || new Date().toISOString().slice(0, 8) + '01'
    const result = await query(`
      SELECT
        g.*,
        COALESCE(s.risk_level, '绿色') AS risk_level,
        COALESCE(s.primary_issue, '') AS primary_issue,
        COALESCE(s.received, 0) AS revenue,
        COALESCE(s.bill_count, 0) AS bill_count,
        COALESCE(s.theoretical_margin_pct, 0) AS margin_pct,
        COALESCE(s.anomaly_rate_pct, 0) AS anomaly_rate,
        COALESCE(s.discount_rate_pct, 0) AS discount_rate,
        COALESCE(s.member_bill_share_pct, 0) AS member_pct,
        COALESCE(s.avg_bill_value, 0) AS avg_bill_value,
        COALESCE(s.avg_guest_value, 0) AS avg_guest_value,
        COALESCE(s.active_days, 0) AS active_days
      FROM analytics.v3_store_grade g
      LEFT JOIN analytics.mv_store_risk_rating s
        ON s.store_code = g.store_code
      WHERE date_trunc('month', g.grade_month) = date_trunc('month', $1::date)
      ORDER BY g.overall_score DESC
    `, [gradeMonth])
    sendSuccess(res, result.rows)
  } catch (err: any) {
    sendError(res, err.message)
  }
})

// 红黄绿灯状态 — 基于实时经营健康度（达成率+异常率+风险等级），与分级维度不同
router.get('/traffic-light', async (req: AuthRequest, res) => {
  try {
    const month = (req.query.month as string) || new Date().toISOString().slice(0, 8) + '01'
    const result = await query(`
      SELECT * FROM (
        SELECT
          g.store_code, g.store_name, g.region, g.grade, g.overall_score,
          g.revenue_achievement_pct,
          COALESCE(s.received, 0) AS revenue,
          COALESCE(s.bill_count, 0) AS bill_count,
          COALESCE(s.theoretical_margin_pct, 0) AS margin_pct,
          COALESCE(s.anomaly_rate_pct, 0) AS anomaly_rate,
          COALESCE(s.risk_level, '绿色') AS risk_level,
          COALESCE(s.primary_issue, '') AS primary_issue,
          CASE
            WHEN COALESCE(s.anomaly_rate_pct, 0) >= 10 THEN 'red'
            WHEN COALESCE(s.anomaly_rate_pct, 0) >= 5 THEN 'yellow'
            WHEN g.revenue_achievement_pct IS NOT NULL AND CAST(g.revenue_achievement_pct AS numeric) < 70 THEN 'yellow'
            ELSE 'green'
          END AS light_status,
          CASE
            WHEN COALESCE(s.anomaly_rate_pct, 0) >= 10 THEN '异常率≥10%'
            WHEN COALESCE(s.anomaly_rate_pct, 0) >= 5 THEN '异常率≥5%'
            WHEN g.revenue_achievement_pct IS NOT NULL AND CAST(g.revenue_achievement_pct AS numeric) < 70 THEN '达成率<70%'
            ELSE '各项指标正常'
          END AS light_reason
        FROM analytics.v3_store_grade g
        LEFT JOIN analytics.mv_store_risk_rating s
          ON s.store_code = g.store_code
        WHERE date_trunc('month', g.grade_month) = date_trunc('month', $1::date)
      ) t
      ORDER BY
        CASE light_status WHEN 'red' THEN 0 WHEN 'yellow' THEN 1 ELSE 2 END,
        anomaly_rate DESC, overall_score ASC
    `, [month])
    sendSuccess(res, result.rows)
  } catch (err: any) {
    sendError(res, err.message)
  }
})

export default router
