# 微盛，企业管家 https://platform.wshoto.com
from lazysdk import lazyrequests
import copy


default_headers = {
        "Accept": "application/json, text/plain, */*",
        "Accept-Encoding": "gzip, deflate, zstd",
        "Accept-Language": "en-US,en;q=0.5",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
        "Host": "platform.wshoto.com",
        "Origin": "https://platform.wshoto.com",
        "Pragma": "no-cache",
        "Referer": "https://platform.wshoto.com/index/dashboard",
        "Sec-Fetch-Dest": "empty",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Site": "same-origin",
        "TE": "trailers",
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:139.0) Gecko/20100101 Firefox/139.0",
        "x-admin-header": "1",
        "x-clientType-header": "pc",
        "x-header-host": "platform.wshoto.com",
    }


def dashboard(
        authorization: str
):
    url = "https://platform.wshoto.com/bff/index/private/pc/dashboard?saMode=SECRET"
    headers = copy.deepcopy(default_headers)
    headers["Authorization"] = authorization
    return lazyrequests.lazy_requests(
        method="POST",
        url=url,
        headers=headers
    )


def material_package(
        authorization: str,
        search_package_name: str = ""
):
    """
    【内容中心】/【组合素材】/【配置素材合集】/查询
    :param authorization:
    :param search_package_name: 被查询的素材合集名称
    :return:
    """
    url = "https://platform.wshoto.com/bff/content/private/pc/material/package/packageQuery"
    headers = copy.deepcopy(default_headers)
    headers["Authorization"] = authorization
    data = {
        "pageSize": 1000,
        "pageIndex": 1,
        "searchPackageName": search_package_name,
        "isManager": 1,
        "isContainsNoUse": True,
        "isContainsStop": True,
        "businessType": 14,
        "isShowRecommend": True,
        "isScope": False
    }
    return lazyrequests.lazy_requests(
        method="POST",
        url=url,
        headers=headers,
        json=data
    )


def create_material_package(
        authorization: str,
        name: str
):
    """
    【内容中心】/【组合素材】/【配置素材合集】/【+添加素材合集】
    :param authorization:
    :param name: 素材合集名称
    :return: {"code":"00000","msg":"OK","data":{"id":"2000222213115036674"}}
    """
    url = "https://platform.wshoto.com/bff/content/private/pc/materialCategory/create"
    headers = copy.deepcopy(default_headers)
    headers["Authorization"] = authorization
    data = {
        "name": name,
        "businessType":14,
        "editStatus":0
    }
    return lazyrequests.lazy_requests(
        method="POST",
        url=url,
        headers=headers,
        json=data
    )


class WshotoCrawler:
    def __init__(
            self,
            authorization: str,
            headers: dict = None,
    ):
        if headers is None:
            headers = default_headers
        self.authorization = authorization
        self.headers = headers
        self.headers["Authorization"] = authorization

    def upload_file(
            self,
            file_path: str,
    ):
        """
        上传文件
        :param file_path: 文件路径
        :return:
        """
        url = "https://platform.wshoto.com/bff/content/private/pc/file/upload"
        headers = copy.deepcopy(self.headers)

        # 以二进制模式打开图片文件
        files = {'file': open(file_path, 'rb')}
        return lazyrequests.lazy_requests(
            method="POST",
            url=url,
            headers=headers,
            files=files
        )

    def material_create(
            self,
            business_type,
            category_id: str = "0",
            cover_image_url: str = None,
            is_package_child_temporary: bool = True,
            is_private: bool = None,
            title: str = None,

            operation: int = 1,

            summary: str = None,
            original_link: str = None,

            app_id: str = None,
            app_path: str = None,
            app_original_id: str = None,

            material_id_list:list = None,
            tag_id_list: list = None,
            visible_dept_ids: list = None,
            visible_user_ids: list = None,
            root_parent_id: str = None,

    ):
        """
        添加一条素材
        :param business_type: 8:小程序，9:网页，"14":创建组合素材
        :param category_id: 默认是0
        :param cover_image_url: 封面图（已上传的图片链接）
        :param is_package_child_temporary:
        :param is_private:
        :param title: 小程序标题/组合标题/网页标题

        :param operation:

        :param summary: 摘要（9）
        :param original_link: 外链网页（9）

        :param app_id:
        :param app_path:
        :param app_original_id:

        :param material_id_list: 所提交的素材的id列表
        :param tag_id_list:
        :param visible_dept_ids:
        :param visible_user_ids:
        :param root_parent_id: 素材合集id
        :return:
        """
        url = "https://platform.wshoto.com/bff/content/private/pc/material/create"
        headers = copy.deepcopy(self.headers)

        data = {
            "businessType": business_type,
            "categoryId": category_id,
            "title": title,  # 标题
        }
        if business_type == 8:
            data["contentApp"] = {
                    "appId": app_id,  # 小程序ID
                    "appPath": app_path,  # 小程序页面路径
                    "appOriginalId": app_original_id  # 小程序原始ID
                }
            if is_private is None:
                data["isPrivate"] = 1
            else:
                data["isPrivate"] = is_private
        elif business_type == 9:
            # 网页
            data["coverImageUrl"] = cover_image_url
            data["isPackageChildTemporary"] = is_package_child_temporary

            data["contentLink"] = {
                "originalLink": original_link
            }  # 推广链接？
            if is_private is None:
                data["isPrivate"] = True
            else:
                data["isPrivate"] = is_private
            data["operation"] = operation
            data["summary"] = summary  # 内容？
        elif str(business_type) == "14":
            data["contentPackage"] = {
                # "materialIdList": [],
                "tagIdList":[],
                "visibleDeptIds":[],
                "visibleUserIds":[]
            }
            if material_id_list:
                data["contentPackage"]["materialIdList"] = material_id_list
            if tag_id_list:
                data["contentPackage"]["tagIdList"] = tag_id_list
            if visible_dept_ids:
                data["contentPackage"]["visibleDeptIds"] = visible_dept_ids
            if visible_user_ids:
                data["contentPackage"]["visibleUserIds"] = visible_user_ids
            data["rootParentId"] = str(root_parent_id)
            data["extensionMap"] = {
                "riskLevel": "R1",
                "sceneSwitch": 1,
                "sendEnable": 1,
                "browseEnable": 1
            }
            data["publishStatus"] = 0
            data["startTime"] = ""
            data["endTime"] = ""

        return lazyrequests.lazy_requests(
            method="POST",
            url=url,
            headers=headers,
            json=data
        )
