"""
步骤：
1、整理需要处理的款号图-输出款号图文件夹
2、整理所有相关的图片作为素材图
3、按要求进行拼接
"""
import os
import time

from PIL import ImageFont
from module.view_control.generate_goods_no_detail_pic.detail_generate_base import DetailBase
from module.view_control.generate_goods_no_detail_pic.pic_deal import PictureProcessing
from PIL import Image, ImageDraw
import math


class DetailPicGetXiaoSuShuoXie3(DetailBase):
    need_view = ["俯视", "侧视", "后跟", "鞋底", "内里"]
    root = r"{}\resources\detail_temp\xiaosushuoxie\3".format(os.getcwd())

    def __init__(self, goods_no, goods_no_value: dict, out_put_dir, windows=None, test=False,excel_data=None,assigned_page_list=None):
        super().__init__(goods_no, goods_no_value, out_put_dir, windows=windows,excel_data=excel_data,assigned_page_list=assigned_page_list)
        self.root = r"{}\resources\detail_temp\xiaosushuoxie\3".format(os.getcwd())
        self.base_bg_color = (236, 226, 211)
        self.deal_pic_func_list = [
            self.deal_pic_1,
            self.deal_pic_2,
            self.deal_pic_3,
            self.deal_pic_4,
            self.deal_pic_5,
        ]

        if test:
            self.run_test()
        else:
            self.run_all()


    def run_test(self):
        detailed_images = []
        detailed_images.append(self.deal_pic_1())
        detailed_images.append(self.deal_pic_2())
        detailed_images.append(self.deal_pic_3())
        detailed_images.append(self.deal_pic_4())
        detailed_images.append(self.deal_pic_5())
        img = self.add_pic(detailed_images)
        img.save(r"{}/{}.jpg".format(self.out_put_dir,self.goods_no, format="JPEG"))

    def deal_pic_1(self):
        """   制作主图  """
        detailed_images = []
        pp_bg = PictureProcessing(r"{}\template_1.png".format(self.root))
        detailed_images.append(pp_bg)
        # -------粘贴文字-------
        mainTitle = self.get_text_value("标题")
        subTitle = self.get_text_value("副标题")

        if mainTitle:
            font = ImageFont.truetype(r"resources\ttf\puhui\Bold.ttf", 70)
            text_1_bg = PictureProcessing("RGB", (1200, 500), self.base_bg_color)
            text_1_bg = text_1_bg.get_text_image_advanced(
                value=(600, 30),
                font=font,
                text=mainTitle,
                align="center",
                anchor="mm",
                spacing=5,
                fill=(17, 16, 16),
                return_mode="min_image_high",
                margins=(10, 10, 0, 0)
            )
            # text_1_bg.show()
            detailed_images.append(text_1_bg)

        if subTitle:
            font = ImageFont.truetype(r"resources\ttf\puhui\Bold.ttf", 40)
            text_2_bg = PictureProcessing("RGB", (1200, 500), self.base_bg_color)
            text_2_bg = text_2_bg.get_text_image_advanced(
                value=(600, 30),
                font=font,
                text=mainTitle,
                align="center",
                anchor="mm",
                spacing=5,
                fill=(17, 16, 16),
                return_mode="min_image_high",
                margins=(10, 10, 0, 0)
            )
            detailed_images.append(text_2_bg)


        # ====粘贴组合图以及其他图
        goods_art_no_list = list(self.data.keys())
        # 文字排列
        _zuhe_pic_list = []
        color_name_list = ["组合", "组合2", "组合3"]
        for color_name in color_name_list:
            pp_1 = self.get_overlay_pic_from_dict(
                goods_art_no=goods_art_no_list[0],
                color_name=color_name,
                bg_color=self.base_bg_color,
            )
            if not pp_1:
                continue
            pp_1 = pp_1.resize(value=int(pp_bg.width / 1.45))
            pp_1 = pp_1.paste_img_invert(
                top_img=PictureProcessing("RGB", (pp_bg.width, pp_1.height + 30), self.base_bg_color),
                base="cc")

            _zuhe_pic_list.append(pp_1)

        if not _zuhe_pic_list:
            pp_1 = self.get_overlay_pic_from_dict(
                goods_art_no=goods_art_no_list[0],
                color_name="俯视",
                bg_color=self.base_bg_color,
            )
            pp_1 = pp_1.resize(value=int(pp_bg.width / 1.45))
            pp_1 = pp_1.paste_img_invert(top_img=PictureProcessing("RGB", (pp_bg.width, pp_1.height + 30), self.base_bg_color),
                                         base="cc")

            _zuhe_pic_list.append(pp_1)

        detailed_images.extend(_zuhe_pic_list)
        detailed_images.append(PictureProcessing(r"{}\template_1_1.png".format(self.root)))
        return PictureProcessing(im=self.add_pic(detailed_images))

    def deal_pic_2(self):
        """
        细节解析
        """
        # 文字排列
        detailed_images = []
        pp_bg = PictureProcessing(
            r"{}\template_2.png".format(
                self.root
            )
        )
        detailed_images.append(pp_bg)


        goods_art_no_list = list(self.data.keys())

        pp_1 = self.get_overlay_pic_from_dict(
            goods_art_no=goods_art_no_list[0],
            color_name="侧视",
            bg_color=self.base_bg_color,
        )
        pp_1= pp_1.resize(value=pp_bg.width / 1.4)
        pp_1= pp_1.paste_img_invert(top_img=PictureProcessing("RGB", (pp_bg.width, pp_1.height + 40), self.base_bg_color),
                                    base="cc"
                                    )
        detailed_images.append(pp_1)

        pp_bg_bottom = PictureProcessing(r"{}\template_2_1.png".format(self.root))
        detailed_images.append(pp_bg_bottom)
        return PictureProcessing(im=self.add_pic(detailed_images))

    def deal_pic_3(self):
        """   各个颜色细节展示  """
        detailed_images = []
        pp_bg = PictureProcessing(
            r"{}\template_3.png".format(
                self.root
            )
        )
        detailed_images.append(pp_bg)


        # ----------主图放置
        y = 120
        pp_list_1 = []
        font = ImageFont.truetype(r"resources\ttf\puhui\Medium.ttf", 25)
        goods_art_no_list = list(self.data.keys())

        all_color_name = []
        for index, goods_art_no in enumerate(goods_art_no_list):
            pp_jpg = self.get_overlay_pic_from_dict(
                goods_art_no=goods_art_no,
                color_name="侧视",
                bg_color=self.base_bg_color,
            )
            if pp_jpg is None:
                continue
            pp_jpg = pp_jpg.resize(value=440)
            color_name = self.goods_no_value["货号资料"][index]["颜色名称"]
            all_color_name.append(color_name)
            text_bg = PictureProcessing("RGB", (440, 200), (255, 255, 255))
            text_bg = text_bg.get_text_image_advanced(
                value=(220, 10),
                font=font,
                text="【{}】".format(color_name),
                align="center",
                anchor="mm",
                spacing=5,
                fill=(55, 55, 55),
                return_mode="min_image_high",
                margins=(10, 5, 0, 0)
            )
            # text_bg.show()
            _bg = PictureProcessing("RGB", (440, pp_jpg.height+text_bg.height), (255, 255, 255))
            _bg = _bg.paste_img(top_img=pp_jpg)
            _bg = _bg.paste_img(top_img=text_bg,value=(0,pp_jpg.height))
            pp_list_1.append(_bg)

        rows = 2
        shoes_bg = PictureProcessing().horizontal_distribution(
            pp_list=pp_list_1,
            bg_width=1200,
            margins=(0, 0, 40, 40),
            line_spacing=60,
            number_per_row=rows,
        )
        detailed_images.append(shoes_bg)


        font_bg = PictureProcessing(r"{}\template_3_1_new.png".format(self.root))
        font = ImageFont.truetype(r"resources\ttf\puhui\Medium.ttf", 30)
        base_x = pp_bg.width - 229
        base_y = 205

        text_list = [
            ("-{}".format("-".join(all_color_name)), (base_x, base_y)),
            ("-{}".format(self.get_text_value("鞋面材质")), (base_x, base_y+70*1)),
            ("-{}".format(self.get_text_value("内里材质")), (base_x, base_y+70*2)),
            ("-{}".format(self.get_text_value("鞋底材质")), (base_x, base_y+70*3)),
            ("-{}".format(self.get_text_value("鞋垫材质")), (base_x, base_y+70*4 )),
            ("-{}".format(self.get_text_value("跟高")), (base_x, base_y+70*5)),
            ("-{}".format(self.get_text_value("尺码")), (base_x, base_y+70*6)),
        ]
        for text_item in text_list:
            position = text_item[1]
            text_str = text_item[0]
            xPos = position[0]
            for char in reversed(text_str):
                font_bg.add_text(
                    mode="pixel",
                    value=(xPos, position[1]),
                    font=font,
                    text=char,
                    align="right",
                    anchor="mm",
                    spacing=10,
                    fill=(30, 30, 30),
                )
                if not "\u4e00" <= char <= "\u9fff":
                    xPos -= 20
                else:
                    xPos -= 35
        # 其他图片
        detailed_images.append(font_bg)
        return PictureProcessing(im=self.add_pic(detailed_images))

    def deal_pic_4(self):
        # =============设计理念================
        detail_images = []
        top_bg = PictureProcessing(r"{}\template_4.png".format(self.root))
        detail_images.append(top_bg)

        font_1 = ImageFont.truetype(r"resources\ttf\puhui\Bold.ttf", 40)
        # 粘贴文字
        text = self.get_text_value("设计理念")
        if not text:
            text = "引领全新裸足脚感，开启自信步履亲肤\n优质鞋面材质赋予全新舒适脚感\n多元场景穿搭，满足你的不同STYLE"
        _, text_height = self.get_font_render_size(text, font_1)
        text_bg = PictureProcessing(
            "RGB",
            (
                top_bg.width,
                text_height + 350,
            ),
            (236, 227, 212),
        )
        goods_art_no_list = list(self.data.keys())
        # y = 430

        x = top_bg.width / 2
        text_bg = text_bg.add_text(
            mode="pixel",
            value=(x, math.ceil(text_bg.height / 2) - 60),
            font=font_1,
            text=text,
            align="center",
            anchor="mm",
            spacing=15,
            fill=(97, 97, 98),
        )
        detail_images.append(text_bg)

        # ==========3个提示信息=========
        title_font = ImageFont.truetype(r"resources\ttf\puhui\Heavy.ttf", 60)
        sub_title_font = ImageFont.truetype(r"resources\ttf\puhui\Medium.ttf", 30)
        desc_font = ImageFont.truetype(r"resources\ttf\puhui\Heavy.ttf", 35)
        color_name_list = ["俯视", "内里", "侧视"]
        # 添加分割线
        detail_images.append(PictureProcessing("RGB", (top_bg.width, 100), (255, 255, 255)))

        for index, color_name in enumerate(color_name_list):
            # 添加分割线
            detail_images.append(PictureProcessing("RGB", (top_bg.width, 20), (255, 255, 255)))

            t_title = self.get_text_value("提示{}主标题".format(index + 1))
            if t_title:
                t_title_pp = PictureProcessing("RGB", (top_bg.width, 500), (255, 255, 255))
                t_title_pp=t_title_pp.get_text_image_advanced(
                    value=(int(top_bg.width / 2), 0),
                    font=title_font,
                    text=t_title,
                    align="center",
                    anchor="ma",
                    spacing=10,
                    fill=(55, 55, 55),
                    return_mode="min_image_high",
                    margins=(10, 10, 0, 0)
                )
                detail_images.append(t_title_pp)


                t_sub_title = self.get_text_value("提示{}副标题".format(index + 1))
                if t_sub_title:
                    t_sub_title_pp = PictureProcessing("RGB", (top_bg.width, 500), (255, 255, 255))
                    t_sub_title_pp = t_sub_title_pp.get_text_image_advanced(
                        value=(int(top_bg.width / 2),0),
                        font=sub_title_font,
                        text=t_sub_title,
                        align="center",
                        anchor="ma",
                        spacing=10,
                        fill=(55, 55, 55),
                        return_mode="min_image_high",
                        margins=(10, 10, 0, 0)
                    )
                    detail_images.append(t_sub_title_pp)


            # 添加图
            pp_jpg = self.get_overlay_pic_from_dict(
                goods_art_no=goods_art_no_list[0],
                color_name=color_name,
                bg_color=self.base_bg_color
            )
            t_desc = self.get_text_value("提示{}描述".format(index + 1))
            if color_name == "俯视":
                pp_jpg = pp_jpg.resize(value=1300)
                pp_jpg = pp_jpg.paste_img_invert(
                    top_img=PictureProcessing("RGB", (749, 1009 if pp_jpg.height>1009 else pp_jpg.height), (236, 227, 212)), base="ws",
                    value=(-300, -50))
                text_pos_value = (50, 50)
                align = "left"
                anchor = ""

            if color_name == "内里":
                pp_jpg = pp_jpg.resize(value=2000)
                pp_jpg = pp_jpg.paste_img_invert(
                    top_img=PictureProcessing("RGB", (749, pp_jpg.height + 150), (236, 227, 212)), base="wc",
                    value=(-230, 0))
                text_pos_value = (50, 50)
                align = "left"
                anchor = ""

            if color_name == "侧视":
                pp_jpg = pp_jpg.resize(value=1600)
                pp_jpg = pp_jpg.paste_img_invert(
                    top_img=PictureProcessing("RGB", (749, 1009 if pp_jpg.height>1009 else pp_jpg.height), (236, 227, 212)), base="se",
                    value=(0, -30))
                text_pos_value = (pp_jpg.width - 30, pp_jpg.height - 360)
                align = "right"
                anchor = "rs"

            if t_desc:
                pp_jpg = pp_jpg.add_text(
                    mode="pixel",
                    value=text_pos_value,
                    font=desc_font,
                    text=t_desc,
                    align=align,
                    anchor=anchor,
                    spacing=10,
                    fill=(102, 102, 102),
                )
            pp_jpg = pp_jpg.paste_img_invert(
                top_img=PictureProcessing("RGB", (top_bg.width, pp_jpg.height,), (255, 255, 255), ), base="cc",
                value=(0, 0))
            detail_images.append(pp_jpg)
            # 添加分割线
            detail_images.append(PictureProcessing("RGB", (top_bg.width, 60), (255, 255, 255), ))

        # 添加分割线
        detail_images.append(PictureProcessing("RGB", (top_bg.width, 100), (255, 255, 255), ))
        image = PictureProcessing(im=self.add_pic(detail_images))
        return image

    def deal_pic_5(self):
        bg_color = (255, 255, 255)
        detailed_images = []
        goods_art_no_list = list(self.data.keys())
        top_bg = PictureProcessing(
            r"{}\template_5.png".format(
                self.root
            )
        )

        detailed_images.append(top_bg)
        pp_list_1 = []
        color_name_1 = ["俯视", "侧视", "内里", "后跟", "鞋底"]
        color_name_2 = ["俯视", "鞋底"]

        color_name_1 = ["俯视", "侧视", "鞋底"]
        color_name_2 = ["俯视", "内里", "后跟"]
        n = 0
        pp_1_height = 100

        for index, goods_art_no in enumerate(goods_art_no_list):
            if index in [0, 2, 4, 6, 8]:
                color_name = color_name_1
            else:
                color_name = color_name_2

            for name in color_name:
                pp_1 = self.get_overlay_pic_from_dict(
                    goods_art_no=goods_art_no,
                    color_name=name,
                    bg_color=self.base_bg_color
                )

                if pp_1:
                    n += 1
                    if name != "后跟":
                        pp_1 = pp_1.resize(value=int(top_bg.width / 1.4))
                    else:
                        pp_1 = pp_1.resize(value=int(top_bg.width / 3))

                    if n == 1:
                        pp_1_height = pp_1.height

                    _height = pp_1.height if pp_1.height > pp_1_height else pp_1_height

                    pp_1 = pp_1.paste_img_invert(base="cc",
                                                 top_img=PictureProcessing("RGB",
                                                                           (int(top_bg.width / 1.4), _height + 10,),
                                                                           self.base_bg_color))

                    pp_1 = pp_1.paste_img_invert(base="cc",
                                                 top_img=PictureProcessing("RGB",
                                                                           (top_bg.width, _height + 100,),
                                                                           (255, 255, 255)))

                    pp_list_1.append(pp_1)

        if pp_list_1:
            pp_list_1.append(PictureProcessing("RGB", (top_bg.width, 100), bg_color))
            detailed_images.extend(pp_list_1)

        return PictureProcessing(im=self.add_pic(detailed_images))

    def generateTextBg(self, parent, position, font, font_size, text, color):
        return parent.add_text(
            mode="pixel",
            value=position,
            font=ImageFont.truetype(font, font_size),
            text=text,
            align="center",
            anchor="ma",
            spacing=10,
            fill=color,
        )

    def get_font_render_size(self, text, font, canvas_size=(2048, 2048)):
        canvas = Image.new('RGB', canvas_size)
        draw = ImageDraw.Draw(canvas)
        draw.text((0, 0), text, font=font, fill=(55, 55, 55))
        bbox = canvas.getbbox()
        # 宽高
        size = (bbox[2] - bbox[0], bbox[3] - bbox[1])
        return size


if __name__ == '__main__':
    import json

    with open(
            r"D:\MyDocuments\PythonCode\MyPython\red_dragonfly\deal_pics\auto_capture_V2\auto_photo\qt_test\data3.txt",
            "r", encoding="utf-8") as f:
        data = json.loads(f.read())

    for goods_no, value in data.items():
        d = DetailPicGetXiaoSuShuoXie3(goods_no, value,
                                       out_put_dir=r"D:\MyDocuments\PythonCode\MyPython\red_dragonfly\deal_pics\auto_capture_V2\auto_photo\output\2024-11-19\软件-详情图生成")
        raise 1
