# -*- coding: utf-8 -*-
"""横版 A4 输出：A4 = 297×210mm，300dpi = 3508×2480px
版式：顶部主题标题带（红字「科学饮水共促健康」＋作品名，Pillow 叠字，绝不让 AI 写中文）+ 下方整幅画面
"""
import glob, os
from PIL import Image, ImageDraw, ImageFont

BASE = '/data/www/files/waterHealthArt/horizontal'
W, H = 3508, 2480                      # A4 横版 @300dpi
RED, GREY, GOLD = (192, 0, 0), (89, 89, 89), (212, 175, 55)
F_TITLE = '/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc'
F_SUB = '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc'

TITLES = {
 '1_一起喝够八杯水': '作品一 · 一起喝够八杯水',
 '2_院坝里的一杯温开水': '作品二 · 院坝里的一杯温开水',
 '3_白开水最好喝': '作品三 · 白开水最好喝',
 '4_接一杯_喝一口_关紧它': '作品四 · 接一杯 喝一口 关紧它',
 '5_全家一起_喝够每一杯': '作品五 · 全家一起，喝够每一杯',
}


def sheet(src, dst):
    art = Image.open(src).convert('RGB')
    aw = int(2070 * 1.4141)                     # 画面区 2070 高，等比得宽
    art = art.resize((aw, 2070), Image.LANCZOS)
    page = Image.new('RGB', (W, H), (255, 255, 255))
    d = ImageDraw.Draw(page)

    ft = ImageFont.truetype(F_TITLE, 150, index=0)
    fs = ImageFont.truetype(F_SUB, 60, index=0)
    d.text((W // 2, 30), '科学饮水共促健康', font=ft, fill=RED, anchor='mt')
    d.text((W // 2, 250), TITLES[os.path.basename(src).rsplit('.', 1)[0]], font=fs, fill=GREY, anchor='mt')
    d.rectangle([340, 350, W - 340, 354], fill=GOLD)
    page.paste(art, ((W - aw) // 2, 380))
    page.save(dst, quality=95, subsampling=0, dpi=(300, 300))
    return dst


for kind in ('lineart', 'color'):
    outdir = os.path.join(BASE, 'A4横幅', '线条图' if kind == 'lineart' else '配色图')
    os.makedirs(outdir, exist_ok=True)
    files = sorted(glob.glob(os.path.join(BASE, kind, '*.jpg')))
    for src in files:
        p = sheet(src, os.path.join(outdir, os.path.basename(src)))
        print(f"{kind:8s} {os.path.basename(p):28s} {os.path.getsize(p)/1024/1024:.2f}MB  {(W,H)}")

    imgs = [Image.open(f).convert('RGB') for f in sorted(glob.glob(os.path.join(outdir, '*.jpg')))]
    pdf = os.path.join(BASE, 'A4横幅', f'{"线条图" if kind == "lineart" else "配色图"}_5份_A4横版.pdf')
    imgs[0].save(pdf, save_all=True, append_images=imgs[1:], resolution=300.0)
    print(f"PDF {os.path.basename(pdf)}  {len(imgs)}页  {os.path.getsize(pdf)/1024/1024:.2f}MB")
