#!/bin/bash
# 每周一渠道订单统计周报脚本
# 执行周期：每天早上 9:00 自动运行
# 功能：统计各渠道每日订单量 → 导出Excel → 发送到指定飞书群

# 1. 初始化参数
REPORT_DATE=$(date +%Y-%m-%d)
REPORT_FILE="/tmp/openclaw/渠道每日订单统计_${REPORT_DATE}.xlsx"
CSV_FILE="/tmp/openclaw/channel_order_temp.csv"
TARGET_CHAT_ID="oc_af81515caefe26918736ad1941286224"

# 2. 加载环境变量
source /root/.openclaw/workspace/secrets.env
export PATH=$PATH:/root/.nvm/versions/node/v24.14.0/bin

# 3. 执行统计查询导出CSV
PGPASSWORD="${PG_ONLINE_PASSWORD}" psql -h bj-postgres-16pob4sg.sql.tencentcdb.com -p 28591 -U ai_member -d vala_bi -A -F "," -o "${CSV_FILE}" -c "
select 
    key_from as \"购课渠道\",
    goods_name as \"购买课包\",
    created_at as \"购课日期\",
    count(distinct trade_no) as \"总订单数\",
    count(distinct case when order_status = 3 then trade_no else NULL end) as \"未退费订单数\",
    count(distinct case when order_status = 4 then trade_no else NULL end) as \"退费订单数\"
from
(
    select id
    from bi_vala_app_account
    where status = 1
    group by id
) as a
left join 
(
    select 
        account_id,
        trade_no,
        date(created_at) as created_at,
        order_status,
        key_from,
        goods_name
    from bi_vala_order
    group by 
        account_id,
        trade_no,
        date(created_at),
        order_status,
        key_from,
        goods_name
) as b on a.id = b.account_id
where key_from is not null
group by 
    key_from,
    goods_name,
    created_at
order by 
    created_at desc,
    总订单数 desc;
"

# 4. CSV转Excel
python3 -c "import pandas as pd; pd.read_csv('${CSV_FILE}').to_excel('${REPORT_FILE}', index=False)"

# 5. 发送Excel到飞书群（curl两步：上传文件 + 发送文件消息）
APP_ID=$(jq -r '.apps[0].appId' /root/.openclaw/credentials/xiaoxi/config.json)
APP_SECRET=$(jq -r '.apps[0].appSecret' /root/.openclaw/credentials/xiaoxi/config.json)
TOKEN=$(curl -s -X POST "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal" \
  -H "Content-Type: application/json" \
  -d "{\"app_id\":\"$APP_ID\",\"app_secret\":\"$APP_SECRET\"}" \
  | jq -r '.tenant_access_token')

# 先发文本消息
curl -s -X POST "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=chat_id" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"receive_id\":\"${TARGET_CHAT_ID}\",\"msg_type\":\"text\",\"content\":\"{\\\"text\\\":\\\"📊 每周渠道订单统计周报（${REPORT_DATE}）\\\"}\"}" > /dev/null 2>&1

# 上传Excel文件
FILE_KEY=$(curl -s -X POST "https://open.feishu.cn/open-apis/im/v1/files" \
  -H "Authorization: Bearer $TOKEN" \
  -F "file_type=xls" \
  -F "file_name=渠道每日订单统计_${REPORT_DATE}.xlsx" \
  -F "file=@${REPORT_FILE}" | jq -r '.data.file_key')

if [ -z "$FILE_KEY" ] || [ "$FILE_KEY" = "null" ]; then
    echo "ERROR: 文件上传失败"
    exit 1
fi

# 发送文件消息到群
curl -s -X POST "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=chat_id" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"receive_id\":\"${TARGET_CHAT_ID}\",\"msg_type\":\"file\",\"content\":\"{\\\"file_key\\\":\\\"${FILE_KEY}\\\"}\"}" > /dev/null 2>&1

# 6. 清理临时文件
rm -f "${CSV_FILE}" "${REPORT_FILE}"
