#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""资质文件合订本 V02：ISO 13485 + ISO 9001 + 营业执照 + 资质荣誉。"""
import base64
import subprocess
from pathlib import Path
import fitz
from PIL import Image, ImageOps

BASE = Path('/Users/liuxinyuan/Desktop/Hermes输出-工作类')
OUTDIR = BASE / '对外物料' / '公司资质文件_20261102'
OUTDIR.mkdir(parents=True, exist_ok=True)
SRC = Path('/Users/liuxinyuan/Desktop/hermas输入-工作台数据库/公司资质/2026_11_02_珠海宝锐 ISO9001证书中文  公章- 20260713更新')
ISO9001 = SRC / '珠海宝锐 ISO9001证书中文  公章- 20260713更新.pdf'
ISO13485 = SRC / '珠海宝锐ISO13485证书 证书（中文+英文，公章） - 至20271113.pdf'
LICENSE = SRC / '珠海宝锐生物营业执照(无章).pdf'
HONOR_DIR = Path('/Users/liuxinyuan/Desktop/hermas输入-工作台数据库/公司资质/资质荣誉')
LOGO = Path('/Users/liuxinyuan/work/公司资料/logo_transparent.png')
FRONT_HTML = OUTDIR / '_front_v2.html'
FRONT_PDF = OUTDIR / '_front_v2.pdf'
HONOR_HTML = OUTDIR / '_honors_v2.html'
HONOR_PDF = OUTDIR / '_honors_v2.pdf'
OUT = OUTDIR / '宝锐生物_资质文件合订本_20261102_V01.pdf'

# 顺序：现行资质优先；国家小巨人牌匾已过期，放在最后并标注历史
HONORS = [
    ('国家高新技术企业证书', '国家高新技术企业认定', '高新技术企业-2023年.png', ''),
    ('广东省专精特新中小企业', '广东省专精特新中小企业', '2025-2028 专精特新中小企业.png', ''),
    ('广东省分子诊断原料酶工程技术研究中心', '广东省科学技术厅认定', '广东省分子诊断原料酶工程技术研究中心.png', ''),
    ('珠海市企业技术中心', '珠海市企业技术中心', '市级企业技术中心.png', ''),
    ('广东省博士后创新实践基地', '广东省人力资源和社会保障厅批准设立', '广东省博士后创新实践基地.png', ''),
    ('国家专精特新“小巨人”企业', '国家专精特新“小巨人”企业', '国家专精特新小巨人企业高清.png', ''),
]

for p in [ISO9001, ISO13485, LICENSE, LOGO] + [HONOR_DIR / h[2] for h in HONORS]:
    if not p.exists():
        raise SystemExit('missing: %s' % p)
    if p.stat().st_size == 0:
        raise SystemExit('zero size: %s' % p)

LOGO_URI = 'data:image/png;base64,' + base64.b64encode(LOGO.read_bytes()).decode('ascii')

# 优化荣誉图片，控制 HTML/PDF 体积
honor_data = []
for idx, (title, caption, fname, status) in enumerate(HONORS, 1):
    im = Image.open(HONOR_DIR / fname).convert('RGB')
    im = ImageOps.exif_transpose(im)
    im.thumbnail((2200, 1600), Image.LANCZOS)
    jpg = OUTDIR / ('_honor_%02d.jpg' % idx)
    im.save(jpg, 'JPEG', quality=92, optimize=True)
    honor_data.append((title, caption, status, base64.b64encode(jpg.read_bytes()).decode('ascii')))

