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 PiaoQuanPipeline, AliyunLogger, tunnel_proxies
from common.mq import MQ


class MHXHspcheduling(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.mq = MQ(topic_name="topic_crawler_etl_" + self.env)
        self.limit_flag = False

    def video_list(self, video_id):
        url = "https://app.miguoyun.cn/app/index.php?i=959&t=0&m=jyt_txvideo&v=31.1.11&from=wxapp&c=entry&a=wxapp&do=videoinfo&vid={}&version=1.0.3".format(
            video_id)
        headers = {
            'Host': 'app.miguoyun.cn',
            'accept': '*/*',
            'content-type': 'application/x-www-form-urlencoded',
            'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E217 MicroMessenger/6.8.0(0x16080000) NetType/WIFI Language/en Branch/Br_trunk MiniProgramEnv/Mac',
            'referer': 'https://servicewechat.com/wx08c7ede18f448973/20/page-frame.html',
            'accept-language': 'zh-cn',
            'Cookie': '0a52___multiid=1; 0a52_logout=; PHPSESSID=d7eaef273b29b6e2a2b0130b0bfb92bc'
        }

        response = requests.post(url, headers=headers)
        data_list = response.json()["data"]
        return data_list

    def get_video_list(self):
        url = "https://app.miguoyun.cn/app/index.php?i=959&t=1&m=jyt_txvideo&v=31.1.11&from=wxapp&c=entry&a=wxapp&do=videolist&sign=bf3a8068467ce73c96a0409ae1136c4f"
        headers = {
            'Host': 'app.miguoyun.cn',
            'accept': '*/*',
            'content-type': 'application/x-www-form-urlencoded',
            'accept-language': 'zh-cn',
            'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E217 MicroMessenger/6.8.0(0x16080000) NetType/WIFI Language/en Branch/Br_trunk MiniProgramEnv/Mac',
            'referer': 'https://servicewechat.com/wx08c7ede18f448973/20/page-frame.html',
            'Cookie': '0a52___multiid=1; 0a52_logout=; PHPSESSID=d7eaef273b29b6e2a2b0130b0bfb92bc'
        }
        page_index = 1
        while True:
            time.sleep(random.randint(1, 10))
            try:
                if self.limit_flag:
                    AliyunLogger.logging(
                        code="2000",
                        platform=self.platform,
                        mode=self.mode,
                        env=self.env,
                        message="本轮已经抓取到足够的数据，自动退出\t{}".format(self.download_cnt),
                    )
                    return
                else:
                    payload = "category=476&page=1&israndom=1&type=0&isview=&noauth=true"

                    response = requests.post(url, headers=headers, data=payload)
                    video_list = response.json()["data"]
                    if video_list:
                        for index, video_obj in enumerate(video_list, 1):
                            try:
                                video_id = video_obj.get("vid", 0)
                                get_video_list = self.video_list(video_id)

                                if get_video_list.get("vtitle"):
                                    AliyunLogger.logging(
                                        code="1001",
                                        platform=self.platform,
                                        mode=self.mode,
                                        env=self.env,
                                        message="扫描到一条视频",
                                        data=video_obj,
                                    )
                                    self.process_video_obj(video_obj, get_video_list)
                            except Exception as e:
                                AliyunLogger.logging(
                                    code="3000",
                                    platform=self.platform,
                                    mode=self.mode,
                                    env=self.env,
                                    data=video_obj,
                                    message="抓取第{}条的时候出现问题， 报错信息是{}".format(index, e),
                                )
                            page_index += 1
                    else:
                        AliyunLogger.logging(
                            code="2000",
                            platform=self.platform,
                            mode=self.mode,
                            env=self.env,
                            message="已经抓完了，自动退出"
                        )
                        return
            except Exception as e:
                AliyunLogger.logging(
                    code="3000",
                    platform=self.platform,
                    mode=self.mode,
                    env=self.env,
                    message="抓取第{}页时候出现错误， 报错信息是{}".format(page_index + 1, e),
                )

    def process_video_obj(self, video_obj, get_video_list):
        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["vid"])
        item.add_video_info("video_title", video_obj["vtitle"])
        item.add_video_info("publish_time_stamp", int(time.time()))
        item.add_video_info("video_url", get_video_list["res"])
        item.add_video_info("cover_url", video_obj["poster"])
        item.add_video_info("out_video_id", video_obj["vid"])
        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 = PiaoQuanPipeline(
            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)
            AliyunLogger.logging(
                code="1002",
                platform=self.platform,
                mode=self.mode,
                env=self.env,
                message="成功发送至 ETL",
                data=mq_obj,
            )
            if self.download_cnt >= int(
                self.rule_dict.get("videos_cnt", {}).get("min", 200)
            ):
                self.limit_flag = True


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