-- 回填 store_task 的 current_value / benchmark_value / target_value
-- 标准7指标从 v_store_monthly_followup 取值
-- 实际成本率/饮品搭售率从 v_store_action_priority_deep_april 取值
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 f.actual_anomaly_rate::text
      WHEN '优惠率' THEN f.actual_discount_rate::text
      WHEN '理论毛利率' THEN f.actual_margin_rate::text
      WHEN '会员复购率' THEN f.actual_repeat_rate::text
      WHEN '平台加权成本率' THEN NULL
      WHEN '客单价' THEN f.actual_avg_bill::text
      WHEN '实收' THEN f.actual_received::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 f.baseline_anomaly_rate::text
      WHEN '优惠率' THEN f.baseline_discount_rate::text
      WHEN '理论毛利率' THEN f.baseline_margin_rate::text
      WHEN '会员复购率' THEN f.baseline_repeat_rate::text
      WHEN '平台加权成本率' THEN f.baseline_meituan_cost_rate::text
      WHEN '客单价' THEN f.baseline_avg_bill::text
      WHEN '实收' THEN f.baseline_received::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 f.target_anomaly_rate::text
      WHEN '优惠率' THEN f.target_discount_rate::text
      WHEN '理论毛利率' THEN f.target_margin_rate::text
      WHEN '会员复购率' THEN f.target_repeat_rate::text
      WHEN '平台加权成本率' THEN f.target_meituan_cost_rate::text
      WHEN '客单价' THEN f.target_avg_bill::text
      WHEN '实收' THEN f.target_received::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.indicator_dictionary d ON d.indicator_name = t.problem_indicator
  WHERE t.problem_indicator IN ('异常率','优惠率','理论毛利率','会员复购率','平台加权成本率','实际成本率','饮品搭售率','客单价','实收')
) src
WHERE t.task_id = src.task_id;
