import json
import random
import time
from urllib import parse

import requests


def operator_poc(account, passwd):
    """
    模拟登录
    """
    # 定义请求地址
    login_url = "https://t.livepocket.jp/api/sessions/create?mytimestamp=" + str(int(time.time()))

    # 定义请求header
    headers = {'Content-Type': 'application/x-www-form-urlencoded;',
               'Referer': 'https://t.livepocket.jp/login?acroot=header-new_p_u_nl',
               'Sec-Ch-Ua': 'Chromium',
               'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
               }

    # 通过字典方式定义请求body
    form_data = {"login": account,
                 "password": passwd,
                 "auto_login": "on",
                 "login_password": f"{account}&{passwd}"
                 }

    data = parse.urlencode(form_data)

    # 代理IP池
    proxy_list = [
        '185.199.228.220:7300',
    ]

    # 随机从ip池中选出一个ip
    proxy = random.choice(proxy_list)
    # 打印出随机选择的代理ip
    print(proxy)
    proxies = {
        'http': 'http://' + proxy,
        'https': 'https://' + proxy,
    }

    session = requests.session()
    content = session.post(url=login_url, headers=headers, data=data).text
    cookie = session.cookies
    response_cookie = cookie.get_dict()
    login_resp = json.loads(content)
    print(f"token: {login_resp['result']['token']}, response_cookie:{response_cookie}")
    # print(login_resp)
    token = login_resp['result']['token']

    event_id = 0
    # 跳转到抢券
    target_url = 'https://t.livepocket.jp/e/4gbm0'
    response = requests.get(target_url)
    if response.status_code == 200:
        html_string = response.content.decode('utf8')
        # print(f'{html_string}')
        start_index = html_string.find('https://t.livepocket.jp/purchase/verify?event_id=')
        if start_index != -1:
            end_index = html_string.find("'", start_index)
            if end_index != -1:
                event_id = html_string[start_index + len('https://t.livepocket.jp/purchase/verify?event_id='):end_index]
                print(f'event_id: {event_id}')
            else:
                print('End index not found.')
        else:
            print('Substring not found.')
    else:
        print('Failed to fetch the page. Status code:', response.status_code)



    # 预购
    prepare_url = 'https://t.livepocket.jp/purchase?type=new'



    # reserved_session_id 6位随机整数
    buy_url = 'https://t.livepocket.jp/api/tickets/purchase?mytimestamp=' + str(int(time.time()))

    reserved_session_id = random.randint(100000, 600000)
    ci_session = json.dumps(session.cookies.get_dict())
    print(ci_session)
    common_cookies = {"ci_session": ci_session}
    # 通过字典方式定义请求body
    form_buy = {"utoken": token,
                "onetime_token_name": 'buy_ticket',
                "onetime_token_value": "GZhM2MyODg2OTYwMmRlMmM3NjNjOWYxMDExMG",
                "url": "https://t.livepocket.jp/purchase/confirm?id=" + str(event_id) + f"&reserved_session_id={reserved_session_id}",
                "reserved_session_id": reserved_session_id,
                "event_id": str(event_id),
                "payment_type": "credit",
                "payment_method": 0,
                # "enquete[q_id]": 44196,
                # "enquete[99063_]": 327196
                }

    data = parse.urlencode(form_buy)

    buy_session = requests.session()
    buy_content = buy_session.post(url=buy_url, headers=headers, data=data, cookies=common_cookies).text
    print(buy_content)
    response_content = json.loads(buy_content)
    print(f"buy_content:{response_content['errmsg']}")


# 返回一个随机的请求头 headers
def get_headers():
    user_agent_list = [
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1"
        "Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6",
        "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6",
        "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1",
        "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5",
        "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
        "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
        "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
        "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
        "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
        "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3",
        "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
        "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24"
    ]
    UserAgent = random.choice(user_agent_list)
    headers = {'User-Agent': UserAgent}

    return headers


if __name__ == '__main__':
    operator_poc("no2es@huatcn.com", "panyue666")