# 封面 + 目录
front_html = f'''<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><title>宝锐生物 资质文件合订本</title>
<style>
@page{{size:A4;margin:0}}*{{box-sizing:border-box;margin:0;padding:0}}
html,body{{width:210mm;background:#fff;color:#17324A;font-family:"Times New Roman","Songti SC","STSong","SimSun","宋体",serif;-webkit-print-color-adjust:exact;print-color-adjust:exact}}
.sheet{{width:210mm;height:297mm;padding:16mm 18mm 14mm;display:flex;flex-direction:column;position:relative;overflow:hidden;background:#fff;break-after:page}}
.sheet:last-child{{break-after:auto}}
.top{{display:flex;align-items:center;gap:5mm;border-bottom:.5mm solid #CFE0EC;padding-bottom:3mm}}
.top img{{height:11mm;width:auto}}.top .tag{{font-size:7pt;color:#5C7C90;letter-spacing:.1em}}.top .pg{{margin-left:auto;font-family:"Times New Roman","Songti SC","STSong","SimSun","宋体",serif;font-size:9pt;color:#1F4E79}}
.cover-body{{flex:1;display:flex;flex-direction:column;justify-content:center;padding-bottom:25mm}}
.kicker{{font-size:7.5pt;letter-spacing:.24em;color:#4E8AA8;font-weight:600}}
h1{{font-size:34pt;line-height:1.1;color:#123B5C;letter-spacing:-.02em;margin:5mm 0 3mm}}
h1 span{{display:block;font-size:15pt;font-weight:500;color:#1F4E79;letter-spacing:.02em;margin-top:2mm}}
.rule{{width:42mm;height:1mm;background:#2A9D8F;margin:7mm 0}}
.company{{font-size:13pt;color:#1F4E79;margin-top:2mm}}.meta{{font-size:9pt;color:#5C7C90;line-height:1.9;margin-top:14mm}}.meta b{{color:#34566B;font-weight:600}}
.cover-foot{{font-size:8pt;color:#6C8798;border-top:.4mm solid #DCE8EF;padding-top:3mm}}.cover-foot b{{color:#1F4E79}}
.body{{flex:1;display:flex;flex-direction:column;padding-top:10mm}}h2{{font-size:22pt;color:#123B5C;margin:0 0 2mm}}.sub{{font-size:8pt;color:#5C7C90;margin-bottom:8mm}}
table{{width:100%;border-collapse:collapse;table-layout:fixed;font-size:7.8pt;line-height:1.4}}th{{background:#1F4E79;color:#fff;text-align:left;padding:2.6mm 2.3mm;font-weight:600}}td{{border-bottom:.3mm solid #D8E6EF;padding:2.5mm 2.3mm;vertical-align:middle;color:#34566B}}td.num{{font-family:"Times New Roman","Songti SC","STSong","SimSun","宋体",serif;color:#1F4E79;font-weight:700;text-align:center;font-size:10pt}}td.cn{{font-family:"Times New Roman","Songti SC","STSong","SimSun","宋体",serif;color:#1F4E79;font-size:6.8pt;text-align:left;white-space:nowrap;font-variant-numeric:tabular-nums;padding-left:2.3mm}}
th:nth-child(1),th:nth-child(4),td:nth-child(1),td:nth-child(4){{text-align:center;vertical-align:middle}}
th:nth-child(3),td:nth-child(3){{text-align:left;vertical-align:middle}}
tr.hist td{{background:#FFF8F1}}tr.hist td:first-child{{color:#A35A1E}}
.note{{margin-top:5mm;background:#F4F9FC;border-left:1.4mm solid #2A9D8F;padding:3.5mm 4.5mm;font-size:7.1pt;line-height:1.65;color:#3E6074}}.note b{{color:#1F4E79}}
.stamp{{margin-top:auto;border-top:.4mm solid #DCE8EF;padding-top:3.5mm;font-size:7.2pt;color:#6C8798;line-height:1.65}}.stamp b{{color:#1F4E79}}
.foot{{font-size:7pt;color:#6C8798;border-top:.4mm solid #DCE8EF;padding-top:2.5mm;display:flex;gap:4mm;align-items:center}}.foot b{{color:#1F4E79}}.foot .slogan{{margin-left:auto;color:#4D7C96}}
</style></head><body>

<div class="sheet">
  <div class="top"><img src="{LOGO_URI}" alt="宝锐生物 BIORI BIOTECH"><span class="tag">BIORI BIOTECH · COMPANY QUALIFICATION</span><span class="pg">01</span></div>
  <div class="cover-body">
    <div class="kicker">COMPANY QUALIFICATION PACKAGE</div>
    <h1>资质文件合订本<span>珠海宝锐生物科技有限公司</span></h1>
    <div class="rule"></div>
    <div class="meta"><b>文件内容：</b>ISO 13485、ISO 9001、营业执照、资质荣誉<br>2026 年<br>中国 · 广东 · 珠海</div>
  </div>
  <div class="cover-foot"><b>BIORI BIOTECH</b>　｜　守护生命健康，缔造美好生活</div>
</div>

<div class="sheet">
  <div class="top"><img src="{LOGO_URI}" alt="宝锐生物 BIORI BIOTECH"><span class="tag">DOCUMENT INDEX · 文件目录</span><span class="pg">02</span></div>
  <div class="body">
    <h2>文件目录</h2>
    <div class="sub">共 12 页。证书、执照与荣誉牌匾均按原件页面插入。</div>
    <table>
      <thead><tr><th style="width:8%">序号</th><th style="width:44%">文件名称</th><th style="width:34%">证书/执照编号</th><th style="width:14%">页次</th></tr></thead>
      <tbody>
        <tr><td class="num">01</td><td><b>ISO 13485:2016 医疗器械质量管理体系认证证书</b><br>中文、英文两页；SGS 签发</td><td class="cn">CN24/00007233</td><td>03–04</td></tr>
        <tr><td class="num">02</td><td><b>ISO 9001:2015 质量管理体系认证证书</b><br>中文；中国质量认证中心（CQC）签发</td><td class="cn">00124Q304781R201</td><td>05</td></tr>
        <tr><td class="num">03</td><td><b>营业执照（副本）</b><br>统一社会信用代码：91440400592109797M</td><td class="cn">91440400592109797M</td><td>06</td></tr>
        <tr><td class="num">04</td><td><b>国家高新技术企业证书</b><br>国家高新技术企业认定</td><td class="cn">GR202344001601</td><td>07</td></tr>
        <tr><td class="num">05</td><td><b>广东省专精特新中小企业</b><br>广东省工业和信息化厅认定</td><td class="cn">—</td><td>08</td></tr>
        <tr><td class="num">06</td><td><b>广东省分子诊断原料酶工程技术研究中心</b><br>广东省科学技术厅认定</td><td class="cn">ID 2022C023</td><td>09</td></tr>
        <tr><td class="num">07</td><td><b>珠海市企业技术中心</b><br>珠海市企业技术中心</td><td class="cn">—</td><td>10</td></tr>
        <tr><td class="num">08</td><td><b>广东省博士后创新实践基地</b><br>广东省人力资源和社会保障厅批准设立</td><td class="cn">—</td><td>11</td></tr>
        <tr><td class="num">09</td><td><b>国家专精特新“小巨人”企业</b><br>国家专精特新“小巨人”企业</td><td class="cn">—</td><td>12</td></tr>
      </tbody>
    </table>
    <div class="note"><b>说明：</b>本合订本共 12 页。证书、执照与荣誉牌匾均按原件页面插入，未改动证书内容、印章或版式。</div>
    <div class="stamp"><b>资料提供：</b>珠海宝锐生物科技有限公司<br><b>联系电话：</b>0756-8699969　｜　<b>邮箱：</b>marketing@biori.com　｜　<b>网址：</b>www.biori.com<br><b>地址：</b>广东省珠海市香洲区水岸一路 88 号</div>
  </div>
  <div class="foot"><b>BIORI BIOTECH</b><span>资质文件合订本 · 2026</span><span class="slogan">守护生命健康，缔造美好生活</span></div>
</div>
</body></html>'''

