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

BASE = '/data/www/files/waterHealthArt/final'
W, H = 3508, 2480
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'

SUB = {
 'A_饮水思源_一滴水的旅行': '作品一 · 饮水思源——一滴水的旅行',
 'B_白开水最好喝': '作品二 · 白开水最好喝',
 'C_接一杯_喝一口_关紧它': '作品三 · 接一杯 喝一口 关紧它',
}


def sheet(src, dst):
    art = Image.open(src).convert('RGB')
    aw = int(2070 * 1.4141)
    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), SUB[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, 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):30s} {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")
