import json
import os
import settings
import shutil


def get_all_dir_info(image_dir):
    # 遍历货号获取所有货号--可能为编号
    folder_name_list = []
    for folder_name in os.listdir(image_dir):
        _path = "{}/{}".format(image_dir, folder_name)
        if not os.path.isdir(_path):
            continue
        if "无法对应" in folder_name:
            continue
        if "软件" in folder_name:
            if len(os.listdir(_path)) == 0:
                # 删除空文件夹
                os.rmdir(_path)
            continue
        folder_name_list.append(folder_name)

    return folder_name_list


def get_all_detail_info(image_dir):
    # 遍历货号获取所有货号--可能为编号
    _list = []
    for goods_no in os.listdir(image_dir):
        goods_art_no_path = "{}/{}".format(image_dir, goods_no)
        if not os.path.isdir(goods_art_no_path):
            continue
        _list.append(goods_no)
    return _list


def get_all_dir_info_and_pic_info(root_path, folder_name_list, need_view_list):
    # 遍历货号获取所有货号--可能为编号
    """
    数据返回为每个文件夹下的文件结构
    """

    return_data = {}
    for one_folder in folder_name_list:
        source_material_path = "{}/{}/阴影图处理".format(root_path, one_folder)
        data = {"pics": {},
                "message": "",
                "800x800": []
                }

        # source_material_path ===================
        if not os.path.exists(source_material_path):
            data["message"] = "缺失 阴影图处理 文件夹"
        else:
            if len(os.listdir(source_material_path)) % 2 != 0:
                data["message"] = "缺失 阴影图处理 图片不为2的倍数"
            else:
                # 遍历图片
                _pic_name_list = []
                for pic in os.listdir(source_material_path):
                    _pic = pic.replace(".png", "")
                    _pic = _pic.split("_")
                    if len(_pic) == 3:
                        # 示例：侧视-阴影
                        data["pics"]["{}-{}".format(_pic[1], _pic[2])] = "{}/{}".format(source_material_path, pic)
                        _pic_name_list.append(_pic[1])

                # 检查图片是否都有
                _ = [x for x in need_view_list if x not in _pic_name_list]
                if _:
                    _ = ",".join(_)
                    data["message"] += "\图片{}视角缺失".format(_)

        # 放入商品货号主图 ===================
        goods_art_800_pic_f = "{}/{}/800x800".format(root_path, one_folder)
        if not os.path.exists(goods_art_800_pic_f):
            data["message"] += "\缺失主图文件夹"
        else:
            if len(os.listdir(goods_art_800_pic_f)) == 0:
                data["message"] += "\缺失主图"
            else:
                for goods_art_pic in os.listdir(goods_art_800_pic_f):
                    # 过滤非图片信息
                    if "jpg" in goods_art_pic or "JPG" in goods_art_pic or "png" in goods_art_pic or "PNG" in goods_art_pic:
                        data["800x800"].append("{}/{}".format(goods_art_800_pic_f, goods_art_pic))

        # =======================
        return_data[one_folder] = data
    print("检查没有问题的文件夹-----------return_data")
    print(json.dumps(return_data))

    return return_data


def merge_local_and_remote_data(all_dir_info_data: dict, remote_data):
    """
    all_dir_info_data:文件夹基础数据；文件夹结构数据
    remote_data：远程数据
    """
    print("---all_dir_info_data:")
    print(json.dumps(all_dir_info_data))

    print("---remote_data:")
    print(json.dumps(remote_data))

    error_folder_name_list = []
    for folder_name, value in all_dir_info_data.items():
        if folder_name not in remote_data:
            value["message"] = "文件夹没有对应数据信息"
            error_folder_name_list.append(folder_name)
        else:
            value["remote_data"] = remote_data[folder_name]

    # =======开始组装数据

    # 组装数据，按款号进行组装数据
    goods_no_dict = {}
    for folder_name, value in all_dir_info_data.items():
        if "remote_data" not in value:
            continue
        if "data" not in value["remote_data"]:
            continue

        _remote_data = value["remote_data"]["data"]
        goods_no = _remote_data["款号"]
        if goods_no not in goods_no_dict:
            goods_no_dict[goods_no] = {}
            goods_no_dict[goods_no]["款号"] = goods_no
            goods_no_dict[goods_no]["货号资料"] = []

        _goods_number = _remote_data["编号"] if "编号" in _remote_data else ""
        if _goods_number:
            _goods_number = "NUM{}".format(_goods_number)
        else:
            _goods_number = ""

        goods_no_dict[goods_no]["货号资料"].append({"货号": _remote_data["商品货号"],
                                                "文件夹名称": folder_name,
                                                "编号": _goods_number,
                                                "颜色名称": _remote_data["颜色名称"] if "颜色名称" in _remote_data else "",
                                                "pics": value["pics"],
                                                "800x800": value["800x800"],
                                                })

        # 添加款号的基础信息，进行去重处理，此处为动态字段
        key = ["款号", "商品货号", "编号", "颜色名称", ]
        for _k, _v in _remote_data.items():
            if _k not in key:
                if _k not in goods_no_dict[goods_no]:
                    goods_no_dict[goods_no][_k] = ""
                if not goods_no_dict[goods_no][_k]:
                    if _v:
                        goods_no_dict[goods_no][_k] = _v

    # ======如果为红蜻蜓，则key需要更改为编号=========
    # 改款号信息  取任意一个商品的编号作为款号，格式为KNUM00001
    if settings.PROJECT == "红蜻蜓":
        _goods_no_dict = {}
        for key, value in goods_no_dict.items():
            number = "K{}".format(value["货号资料"][0]["编号"])
            _goods_no_dict[number] = value
    else:
        _goods_no_dict = goods_no_dict

    return _goods_no_dict, error_folder_name_list


def move_folders(path_list, target_folder):
    create_folder(target_folder)
    for source_folder in path_list:
        shutil.move(source_folder, target_folder)


def create_folder(path):
    if not os.path.exists(path):
        os.makedirs(path)