FRONT_HTML.write_text(front_html, encoding='utf-8')

# 荣誉页：A4 横向，每页一张牌匾/证书
honor_pages = []
for i, (title, caption, status, b64) in enumerate(honor_data):
    pgno = 7 + i
    honor_pages.append(f'''<div class="sheet">
  <div class="top"><img src="{LOGO_URI}" alt="宝锐生物 BIORI BIOTECH"><span class="tag">QUALIFICATION & HONOUR · 资质荣誉</span><span class="pg">{pgno:02d}</span></div>
  <div class="hbody">
    <div class="htitle">{title}</div>
    <div class="himg"><img src="data:image/jpeg;base64,{b64}" alt="{title}"></div>
    <div class="hcap">{caption}</div>
  </div>
  <div class="foot"><b>BIORI BIOTECH</b><span>资质文件合订本 · 2026</span><span class="slogan">守护生命健康，缔造美好生活</span></div>
</div>''')

honor_html = f'''<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><title>资质荣誉</title>
<style>
@page{{size:A4 landscape;margin:0}}*{{box-sizing:border-box;margin:0;padding:0}}
html,body{{width:297mm;background:#fff;color:#17324A;font-family:"Times New Roman","Songti SC","STSong","SimSun","宋体",serif;-webkit-print-color-adjust:exact;print-color-adjust:exact}}
.sheet{{width:297mm;height:210mm;padding:9mm 14mm 8mm;display:flex;flex-direction:column;position:relative;overflow:hidden;background:#fff;break-after:page}}.sheet:last-child{{break-after:auto}}
.top{{display:flex;align-items:center;gap:4mm;border-bottom:.4mm solid #CFE0EC;padding-bottom:2mm;flex:0 0 12mm}}.top img{{height:8mm;width:auto}}.top .tag{{font-size:6.5pt;color:#5C7C90;letter-spacing:.08em}}.top .pg{{margin-left:auto;font-family:"Times New Roman","Songti SC","STSong","SimSun","宋体",serif;font-size:8pt;color:#1F4E79}}
.hbody{{flex:1;display:flex;flex-direction:column;min-height:0;padding-top:5mm}}
.htitle{{font-size:12pt;font-weight:700;color:#123B5C;display:flex;align-items:center;gap:3mm;flex:0 0 9mm}}
.badge{{font-size:6.5pt;padding:1mm 2.4mm;border-radius:1mm;color:#fff;font-weight:600;letter-spacing:.04em}}
.himg{{flex:1;display:flex;align-items:center;justify-content:center;min-height:0;padding:2mm 0}}.himg img{{max-width:265mm;max-height:145mm;width:auto;height:auto;object-fit:contain;border:.3mm solid #D8E6EF}}
.hcap{{font-size:8pt;color:#5C7C90;line-height:1.5;flex:0 0 10mm;text-align:center;padding-top:1.5mm}}
.foot{{font-size:6.5pt;color:#6C8798;border-top:.3mm solid #DCE8EF;padding-top:2mm;display:flex;gap:4mm;align-items:center;flex:0 0 7mm}}.foot b{{color:#1F4E79}}.foot .slogan{{margin-left:auto;color:#4D7C96}}
</style></head><body>{''.join(honor_pages)}</body></html>'''
HONOR_HTML.write_text(honor_html, encoding='utf-8')

