-- 为 province_daily_price 表生成前7天的15个省份数据
-- 价格在基准价格（从 cattleprovince 表获取）上下浮动1元之内
-- 使用 INSERT IGNORE 避免重复插入（如果某天某省份已有数据则跳过）

-- 生成前7天的数据（包括今天，共7天：今天、昨天、前天...）
INSERT IGNORE INTO `province_daily_price` (`province`, `price`, `price_date`, `create_time`, `up_time`)
SELECT 
    cp.province,
    -- 价格浮动：基准价格 + (-1.00 到 +1.00 之间的随机值)
    -- 使用 ROUND() 保留2位小数
    -- 使用 GREATEST() 确保价格不小于 0.01
    ROUND(
        GREATEST(0.01, 
            cp.province_price + (RAND() * 2 - 1)  -- RAND() * 2 - 1 生成 -1 到 +1 之间的值
        ), 
        2
    ) as price,
    DATE_SUB(CURDATE(), INTERVAL day_offset DAY) as price_date,
    NOW() as create_time,
    NOW() as up_time
FROM 
    (SELECT DISTINCT province, province_price 
     FROM cattleprovince 
     WHERE province_price IS NOT NULL 
     ORDER BY province) cp
CROSS JOIN
    (SELECT 0 as day_offset UNION ALL 
     SELECT 1 UNION ALL 
     SELECT 2 UNION ALL 
     SELECT 3 UNION ALL 
     SELECT 4 UNION ALL 
     SELECT 5 UNION ALL 
     SELECT 6) days
ORDER BY cp.province, day_offset;

-- 验证生成的数据
-- 查看前7天每个省份的价格和与基准价格的差值
SELECT 
    pdp.province,
    pdp.price_date,
    pdp.price,
    cp.province_price as base_price,
    ROUND(pdp.price - cp.province_price, 2) as price_diff,
    CASE 
        WHEN ABS(pdp.price - cp.province_price) <= 1.0 THEN '✓ 在范围内'
        ELSE '✗ 超出范围'
    END as status
FROM province_daily_price pdp
INNER JOIN cattleprovince cp ON pdp.province = cp.province
WHERE pdp.price_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
  AND pdp.price_date <= CURDATE()
ORDER BY pdp.province, pdp.price_date DESC;

-- 统计信息
-- SELECT 
--     COUNT(*) as total_records,
--     COUNT(DISTINCT province) as province_count,
--     MIN(price_date) as earliest_date,
--     MAX(price_date) as latest_date
-- FROM province_daily_price
-- WHERE price_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY);

