-- 补充回填：v_store_monthly_followup 中值为 NULL 的门店
-- 从 v_store_action_priority_deep_april 和 v_store_risk_rating 补充
UPDATE analytics.store_task t
SET
  current_value = src.current_val::numeric,
  benchmark_value = src.benchmark_val::numeric,
  target_value = src.target_val::numeric
FROM (
  SELECT
    t.task_id,
    CASE t.problem_indicator
      WHEN '异常率' THEN COALESCE(f.actual_anomaly_rate, r.anomaly_rate_pct)::text
      WHEN '优惠率' THEN COALESCE(f.actual_discount_rate, v.discount_rate_pct)::text
      WHEN '理论毛利率' THEN COALESCE(f.actual_margin_rate, v.theoretical_margin_pct)::text
      WHEN '会员复购率' THEN COALESCE(f.actual_repeat_rate, v.repeat_rate_pct)::text
      WHEN '实际成本率' THEN v.actual_food_cost_rate_pct::text
      WHEN '饮品搭售率' THEN v.noodle_drink_attach_pct::text
      ELSE NULL
    END AS current_val,
    CASE t.problem_indicator
      WHEN '异常率' THEN COALESCE(f.baseline_anomaly_rate, d.yellow_threshold)::text
      WHEN '优惠率' THEN COALESCE(f.baseline_discount_rate, d.yellow_threshold)::text
      WHEN '理论毛利率' THEN COALESCE(f.baseline_margin_rate, d.yellow_threshold)::text
      WHEN '会员复购率' THEN COALESCE(f.baseline_repeat_rate, d.yellow_threshold)::text
      WHEN '实际成本率' THEN v.theoretical_cost_rate_pct::text
      WHEN '饮品搭售率' THEN '15'
      ELSE d.yellow_threshold::text
    END AS benchmark_val,
    CASE t.problem_indicator
      WHEN '异常率' THEN COALESCE(f.target_anomaly_rate, d.red_threshold)::text
      WHEN '优惠率' THEN COALESCE(f.target_discount_rate, d.red_threshold)::text
      WHEN '理论毛利率' THEN COALESCE(f.target_margin_rate, d.red_threshold)::text
      WHEN '会员复购率' THEN COALESCE(f.target_repeat_rate, d.red_threshold)::text
      WHEN '实际成本率' THEN d.red_threshold::text
      WHEN '饮品搭售率' THEN '20'
      ELSE d.red_threshold::text
    END AS target_val
  FROM analytics.store_task t
  LEFT JOIN analytics.v_store_monthly_followup f ON f.store_code = t.store_code
  LEFT JOIN analytics.v_store_action_priority_deep_april v ON v.store_code = t.store_code
  LEFT JOIN analytics.v_store_risk_rating r ON r.store_code = t.store_code
  LEFT JOIN analytics.indicator_dictionary d ON d.indicator_name = t.problem_indicator
  WHERE t.current_value IS NULL
    AND t.problem_indicator IN ('异常率','优惠率','理论毛利率','会员复购率','实际成本率','饮品搭售率')
) src
WHERE t.task_id = src.task_id
  AND src.current_val IS NOT NULL;
