import os
import json
import random
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


def get_video_detail(vid, userad, cate):
    time.sleep(random.randint(5, 25))
    url = "https://gkvxwq2023.we-media.cn/app/index.php"
    payload = {
        "i": "1",
        "t": "0",
        "m": "jyt_txvideo",
        "v": "1.0.0",
        "from": "wxapp",
        "c": "entry",
        "a": "wxapp",
        "do": "videodetail",
        "vid": vid,
        "userad": userad,
        "cate": cate,
    }
    headers = {
        "Host": "gkvxwq2023.we-media.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.5(0x13080510)XWEB/1100",
        "content-type": "application/x-www-form-urlencoded",
        "accept": "*/*",
        "referer": "https://servicewechat.com/wx49f06df06becc7fa/2/page-frame.html",
        "accept-language": "en-US,en;q=0.9",
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    return response.json()


class SongZhuFuRecommend(object):
    def __init__(self, platform, mode, rule_dict, user_list, env):
        self.platform = platform
        self.mode = mode
        self.rule_dict = rule_dict
        self.user_list = user_list
        self.env = env
        self.download_cnt = 0
        self.limit_flag = False

    def get_video_list(self):
        """
        推荐流并没有页数，每次请求数据不同，设置每天的抓取视频数量为100-200条
        """
        base_url = "https://gkvxwq2023.we-media.cn/app/index.php"
        headers = {
            "Host": "gkvxwq2023.we-media.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.5(0x13080510)XWEB/1100",
            "content-type": "application/x-www-form-urlencoded",
            "accept": "*/*",
            "referer": "https://servicewechat.com/wx49f06df06becc7fa/2/page-frame.html",
            "accept-language": "en-US,en;q=0.9",
        }
        params = {
            "i": "1",
            "t": "0",
            "m": "jyt_txvideo",
            "v": "1.0.0",
            "from": "wxapp",
            "c": "entry",
            "a": "wxapp",
            "do": "videotui",
            "city": "",
            "category": "494",
        }
        while True:
            time.sleep(random.randint(1, 10))
            try:
                if self.limit_flag:
                    message="本轮已经抓取到足够的数据，自动退出\t{}".format(self.download_cnt)
                    print(message)
                    return
                else:
                    response = requests.get(
                        url=base_url,
                        headers=headers,
                        params=params,
                        proxies=tunnel_proxies(),
                    )
                    video_list = response.json()['data']
                    if video_list:
                        for index, video_obj in enumerate(video_list, 1):
                            try:
                                print("扫描到一条视频")
                                self.process_video_obj(video_obj)
                            except Exception as e:
                                print("抓取第{}条的时候出现问题， 报错信息是{}".format(index, e))
                    else:
                        print("已经抓完了，自动退出")
                        return
            except Exception as e:
                print("抓取推荐页的时候出现错误， 报错信息是{}".format(e))

    def process_video_obj(self, video_obj):
        trace_id = self.platform + str(uuid.uuid1())
        our_user = random.choice(self.user_list)
        item = VideoItem()
        item.add_video_info("user_id", our_user["uid"])
        item.add_video_info("user_name", our_user["nick_name"])
        item.add_video_info("video_id", video_obj["id"])
        item.add_video_info("video_title", video_obj["vtitle"])
        item.add_video_info("publish_time_stamp", int(video_obj['create_time']))
        vid = video_obj['vid']
        userad = ""
        cate = video_obj['category']
        detail_obj = get_video_detail(vid=vid, userad=userad, cate=cate)['data']
        item.add_video_info("video_url", detail_obj['vid'])
        item.add_video_info("cover_url", detail_obj["poster"])
        item.add_video_info("duration", detail_obj['vtime'])
        item.add_video_info("play_cnt", detail_obj['realview'])
        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())))
        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():
            self.download_cnt += 1
            # self.mq.send_msg(mq_obj)
            print(mq_obj)
            print("成功发送至 ETL")
            if self.download_cnt >= int(
                self.rule_dict.get("videos_cnt", {}).get("min", 200)
            ):
                self.limit_flag = True


if __name__ == '__main__':
    S = SongZhuFuRecommend(
        platform="meitiansongzhufu",
        mode="recommend",
        env="dev",
        rule_dict={},
        user_list=[{'nick_name': "Ivring", 'uid': "1997"}, {'nick_name': "paul", 'uid': "1998"}]
    )
    S.get_video_list()