#!/bin/bash
# Flower Database Access - 示例脚本
# 这个脚本演示了如何使用数据库访问skill

set -e

# 数据库连接参数
export DB_HOST="127.0.0.1"
export DB_PORT="5432"
export DB_NAME="flower"
export DB_USER="postgres"
export DB_PASS="postgres"

echo "=== Flower ERP 数据库访问示例 ==="
echo

# 示例1: 查询商户信息
echo "1. 查询商户列表:"
echo "---"
PGPASSWORD=$DB_PASS psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -c "
SELECT id, name, type, created_at 
FROM basic_info_merchant 
ORDER BY created_at DESC 
LIMIT 5;
"
echo

# 示例2: 查询最近的销售订单
echo "2. 查询最近10条销售订单:"
echo "---"
PGPASSWORD=$DB_PASS psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -c "
SELECT 
    so.id,
    so.sales_date,
    c.name as customer_name,
    so.status,
    so.created_at
FROM business_salesorder so
JOIN basic_info_customer c ON so.customer_id = c.id
ORDER BY so.created_at DESC
LIMIT 10;
"
echo

# 示例3: 查询库存
echo "3. 查询库存状态（前10个）:"
echo "---"
PGPASSWORD=$DB_PASS psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -c "
SELECT 
    p.name as product_name,
    w.name as warehouse,
    si.quantity,
    p.unit
FROM stock_inventory si
JOIN basic_info_product p ON si.product_id = p.id
JOIN basic_info_warehouse w ON si.warehouse_id = w.id
WHERE si.quantity > 0
ORDER BY si.quantity DESC
LIMIT 10;
"
echo

# 示例4: 查询印染订单统计
echo "4. 印染订单统计（最近7天）:"
echo "---"
PGPASSWORD=$DB_PASS psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -c "
SELECT 
    DATE(created_at) as date,
    COUNT(*) as total_orders,
    SUM(CASE WHEN is_urgent THEN 1 ELSE 0 END) as urgent_orders,
    SUM(CASE WHEN is_fabric_received THEN 1 ELSE 0 END) as fabric_received
FROM printing_printingorder
WHERE created_at >= CURRENT_DATE - INTERVAL '7 days'
GROUP BY DATE(created_at)
ORDER BY date DESC;
"
echo

# 示例5: 查询开版订单进度
echo "5. 开版订单进度统计:"
echo "---"
PGPASSWORD=$DB_PASS psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -c "
SELECT 
    po.id,
    po.style_name,
    po.plate_type,
    po.urgency_level,
    po.is_ordered,
    po.created_at
FROM printing_plateorder po
WHERE po.is_invalid = false
ORDER BY po.created_at DESC
LIMIT 10;
"
echo

# 示例6: 查询最大的表
echo "6. 数据库表大小统计（前10）:"
echo "---"
PGPASSWORD=$DB_PASS psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -c "
SELECT 
    schemaname,
    tablename,
    pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename)) as size
FROM pg_tables
WHERE schemaname = 'public'
ORDER BY pg_total_relation_size(schemaname||'.'||tablename) DESC
LIMIT 10;
"
echo

echo "=== 示例完成 ==="
echo "更多查询示例请查看 SKILL.md 文件"
