import os
import json
import sys
import time
import uuid

import requests

sys.path.append(os.getcwd())
from common.video_item import VideoItem
from common import tunnel_proxies
from common.pipeline import PiaoQuanPipelineTest
from common.mq import MQ
from zhuwanwufusu.crypt import AESCipher as AES


class ZhuWanWuFuSuRecommend(object):
    def __init__(self, platform, mode, rule_dict, user_dict, env):
        self.platform = platform
        self.mode = mode
        self.rule_dict = rule_dict
        self.user_dict = user_dict
        self.env = env
        self.download_cnt = 0
        self.mq = MQ(topic_name="topic_crawler_etl_" + self.env)
        self.expire_flag = False
        self.cryptor = AES()

    def get_recommend_list(self):
        url = "https://api.lidongze.cn/jeecg-boot/ugc/getVideoListsEn2"
        headers = {
            'Host': 'api.lidongze.cn',
            'xweb_xhr': '1',
            'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/6.8.0(0x16080000) NetType/WIFI MiniProgramEnv/Mac MacWechat/WMPF MacWechat/3.8.4(0x13080410)XWEB/31009',
            'token': '',
            'content-type': 'application/json',
            'accept': '*/*',
            'referer': 'https://servicewechat.com/wx0afdc2669ed8df2f/3/page-frame.html',
            'accept-language': 'en-US,en;q=0.9'
        }
        page_index = 1
        total_page = 2
        while page_index <= total_page:
            query = {
                "pageNo": page_index,
                "pageSize": 10,
                "groupId": "1650323161797439489",  # 推荐流的 ID
                "vn": 1,
                "gx": 1,
                "appid": "wx0afdc2669ed8df2f",
                "type": 0
            }
            params = {
                "v": self.cryptor.aes_encrypt(data=json.dumps(query))
            }
            response = requests.request("GET", url, headers=headers, params=params, proxies=tunnel_proxies())
            result = json.loads(self.cryptor.aes_decrypt(response.text))
            total_page = result['list']['pages']
            page_index = result['list']['current'] + 1
            for index, video_obj in enumerate(result['list']['records']):
                self.process_video_obj(video_obj)

    def process_video_obj(self, video_obj):
        trace_id = self.platform + str(uuid.uuid1())
        play_cnt = int(video_obj['playnum'].replace("万+", "0000")) if "万+" in video_obj['playnum'] else int(
            video_obj['playnum'])
        item = VideoItem()
        item.add_video_info("video_id", video_obj['id'])
        item.add_video_info("video_title", video_obj['vname'])
        item.add_video_info("play_cnt", play_cnt)
        item.add_video_info("publish_time_stamp", int(time.time()))
        item.add_video_info("out_user_id", video_obj['authid'])
        item.add_video_info("cover_url", video_obj['shareimg'])
        item.add_video_info("like_cnt", int(video_obj['likenum']))
        item.add_video_info("video_url", video_obj['videoaddr'])
        item.add_video_info("out_video_id", video_obj['id'])
        item.add_video_info("platform", self.platform)
        item.add_video_info("strategy", self.mode)
        item.add_video_info("session", "{}-{}".format(self.platform, int(time.time())))
        item.add_video_info("user_id", self.user_dict['uid'])
        item.add_video_info("user_name", self.user_dict['nick_name'])

        mq_obj = item.produce_item()
        pipeline = PiaoQuanPipelineTest(
            platform=self.platform,
            mode=self.mode,
            rule_dict=self.rule_dict,
            env=self.env,
            item=mq_obj,
            trace_id=trace_id,
        )
        if pipeline.process_item():
            print(json.dumps(mq_obj, ensure_ascii=False, indent=4))
            self.download_cnt += 1
            print(self.download_cnt)


if __name__ == '__main__':
    Z = ZhuWanWuFuSuRecommend(
        platform="zhuwanwufusu",
        mode="recommend",
        rule_dict={},
        user_dict={"uid": 123456, "nick_name": "luojunhuishuaige"},
        env="prod"
    )
    Z.get_recommend_list()
