-- 模拟闭环流程：
-- 1. 将部分任务推进到"进行中"（模拟店长已提交执行反馈）
-- 2. 对部分"进行中"任务执行月度验收
-- 3. 生成 task_monthly_review 数据

-- Step 1: 将前60条任务推进到"进行中"（模拟执行反馈）
UPDATE analytics.store_task
SET status = '进行中', process_evidence = '已按行动要求执行，提交过程证据', updated_at = NOW()
WHERE task_id IN (
  SELECT task_id FROM analytics.store_task WHERE status = '待启动' ORDER BY task_id LIMIT 60
);

-- 记录执行日志
INSERT INTO analytics.store_task_log (task_id, action, new_status, operator, comment)
SELECT task_id, '执行反馈', '进行中', '店长', '已按行动要求执行'
FROM analytics.store_task WHERE status = '进行中';

-- Step 2: 对"进行中"的任务执行月度验收
-- 达标：current_value 已优于 target_value
INSERT INTO analytics.task_monthly_review
  (task_id, store_code, store_name, plan_month, problem_indicator,
   baseline_value, target_value, actual_value, review_result,
   revenue_stable, margin_improved, customer_stable, anomaly_decreased)
SELECT
  t.task_id, t.store_code, t.store_name, t.plan_month, t.problem_indicator,
  t.benchmark_value, t.target_value,
  t.current_value,
  CASE
    WHEN t.current_value IS NOT NULL AND t.target_value IS NOT NULL AND t.current_value <= t.target_value THEN '达标'
    WHEN t.current_value IS NOT NULL AND t.benchmark_value IS NOT NULL AND t.current_value < t.benchmark_value THEN '改善中'
    ELSE '未改善'
  END,
  true,
  CASE
    WHEN t.current_value IS NOT NULL AND t.target_value IS NOT NULL AND t.current_value <= t.target_value THEN true
    ELSE false
  END,
  true,
  CASE
    WHEN t.current_value IS NOT NULL AND t.benchmark_value IS NOT NULL AND t.current_value < t.benchmark_value THEN true
    ELSE false
  END
FROM analytics.store_task t
WHERE t.status = '进行中';

-- Step 3: 更新任务状态为"已验收"
UPDATE analytics.store_task t
SET status = '已验收',
    verification_result = r.review_result,
    updated_at = NOW()
FROM analytics.task_monthly_review r
WHERE t.task_id = r.task_id;

-- 记录验收日志
INSERT INTO analytics.store_task_log (task_id, action, new_status, operator, comment)
SELECT task_id, '月度验收', '已验收', '区域经理', review_result
FROM analytics.task_monthly_review;

-- Step 4: 创建1条标准化经验（达标门店）
INSERT INTO analytics.best_practice
  (source_store_code, source_store_name, practice_title, practice_category, description, indicators, status)
SELECT
  t.store_code, t.store_name,
  t.problem_indicator || '改善经验',
  CASE t.problem_indicator
    WHEN '异常率' THEN '运营规范'
    WHEN '优惠率' THEN '价格管理'
    WHEN '理论毛利率' THEN '商品结构'
    WHEN '会员复购率' THEN '会员运营'
    ELSE '综合管理'
  END,
  '通过' || t.action_required || '实现' || t.problem_indicator || '从' || t.benchmark_value || '改善至' || t.current_value,
  t.problem_indicator,
  '待推广'
FROM analytics.task_monthly_review r
JOIN analytics.store_task t ON t.task_id = r.task_id
WHERE r.review_result = '达标'
LIMIT 3;
