# -*- coding: utf-8 -*-
# ! /usr/bin/env python3
# @Author           : yangzihao
# @CreateTime       : 2024/04/17

"""
This file is for PDF report generate.
Refer to the CSDN: https://blog.csdn.net/cainiao_python/article/details/128928298
"""

from reportlab.pdfbase import pdfmetrics  # 注册字体
from reportlab.pdfbase.ttfonts import TTFont  # 字体类
from reportlab.platypus import Table, SimpleDocTemplate, Paragraph, Image  # 报告内容相关类
from reportlab.lib.pagesizes import A4  # 页面的标志尺寸(8.5*inch, 11*inch)
from reportlab.lib.styles import getSampleStyleSheet  # 文本样式
from reportlab.lib import colors  # 颜色模块
from reportlab.graphics.charts.barcharts import VerticalBarChart  # 图表类
from reportlab.graphics.charts.legends import Legend  # 图例类
from reportlab.graphics.shapes import Drawing  # 绘图工具
from reportlab.lib.units import cm  # 单位:cm
from reportlab.lib import utils

import json
import pandas as pd

# 注册字体(提前准备好字体文件, 如果同一个文件需要多种字体可以注册多个)
pdfmetrics.registerFont(TTFont('SimSun', 'SimSun.ttf'))


class ReportPDF:
    """
    This class is for PDF report generate.
    """

    # 绘制标题
    @staticmethod
    def draw_title(title: str):
        # 获取所有样式表
        style = getSampleStyleSheet()
        # 拿到标题样式
        ct = style['Heading4']
        # 单独设置样式相关属性
        ct.fontName = 'SimSun'  # 字体名
        ct.fontSize = 18  # 字体大小
        ct.leading = 30  # 行间距
        ct.textColor = colors.black  # 字体颜色
        ct.alignment = 1  # 居中
        ct.bold = True
        # 创建标题对应的段落,并且返回
        return Paragraph(title, ct)

    # 绘制小标题
    @staticmethod
    def draw_little_title(title: str):
        # 获取所有样式表
        style = getSampleStyleSheet()
        # 拿到标题样式
        ct = style['Normal']
        # 单独设置样式相关属性
        ct.fontName = 'SimSun'  # 字体名
        ct.fontSize = 15  # 字体大小
        # ct.leading = 15  # 行间距
        ct.textColor = colors.darkblue  # 字体颜色
        # 创建标题对应的段落,并且返回
        return Paragraph(title, ct)

    # 绘制普通段落内容
    @staticmethod
    def draw_text(text: str):
        # 获取所有样式表
        style = getSampleStyleSheet()
        # 获取普通样式
        ct = style['Normal']
        ct.fontName = 'SimSun'
        ct.fontSize = 10
        # ct.wordWrap = 'CJK'  # 设置自动换行
        ct.alignment = 0  # 左对齐
        # ct.firstLineIndent = 32  # 第一行开头空格
        ct.leading = 15
        return Paragraph(text, ct)

    # 绘制普通段落内容
    @staticmethod
    def draw_line_feed(text: str):
        # 获取所有样式表
        style = getSampleStyleSheet()
        # 获取普通样式
        ct = style['Normal']
        ct.fontName = 'SimSun'
        ct.fontSize = 10
        ct.textColor = colors.white
        # ct.wordWrap = 'CJK'  # 设置自动换行
        ct.alignment = 0  # 左对齐
        # ct.firstLineIndent = 32  # 第一行开头空格
        ct.leading = 15
        return Paragraph(text, ct)

    # 绘制表格
    @staticmethod
    def draw_table(*args):
        # 列宽度
        # col_width = 120
        style = [
            ('FONTNAME', (0, 0), (-1, -1), 'SimSun'),  # 字体
            ('FONTSIZE', (0, 0), (-1, 0), 9),  # 第一行的字体大小
            ('FONTSIZE', (0, 1), (-1, -1), 9),  # 第二行到最后一行的字体大小
            ('BACKGROUND', (0, 0), (-1, 0), '#d5dae6'),  # 设置第一行背景颜色
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),  # 第一行水平居中
            ('ALIGN', (0, 1), (-1, -1), 'CENTER'),  # 第二行到最后一行左右左对齐
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),  # 所有表格上下居中对齐
            ('TEXTCOLOR', (0, 0), (-1, -1), colors.darkslategray),  # 设置表格内文字颜色
            ('GRID', (0, 0), (-1, -1), 0.5, colors.grey),  # 设置表格框线为grey色,线宽为0.5
            # ('SPAN', (0, 1), (0, 2)),  # 合并第一列二三行
            # ('SPAN', (0, 3), (0, 4)),  # 合并第一列三四行
            # ('SPAN', (0, 5), (0, 6)),  # 合并第一列五六行
            # ('SPAN', (0, 7), (0, 8)),  # 合并第一列五六行
        ]
        # table = Table(args, colWidths=col_width, style=style)
        table = Table(args, style=style)
        return table

    # 创建图表
    @staticmethod
    def draw_bar(bar_data: list, ax: list, items: list):
        drawing = Drawing(500, 250)
        bc = VerticalBarChart()
        bc.x = 45  # 整个图表的x坐标
        bc.y = 45  # 整个图表的y坐标
        bc.height = 200  # 图表的高度
        bc.width = 350  # 图表的宽度
        bc.data = bar_data
        bc.strokeColor = colors.black  # 顶部和右边轴线的颜色
        bc.valueAxis.valueMin = 5000  # 设置y坐标的最小值
        bc.valueAxis.valueMax = 26000  # 设置y坐标的最大值
        bc.valueAxis.valueStep = 2000  # 设置y坐标的步长
        bc.categoryAxis.labels.dx = 2
        bc.categoryAxis.labels.dy = -8
        bc.categoryAxis.labels.angle = 20
        bc.categoryAxis.categoryNames = ax

        # 图示
        leg = Legend()
        leg.fontName = 'SimSun'
        leg.alignment = 'right'
        leg.boxAnchor = 'ne'
        leg.x = 475  # 图例的x坐标
        leg.y = 240
        leg.dxTextSpace = 10
        leg.columnMaximum = 3
        leg.colorNamePairs = items
        drawing.add(leg)
        drawing.add(bc)
        return drawing

    # 绘制图片
    @staticmethod
    def draw_img(path):
        img = Image(path)  # 读取指定路径下的图片
        img.drawWidth = 0.8 * cm  # 设置图片的宽度
        img.drawHeight = 0.8 * cm  # 设置图片的高度
        img.hAlign = 0
        return img


