#!/bin/bash
# L2 每个课时首次通关耗时统计 - 优化版
export PGPASSWORD='LdfjdjL83h3h3^$&**YGG*'
PSQL="psql -h bj-postgres-16pob4sg.sql.tencentcdb.com -p 28591 -U ai_member -d vala_bi -t -A"

echo "chapter_id|season|unit|lesson|完成人数|平均用时_分钟"

# 获取章节列表
while IFS='|' read -r cid season unit lesson; do
  # 查首次完成记录，来自8张分表 （不查 component 耗时那步太慢，直接用 chapter 表做简单计数）
  # 先只统计完成人数
  count=$($PSQL -c "
  SELECT COUNT(*)
  FROM (
    SELECT user_id FROM bi_user_chapter_play_record_0 WHERE play_status=1 AND chapter_id=$cid
    UNION ALL SELECT user_id FROM bi_user_chapter_play_record_1 WHERE play_status=1 AND chapter_id=$cid
    UNION ALL SELECT user_id FROM bi_user_chapter_play_record_2 WHERE play_status=1 AND chapter_id=$cid
    UNION ALL SELECT user_id FROM bi_user_chapter_play_record_3 WHERE play_status=1 AND chapter_id=$cid
    UNION ALL SELECT user_id FROM bi_user_chapter_play_record_4 WHERE play_status=1 AND chapter_id=$cid
    UNION ALL SELECT user_id FROM bi_user_chapter_play_record_5 WHERE play_status=1 AND chapter_id=$cid
    UNION ALL SELECT user_id FROM bi_user_chapter_play_record_6 WHERE play_status=1 AND chapter_id=$cid
    UNION ALL SELECT user_id FROM bi_user_chapter_play_record_7 WHERE play_status=1 AND chapter_id=$cid
  ) t;
  " 2>/dev/null || echo "0")
  
  echo "$cid|$season|$unit|$lesson|${count:-0}|NA"
done < <($PSQL -c "SELECT id, course_season, course_unit, course_lesson FROM bi_level_unit_lesson WHERE course_level='L2' ORDER BY id;")
