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


class DetailPicGetHqt(DetailBase):
    need_view = ["俯视","侧视","后跟","鞋底","内里"]
    root = r"{}\resources\detail_temp\hongqingting\1".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,**kwargs):
        super().__init__(goods_no, goods_no_value, out_put_dir,windows=windows)
        self.root = r"{}\resources\detail_temp\hongqingting\1".format(os.getcwd())
        self.run()

    def run(self):
        detailed_images = self.deal_details()

        self.create_folder(self.out_put_dir)
        detail_path = "{out_put_dir}/{goods_no}/details".format(out_put_dir=self.out_put_dir, goods_no=self.goods_no)
        self.create_folder(detail_path)
        join_path = "{out_put_dir}/{goods_no}/拼接图".format(out_put_dir=self.out_put_dir, goods_no=self.goods_no)
        self.create_folder(join_path)

        for index, pp in enumerate(detailed_images):
            pp.im.save("{}/{}（{}）.jpg".format(detail_path, self.goods_no, str(index + 11).zfill(2)), format="JPEG")

        img = self.add_pic(detailed_images)
        img.save("{}/1.jpg".format(join_path), format="JPEG")

        # ------------移动其他图片---------------------
        self.move_other_pic()
        return True

    def deal_details(self):
        bg_color = (246, 246, 246)
        self.image_init(bg_color)
        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())
        return [x for x in detailed_images if x]

    def deal_pic_1(self):
        bg_color = (246, 246, 246)
        """   制作主图  """
        goods_art_no_list = list(self.data.keys())

        pp_1 = self.data[goods_art_no_list[0]]["pic_is_deal"]["侧视"]
        pp_image = pp_1.resize(mode="relative",
                               base="by_im",
                               value=0,
                               base_im=PictureProcessing("RGB", (550, 340), (248, 248, 248)),
                               percentage=0)

        pp_image = PictureProcessing("RGB", (550, 340), bg_color).paste_img(
            mode="pixel", top_img=pp_image, base="center"
        )

        bg_img = PictureProcessing(r"{}\image (1).jpg".format(self.root)).paste_img(
            mode="pixel", top_img=pp_image, base="nw", value=(26, 263))
        # bg_img.show()

        #   ---------- 第二张图粘贴
        pp_2 = self.data[goods_art_no_list[0]]["pic_is_deal"]["俯视"]
        pp_image = pp_2.resize(mode="relative",
                               base="by_im",
                               value=0,
                               base_im=PictureProcessing("RGB", (550, 340), (248, 248, 248)),
                               percentage=0)
        pp_image = PictureProcessing("RGB", (550, 340), bg_color).paste_img(
            mode="pixel", top_img=pp_image, base="center"
        )
        bg_img = bg_img.paste_img(
            mode="pixel", top_img=pp_image, base="nw", value=(26, 626))

        # -------粘贴文字-------
        font = ImageFont.truetype(r'resources\ttf\simhei.ttf', 30)
        text_list = [("商品款号", self.goods_no_value["款号"], 700, 297),
                     ("商品面料", self.goods_no_value["商品面料"], 700, 380),
                     ("商品内里", self.goods_no_value["商品内里"], 700, 469),
                     ("商品鞋底", self.goods_no_value["商品鞋底"], 700, 549),
                     ("后帮高", self.goods_no_value["后帮高"], 700, 667),
                     ("前掌宽", self.goods_no_value["前掌宽"], 700, 751),
                     ("鞋跟高", self.goods_no_value["鞋跟高"], 700, 828), ]
        for i in text_list:
            bg_img = bg_img.add_text(mode="pixel",
                                     value=(i[2], i[3]),
                                     font=font,
                                     text="{}:{}".format(i[0], i[1]),
                                     align="center",
                                     spacing=10,
                                     fill=(17, 16, 16))
        return bg_img

    def deal_pic_2(self):
        # 设计师说展示图
        # 设计师说
        if "FAB说明" not in self.goods_no_value:
            return
        text = self.goods_no_value["FAB说明"]  # FAB说明
        if not text:
            return
        pp_1 = PictureProcessing(r"{}\image (2).jpg".format(self.root))

        text = text.replace(r"\n", "\n")
        _ = text.split("\n")
        text_img = PictureProcessing("RGB", (1200, len(_) * 100 + 30), (255, 255, 255))
        font = ImageFont.truetype(r'resources\ttf\simhei.ttf', 30)

        text_img = text_img.add_text(mode="pixel",
                                     value=(600, 50),
                                     font=font,
                                     text=text,
                                     anchor="ma",
                                     align="center",
                                     spacing=50,
                                     fill=(83, 83, 83))
        new_image = PictureProcessing("RGB", (1200, pp_1.height + text_img.height), (255, 255, 255))
        new_image = new_image.paste_img(mode="pixel", top_img=pp_1, value=(0, 0))
        new_image = new_image.paste_img(mode="pixel", top_img=text_img, value=(0, pp_1.height))
        return new_image

    def deal_pic_3(self):
        # 制作角度展示图
        bg_color = (246, 246, 246)
        detailed_images = []
        pp_1 = PictureProcessing(r"{}\image (3).jpg".format(self.root))
        detailed_images.append(pp_1)
        goods_art_no_list = list(self.data.keys())
        for index, goods_art_no in enumerate(goods_art_no_list):
            if index == 0:
                name_list = ["侧视", "俯视", "后跟", "鞋底"]
            else:
                name_list = ["侧视", "俯视", ]

            for _name in name_list:
                # 处理图片，需要粘贴到背景等处理
                if _name not in self.data[goods_art_no]["pic_is_deal"]:
                    continue

                _pp = self.data[goods_art_no]["pic_is_deal"][_name]
                _pp = _pp.resize(mode="pixel", base="width", value=649 if _name == "后跟" else 1058, )
                bg_img = PictureProcessing("RGBA", (1200, int(_pp.height + 50)), bg_color)
                bg_img = bg_img.paste_img(mode="pixel", top_img=_pp, base="center")

                detailed_images.append(bg_img)
                # 添加分割线
                detailed_images.append(PictureProcessing("RGB", (1200, 50), (255, 255, 255)))

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

    def deal_pic_4(self):
        # 制作详细图
        bg_color = (246, 246, 246)
        detailed_images = []
        pp_1 = PictureProcessing(r"{}\image (4).jpg".format(self.root))
        detailed_images.append(pp_1)
        name_list = ["俯视", "内里", "后跟", "鞋底"]
        goods_art_no = list(self.data.keys())[0]

        view_dict = {"俯视": (0, 0, 1100, 1200),
                     "内里": (-1, -100, 1100, 1200),
                     "后跟": (0, -100, 1100, 1200),
                     "鞋底": (0, -100, 1100, 1200),
                     }

        for _name in name_list:
            # 处理图片，需要粘贴到背景等处理
            if _name not in self.data[goods_art_no]["pic_is_deal"]:
                continue
            _pp = self.data[goods_art_no]["pic_is_deal"][_name]
            _pp = _pp.resize(mode="pixel", base="width", value=1300 if _name == "后跟" else 2200, )
            _pp = _pp.crop_img(mode="pixel", base="sw", value=view_dict[_name], color_fill=bg_color)
            _pp = _pp.radius(mode="relative", circular_pos=(1, 0, 0, 1), value=100)
            bg_pp = PictureProcessing("RGB", (1200, 1316), (255, 255, 255))
            bg_pp.paste_img(mode="pixel", top_img=_pp, base="ec", value=(0, 0))
            detailed_images.append(bg_pp)

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

    def deal_pic_5(self):
        # 其他图片添加
        pp_1 = PictureProcessing(r"{}\image (5).jpg".format(self.root))
        return pp_1


if __name__ == '__main__':
    import json

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

    for goods_no, value in data.items():
        d = DetailPicGetHqt(goods_no, value, out_put_dir=r"D:\MyDocuments\PythonCode\MyPython\red_dragonfly\deal_pics\auto_capture_V2\auto_photo\out_put\测试文件夹\详情图生成")
        raise 1