chrome = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
for html, pdf in [(FRONT_HTML, FRONT_PDF), (HONOR_HTML, HONOR_PDF)]:
    subprocess.run([chrome, '--headless=new', '--disable-gpu', '--no-pdf-header-footer',
                    f'--print-to-pdf={pdf}', f'file://{html}'],
                   check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

out = fitz.open()
front = fitz.open(FRONT_PDF)
out.insert_pdf(front)
for p in [ISO13485, ISO9001, LICENSE]:
    src = fitz.open(p)
    out.insert_pdf(src)
    src.close()
hon = fitz.open(HONOR_PDF)
out.insert_pdf(hon)
hon.close()

toc = [[1, '封面', 1], [1, '文件目录', 2], [1, 'ISO 13485:2016 证书（中文）', 3], [1, 'ISO 13485:2016 证书（英文）', 4], [1, 'ISO 9001:2015 证书（中文）', 5], [1, '营业执照（副本）', 6]]
toc += [[1, h[0], 7 + i] for i, h in enumerate(HONORS)]
out.set_toc(toc)
out.set_metadata({'title': '宝锐生物 资质文件合订本', 'author': '珠海宝锐生物科技有限公司', 'subject': 'ISO 13485、ISO 9001、营业执照、资质荣誉', 'creator': 'BIORI BIOTECH'})
out.save(OUT, garbage=4, deflate=True)
out.close()
print('written', OUT, OUT.stat().st_size, 'pages', fitz.open(OUT).page_count)
