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

import os
from PIL import ImageFont, Image, ImageDraw
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

import math


class DetailPicGetXiaoSuShuoXie2(DetailBase):
    need_view = ["俯视", "侧视", "后跟", "鞋底", "内里"]
    root = r"{}\resources\detail_temp\xiaosushuoxie\2".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\2".format(os.getcwd())
        self.base_bg_color = (235, 234, 234)
        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,
            self.deal_pic_6,
            self.deal_pic_7,
        ]
        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())
        detailed_images.append(self.deal_pic_6())
        detailed_images.append(self.deal_pic_7())
        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)

        font_1 = ImageFont.truetype(r"resources\ttf\puhui\Bold.ttf", 60)
        font_2 = ImageFont.truetype(r"resources\ttf\puhui\Bold.ttf", 35)
        # font_2 = ImageFont.truetype(r"resources\ttf\puhui\Light.ttf", 35)

        t1_title = self.get_text_value("标题")
        t1_sub_title = self.get_text_value("副标题")
        # t1_sub_title = "副标题副标题副标题副标题副标题\n副标题副标题副标题副标题\n副标题副标题副标题"
        base_bg_color = (236, 235, 235)
        if t1_title:
            t_title_pp = PictureProcessing("RGB", (1200, 500), base_bg_color)
            t_title_pp = t_title_pp.get_text_image_advanced(
                value=(50, 10),
                font=font_1,
                text=t1_title,
                align="left",
                spacing=10,
                fill=(17, 16, 16),
                return_mode="min_image_high",
                margins=(0, 0, 0, 0)
            )
            detailed_images.append(t_title_pp)
        if t1_sub_title:
            t_title_2_pp = PictureProcessing("RGB", (1200, 500), base_bg_color)
            t_title_2_pp = t_title_2_pp.get_text_image_advanced(
                value=(50, 10),
                font=font_2,
                text=t1_sub_title,
                align="left",
                spacing=10,
                fill=(32, 32, 32),
                return_mode="min_image_high",
                margins=(0, 0, 0, 0)
            )
            detailed_images.append(t_title_2_pp)

        # 添加分割线
        detailed_images.append(PictureProcessing("RGB",(pp_bg.width,150),self.base_bg_color))

        # ================添加图片
        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("RGB",(pp_bg.width,150),self.base_bg_color))
        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)

        font_1 = ImageFont.truetype(r"resources\ttf\puhui\Bold.ttf", 60)
        font_2 = ImageFont.truetype(r"resources\ttf\puhui\Light.ttf", 30)

        t1_title = self.get_text_value("提示1主标题")
        t1_sub_title = self.get_text_value("提示1副标题")
        if t1_title:
            t_title_pp = PictureProcessing("RGB", (1200, 500), (249, 249, 249))
            t_title_pp = t_title_pp.get_text_image_advanced(
                value=(1200 - 80, 45),
                font=font_1,
                text=t1_title,
                align="right",
                anchor="rs",
                spacing=10,
                fill=(17, 16, 16),
                return_mode="min_image_high",
                margins=(10, 10, 0, 0)
            )
            detailed_images.append(t_title_pp)
        if t1_sub_title:
            t_title_2_pp = PictureProcessing("RGB", (1200, 500), (249, 249, 249))
            t_title_2_pp = t_title_2_pp.get_text_image_advanced(
                value=(1200 - 80, 30),
                font=font_2,
                text=t1_sub_title,
                align="right",
                anchor="rs",
                spacing=10,
                fill=(55, 55, 55),
                return_mode="min_image_high",
                margins=(10, 10, 0, 0)
            )
            detailed_images.append(t_title_2_pp)

        # ----------主图放置
        goods_art_no_list = list(self.data.keys())
        # ---------------鞋底图
        bg_color = (249, 249, 249)
        pp_jpg = self.get_overlay_pic_from_dict(
            goods_art_no=goods_art_no_list[0],
            color_name="鞋底",
            bg_color=bg_color
        )
        pp_jpg = pp_jpg.paste_img_invert(top_img=PictureProcessing("RGB", (1200, pp_jpg.height + 100), bg_color),
                                         base="nc",
                                         value=(400, 00)
                                         )
        detailed_images.append(pp_jpg)
        return PictureProcessing(im=self.add_pic(detailed_images))

    def deal_pic_3(self):
        detailed_images = []
        pp_bg = PictureProcessing(r"{}\template_4.png".format(self.root))
        detailed_images.append(pp_bg)
        font_1 = ImageFont.truetype(r"resources\ttf\puhui\Bold.ttf", 60)
        font_2 = ImageFont.truetype(r"resources\ttf\puhui\Light.ttf", 30)

        t1_title = self.get_text_value("提示2主标题")
        t1_sub_title = self.get_text_value("提示2副标题")
        bg_color = (252, 252, 252)
        if t1_title:
            t_title_pp = PictureProcessing("RGB", (1200, 500), bg_color)
            t_title_pp = t_title_pp.get_text_image_advanced(
                value=(80, 45),
                font=font_1,
                text=t1_title,
                align="left",
                anchor=None,
                spacing=10,
                fill=(17, 16, 16),
                return_mode="min_image_high",
                margins=(10, 10, 0, 0)
            )
            detailed_images.append(t_title_pp)
        if t1_sub_title:
            t_title_2_pp = PictureProcessing("RGB", (1200, 500), bg_color)
            t_title_2_pp = t_title_2_pp.get_text_image_advanced(
                value=(80, 30),
                font=font_2,
                text=t1_sub_title,
                align="left",
                anchor=None,
                spacing=10,
                fill=(55, 55, 55),
                return_mode="min_image_high",
                margins=(10, 10, 0, 0)
            )
            detailed_images.append(t_title_2_pp)

        # ----------主图放置
        goods_art_no_list = list(self.data.keys())
        # ---------------鞋底图

        pp_jpg = self.get_overlay_pic_from_dict(
            goods_art_no=goods_art_no_list[0],
            color_name="侧视",
            bg_color=bg_color
        )
        pp_jpg = pp_jpg.resize(value=1686)
        pp_jpg = pp_jpg.paste_img_invert(top_img=PictureProcessing("RGB", (1200, pp_jpg.height), bg_color),
                                         base="ec",
                                         value=(0, 0)
                                         )
        # pp_jpg = pp_jpg.resize(value=1000)
        # pp_jpg = pp_jpg.paste_img_invert(top_img=PictureProcessing("RGB",(1200,pp_jpg.height+150),bg_color),
        #                                  base="wc",
        #                                  value=(0,0)
        #                                  )
        detailed_images.append(pp_jpg)

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

    def deal_pic_4(self):
        """各个颜色细节展示"""
        bg_color = (235, 235, 235)
        detailed_images = []
        pp_bg = PictureProcessing(r"{}\template_5.png".format(self.root))
        detailed_images.append(pp_bg)
        font_1 = ImageFont.truetype(r"resources\ttf\puhui\Bold.ttf", 60)
        font_2 = ImageFont.truetype(r"resources\ttf\puhui\Light.ttf", 30)

        t1_title = self.get_text_value("提示3主标题")
        t1_sub_title = self.get_text_value("提示3副标题")
        if t1_title:
            t_title_pp = PictureProcessing("RGB", (1200, 500), bg_color)
            t_title_pp = t_title_pp.get_text_image_advanced(
                value=(1200 - 80, 45),
                font=font_1,
                text=t1_title,
                align="right",
                anchor="rs",
                spacing=10,
                fill=(17, 16, 16),
                return_mode="min_image_high",
                margins=(10, 10, 0, 0)
            )
            detailed_images.append(t_title_pp)
        if t1_sub_title:
            t_title_2_pp = PictureProcessing("RGB", (1200, 500), bg_color)
            t_title_2_pp = t_title_2_pp.get_text_image_advanced(
                value=(1200 - 80, 30),
                font=font_2,
                text=t1_sub_title,
                align="right",
                anchor="rs",
                spacing=10,
                fill=(55, 55, 55),
                return_mode="min_image_high",
                margins=(10, 10, 0, 0)
            )
            detailed_images.append(t_title_2_pp)

        goods_art_no_list = list(self.data.keys())
        # ------侧视图-------------
        pp_2 = self.image_one_pic(
            goods_art_no=goods_art_no_list[0], name="侧视", bg_color=bg_color
        )
        pp_2 = pp_2.resize(mode="pixel", base="width", value=2327)
        pp_2 = PictureProcessing("RGBA", (200, 300), bg_color).paste_img(
            mode="pixel", top_img=pp_2, base="wc", value=(-900, 0)
        )

        # ------侧视-------------
        pp_3 = self.image_one_pic(
            goods_art_no=goods_art_no_list[0], name="侧视", bg_color=bg_color
        )
        pp_3 = pp_3.resize(mode="pixel", base="width", value=3000)
        pp_3 = PictureProcessing("RGBA", (200, 300), bg_color).paste_img(
            mode="pixel", top_img=pp_3, base="cc", value=(-500, 0)
        )
        # ---------------侧视图---------------旋转
        _, pp_4 = self.image_one_pic(
            goods_art_no=goods_art_no_list[0],
            name="侧视",
            bg_color=bg_color,
            return_orign=True,
        )
        pp_4 = pp_4.resize(mode="pixel", base="width", value=1163)
        pp_4_max = pp_4.width if pp_4.width > pp_4.height else pp_4.height
        past_y = 0
        top_img_bg = PictureProcessing("RGBA", (pp_bg.width, pp_2.height), bg_color)
        top_img_bg = top_img_bg.paste_img(
            mode="pixel", top_img=pp_2, base="wc", value=(50, past_y)
        )
        top_img_bg = top_img_bg.paste_img(
            mode="pixel", top_img=pp_3, base="wc", value=(267, past_y)
        )
        new_pp4_bg = PictureProcessing(
            "RGBA", (pp_4_max, pp_4_max + 100), (239, 239, 239, 0)
        )
        pp_4 = PictureProcessing("RGBA", (pp_4.width, pp_4.height), bg_color).paste_img(
            mode="pixel", top_img=pp_4, base="nw", value=(0, 0)
        )
        new_pp4_bg.paste_img(mode="pixel", top_img=pp_4, base="wc", value=(0, 0))
        new_pp4_bg = new_pp4_bg.rotate(30)
        pp4_im = new_pp4_bg.get_im()
        new_pp4_im = pp4_im.crop(pp4_im.getbbox())
        new_pp5_bg = PictureProcessing(
            "RGBA", (pp_bg.width, new_pp4_im.height - 200), bg_color
        )
        new_pp5_bg = new_pp5_bg.paste_img(
            mode="pixel", top_img=new_pp4_bg, base="cc", value=(-50, 0)
        )
        new_empty_bg = PictureProcessing("RGBA", (pp_bg.width, 50), bg_color)
        detailed_images.append(top_img_bg)
        detailed_images.append(new_pp5_bg)
        detailed_images.append(new_empty_bg)

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

    def deal_pic_5(self):
        bg_color = (255, 255, 255)
        detailed_images = []

        # =============文字=================
        font_1 = ImageFont.truetype(r"resources\ttf\puhui\en\Black.otf", 65)
        font_2 = ImageFont.truetype(r"resources\ttf\puhui\Medium.ttf", 65)
        t1_title = "INFORMATION"
        t1_sub_title = "产品信息"
        if t1_title:
            t_title_pp = PictureProcessing("RGB", (1200, 500), bg_color)
            t_title_pp = t_title_pp.get_text_image_advanced(
                value=(600, 45),
                font=font_1,
                text=t1_title,
                align="center",
                anchor="mm",
                spacing=10,
                fill=(16, 16, 16),
                return_mode="min_image_high",
                margins=(10, 10, 0, 0)
            )
            detailed_images.append(t_title_pp)
        if t1_sub_title:
            t_title_2_pp = PictureProcessing("RGB", (1200, 500), bg_color)
            t_title_2_pp = t_title_2_pp.get_text_image_advanced(
                value=(600, 30),
                font=font_2,
                text=t1_sub_title,
                align="center",
                anchor="mm",
                spacing=10,
                fill=(16, 16, 16),
                return_mode="min_image_high",
                margins=(10, 10, 0, 0)
            )
            detailed_images.append(t_title_2_pp)

        goods_art_no_list = list(self.data.keys())
        product_img = self.get_overlay_pic_from_dict(
            goods_art_no=goods_art_no_list[0],
            color_name="俯视",
            bg_color=bg_color
        )
        product_img = product_img.resize(value=1200 / 1.75)
        product_img = product_img.paste_img_invert(
            top_img=PictureProcessing("RGB", (1200, product_img.height), bg_color),
            base="cc",
        )

        text_font = ImageFont.truetype(r"resources\ttf\puhui\Regular.otf", 30)
        tips_font = ImageFont.truetype(r"resources\ttf\puhui\Medium.ttf", 30)
        h = 280 if product_img.height < 312 else 312
        paramsList = [("帮高", (140, product_img.height - h)), ("跟高", (1200 - 140, product_img.height - h)),
                      ("鞋宽", (1200 - 140, product_img.height - 87))]
        tipsList = [("帮高", (140, product_img.height - h - 30)), ("跟高", (1200 - 140, product_img.height - h - 30)),
                    ("鞋宽", (1200 - 140, product_img.height - 87 - 30))]

        for index,item in enumerate(paramsList):
            text ="{}".format(self.get_text_value(item[0]))
            if not text:
                continue

            product_img = product_img.add_text(
                mode="pixel",
                value=item[1],
                font=text_font,
                anchor="mm",
                text=text,
                align="center",
                spacing=10,
                fill=(143, 143, 143),
            )

            product_img = product_img.add_text(
                mode="pixel",
                value=tipsList[index][1],
                font=tips_font,
                anchor="mm",
                text="{}".format(tipsList[index][0]),
                align="center",
                spacing=15,
                fill=(143, 143, 143),
            )

        detailed_images.append(product_img)

        # ===========================================================================================================d
        pp_bg = PictureProcessing(r"{}\template_6.png".format(self.root))
        tableList = [
            ("鞋面材质", (300, 72)),
            ("内里材质", (760, 72)),
            ("鞋垫材质", (300, 72 + 105)),
            ("鞋底材质", (760, 72 + 105)),
        ]
        table_font = ImageFont.truetype(r"resources\ttf\puhui\Medium.ttf", 30)
        spacing = 15
        text_arrays = []
        for i, tableItem in enumerate(tableList):
            item_text = self.get_text_value(tableItem[0])
            if not item_text:
                continue
            text_arrays.append("{} : {}".format(tableItem[0], item_text))

        for index, item in enumerate(text_arrays):
            row = index // 2 + 1  # 计算行号（从1开始计数）
            col = (index % 2) + 1  # 计算列号（从1开始计数）
            if col == 1:
                c_x = 102
            else:
                c_x = 635
            if row == 1:
                c_y = 40
            else:
                c_y = 40 + 105
            pp_bg = pp_bg.add_text(
                mode="pixel",
                value=(c_x, c_y),
                font=table_font,
                text=item,
                align="left",
                spacing=spacing,
                fill=(80, 80, 80),
            )
        detailed_images.append(pp_bg)
        return PictureProcessing(im=self.add_pic(detailed_images))

    def searchNotEmptyItem(self, current_idx, tableList):
        idx = current_idx - 1
        if idx < 0:
            idx = 0
        value = self.get_text_value(tableList[idx][0])
        if idx == 0:
            return idx
        if value == "":
            return self.searchNotEmptyItem(idx, tableList)
        else:
            return idx + 1

    def deal_pic_6(self):
        bg_color = (255, 255, 255)
        detailed_images = []
        pp_bg = PictureProcessing(r"{}\template_7.png".format(self.root))
        detailed_images.append(pp_bg)

        # ==========添加颜色===================
        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=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), bg_color)
            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), bg_color)
            _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)

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

    def get_font_render_size(self, text, font):
        canvas = Image.new("RGB", (2048, 2048))
        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

    def deal_pic_7(self):
        detailed_images = []

        bg_color = (255, 255, 255)
        goods_art_no_list = list(self.data.keys())
        pp_bg = PictureProcessing(r"{}\template_8.png".format(self.root))
        detailed_images.append(pp_bg)

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

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

        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_jpg = self.get_overlay_pic_from_dict(
                    goods_art_no=goods_art_no,
                    color_name=name,
                    bg_color=bg_color
                )
                if pp_jpg:
                    if name != "后跟":
                        pp_jpg = pp_jpg.resize(value=int(pp_bg.width / 1.2))
                    else:
                        pp_jpg = pp_jpg.resize(value=int(pp_bg.width / 2.2))

                    pp_jpg = pp_jpg.paste_img_invert(
                        top_img=PictureProcessing("RGB", (pp_bg.width, pp_jpg.height + 30), bg_color),
                        base="cc")
                    detailed_images.append(pp_jpg)
                    detailed_images.append(PictureProcessing("RGB", (pp_bg.width, 220), bg_color))

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


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 = DetailPicGetXiaoSuShuoXie2(
            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
