import time
from urllib import parse

import requests


def query_event(account, passwd, target_url):
    """
    模拟登录
    """
    # 定义请求地址
    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)
    session = requests.session()
    content = session.post(url=login_url, headers=headers, data=data, proxies=None).text
    cookie = session.cookies
    response_cookie = cookie.get_dict()
    # login_resp = json.loads(content)
    # token = login_resp['result']['token']
    # print('response cookie: ', response_cookie)
    print('response_cookie: ', response_cookie)

    # 跳转到抢券
    login_session = response_cookie['ci_session']
    event_id = 0
    php_session = response_cookie['PHPSESSID']

    response = requests.get(target_url)
    if response.status_code == 200:
        html_string = response.content.decode('utf8')
        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)

    return event_id, login_session, php_session


def query_params_reserved_session_id(id, my_session, php_session_id, origin_url):
    reserved_url = f"https://t.livepocket.jp/purchase/security?id={id}&type=new"
    result = requests.Session()
    header = {
        'Host': 't.livepocket.jp',
        'DNT': '1',
        'Upgrade-Insecure-Requests': '1',
        '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',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,'
                  'application/signed-exchange;v=b3;q=0.7',
        'Sec-Fetch-Site': 'same-origin',
        'Sec-Fetch-Mode': 'navigate',
        'Sec-Fetch-User': '?1',
        'Referer': f'{origin_url}',
        'Sec-Fetch-Dest': 'document',
        'sec-ch-ua': '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"macOS"',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Accept-Encoding': 'gzip, deflate, br, zstd',
        'Cache-Control': 'max-age=0'
    }

    cookies = {
        'ci_session': f'{my_session}',
        'PHPSESSID': f'{php_session_id}',
        'list_count': '{"success":true,"result":{"myticket_count":{"count":"1"},"today_event":{"total_count":1,"data_list":[{"id":"310461","name":"【5月5日(日・祝)】アイビー×ケンティー　着こなしと香りの完全攻略ガイド（先着受付）","artist":"アイビー, ケンティー","event_pic_url":"https://t.livepocket.jp/image/ogDi7QnoXzcjytaA6A08BX0Sezyx5XvndoMMJZiSH3LxVO6uyKHGY7KdKX6DbaAC","loc_name":"ジェイアール名古屋タカシマヤ 7階 ローズパティオ","date_info":{"startname":"開演日時","endname":"終演日時","starttime":"2024-05-05 10:15:00","endtime":"2024-05-05 18:30:00"},"order_status":""}]},"unread_count":10},"submit":true}'.encode('utf-8').decode('latin1'),
        'display_init': '{"success":true,"result":{"purchased_tickets":{"total_count":0,"data_list":{"ticket_info":[]}},"lottery_tickets":{"total_count":0,"data_list":{"ticket_info":[]}},"order_limited_event_tickets":{"data_list":{"ticket_info":[]},"total_count":0},"event_order_limit":true},"submit":true}'.encode('utf-8').decode('latin1'),
        'sns_status': '{"success":true,"result":{"facebook":0,"twitter":0,"mixi":0,"line":0,"yahoo":0,"plusid":1,"google":0},"submit":true}'.encode('utf-8').decode('latin1')
    }
    response = result.get(reserved_url, headers=header, cookies=cookies, allow_redirects=False)
    print('response.headers:', response.headers)
    redirect_url = response.headers['Location']
    print('redirect_url:', redirect_url)

    return redirect_url


def query_params_o_token(net_url, my_session, origin_url):
    net_url = "https://t.livepocket.jp/purchase/confirm?id=314095&reserved_session_id=809279"
    result = requests.Session()
    header = {
        'Host': 't.livepocket.jp',
        'User-Agent': "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) "
                      "Chrome/69.0.3947.100 Safari/537.36",
        # 'Referer': f'{origin_url}',
    }
    cookies = {
        'ci_session': f'{my_session}'
    }
    response = result.get(net_url, headers=header, cookies=cookies, allow_redirects=False)
    print('response', response)
    location_url = response.headers['Location']
    region_string = location_url.split('?')[1]
    params = region_string.split('&')
    data = {
        'id': params[0].split('=')[1],
        'reserved_session_id': params[1].split('=')[1],
        'otoken': params[2].split('=')[1]
    }

    return data


if __name__ == '__main__':
    # url = 'https://t.livepocket.jp/e/55minholidays_1'
    #
    # event_id, x_session, php_session = query_event("n8vzi@huatcn.com", "panyue666", url)
    # x_url = query_params_reserved_session_id(event_id, x_session, php_session, url)
    # data = query_params_o_token(x_url, x_session, url)
    # print(data)

    my_session = {
        'ci_session': 'w2uNUg2evDN3Y5p9FF6ov%2BeGbOd1bG2G6TcquqbP6s%2BS8sHGzdxFsQiX9MZfADOXtJoTezlRRTMnSHN6eKM4Jj2R9JfAqm4H5VDBp6uMnftQGB4tJLSqk6xAKRi3R9BeAwFh8KQF75VAY88apyvHXzSIr3Cbad5dS2kY4bvj3AiKORmlwm8XamH%2FRr5%2BGYVc20ci0TZ5%2FRft5%2FiU6Du3mBKVqh4wQmKezkwZd7VIWC5FaApglFF%2FNAeuBxgsCnrBEJABu734BJXqHECPiEWWhI5BYx1X2V%2BjIxUI%2Fv6%2FwLDsPPmdwq0tO3mAMHSyMfo402xjZN0iVX3ZwFby2%2Bp8VUSfJdz7DfgZO1FcC62H2n12yJUaatCcXeWn6RgykRzO04o%2BeasJVIwML215vCI6YmgvdRiwSCDlr7QB4%2F5Ae7ZByAE0qk9Ofx4yEHXfjNSlN5j1JN7iNN6NYMkc0raVsQ%3D%3D'
    }

    query_params_o_token(None, my_session, None)