def report_generate(reportDict, reportPdf):
    # with open(f'{reportJson}', 'r', encoding='utf-8') as f:
    #     data = json.load(f)

    data = reportDict  # dict
    # 创建PDF文档
    styles = getSampleStyleSheet()

    # 提取数据
    name = data["name"]
    # algorithm_score = data["algorithmComprehensiveScore"]
    # algorithm_level = data["algorithmLevel"]
    test_mileage = data["testMileage"]
    test_duration = data["testDuration"]
    algorithm_result_description = data["algorithmResultDescription"]
    efficient_description = data["details"]["efficient"]["description"]
    comfort_description = data["details"]["comfort"]["description"]

    efficient_description1 = data["details"]["efficient"]["description1"]
    efficient_description2 = data["details"]["efficient"]["description2"]
    comfort_description1 = data["details"]["comfort"]["description1"]
    comfort_description2 = data["details"]["comfort"]["description2"]

    # 创建表格数据
    # table_data = [
    #     ["评价维度", "评价指标", "指标描述"],
    #     ["高效性", "无障碍物停止", efficient_description1],
    #     ["高效性", "速度", efficient_description2],
    #     ["平顺性", "线加速度", comfort_description1],
    #     ["平顺性", "角加速度", comfort_description2]
    # ]
    table_data = [
        ("评价维度", "评价指标", "指标描述"),
        ("高效性", "无障碍物停止", efficient_description1),
        ("高效性", "速度", efficient_description2),
        ("平顺性", "线加速度", comfort_description1),
        ("平顺性", "角加速度", comfort_description2)
    ]

    # 创建内容对应的空列表
    content = list()
    content.append(ReportPDF.draw_img('Pji.png'))
    content.append(ReportPDF.draw_title('朴津室内AMR算法评价报告'))

    infos = f"数据包: {name}, 行驶时长: {test_duration}, 行驶里程: {test_mileage}"
    content.append(ReportPDF.draw_text(infos))
    content.append(ReportPDF.draw_text(algorithm_result_description))
    content.append(ReportPDF.draw_text(efficient_description))
    content.append(ReportPDF.draw_text(comfort_description))
    content.append(ReportPDF.draw_line_feed("换行"))

    content.append(ReportPDF.draw_table(*table_data))

    content.append(ReportPDF.draw_line_feed("换行"))

    # 添加图片到PDF文档
    for key, value in data["graphPath"].items():
        # content.append(Paragraph(key, styles['Heading5']))
        content.append(ReportPDF.draw_text(key))
        content.append(Image(value, width=480, height=120))

    # 创建PDF文档
    # pdf_file = "./report123.pdf"
    pdf_file = reportPdf
    doc = SimpleDocTemplate(pdf_file, pagesize=A4)

    doc.build(content)
    print("PDF报告已生成!")


if __name__ == '__main__':
    reportJson = './report.json'
    reportPdf = "./report123.pdf"
    report_generate(reportJson, reportPdf)
    print('over')