# -*- coding: utf-8 -*-
"""final2 横版 A4 合成（已去掉手抄报式标题带）
版式：画面尽量占满 A4（左右各留 120px），仅在最下方留一条窄带，
      右下角用小号灰字标一行作品名（不是标题框、不是分割线，避免手抄报观感）
A4 = 297×210mm @300dpi = 3508×2480
"""
import glob, os
from PIL import Image, ImageDraw, ImageFont

BASE = '/data/www/files/waterHealthArt/final2'
W, H = 3508, 2480
GREY = (110, 110, 110)
F_SUB = '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc'

SUB = {
 'A_饮水思源_一滴水的旅行': '作品一《饮水思源——一滴水的旅行》',
 'B_白开水最好喝': '作品二《白开水最好喝》',
 'C_接一杯_喝一口_关紧它': '作品三《接一杯 喝一口 关紧它》',
}
MARGIN = 120
BAND = 108                      # 底部窄带高度
ART_W = W - 2 * MARGIN          # 3268
ART_H = int(ART_W / 1.4141)     # 2311


def sheet(src, dst):
    art = Image.open(src).convert('RGB').resize((ART_W, ART_H), Image.LANCZOS)
    page = Image.new('RGB', (W, H), (255, 255, 255))
    page.paste(art, (MARGIN, 24))
    d = ImageDraw.Draw(page)
    fs = ImageFont.truetype(F_SUB, 46, index=0)
    d.text((W - MARGIN, H - 34), SUB[os.path.basename(src).rsplit('.', 1)[0]], font=fs, fill=GREY, anchor='rs')
    page.save(dst, quality=95, subsampling=0, dpi=(300, 300))
    return dst


for kind, label in (('illustration', '配色图'), ('lineart', '线条图')):
    outdir = os.path.join(BASE, 'A4横版', label)
    os.makedirs(outdir, exist_ok=True)
    for src in sorted(glob.glob(os.path.join(BASE, kind, '*.jpg'))):
        p = sheet(src, os.path.join(outdir, os.path.basename(src)))
        print(f"{label}  {os.path.basename(p):28s} {os.path.getsize(p)/1024/1024:.2f}MB  {W}x{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'{label}_3份_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")
