import os
import sys
import time
import random

sys.path.append(os.path.dirname(sys.path[0]))  # 上级目录
from utils.db_connect import BaseUtils
import json
from flask import Flask, request, jsonify
import requests
import traceback

app = Flask(__name__)


def db_resin():
    redis14_ = BaseUtils().redis_db()
    return redis14_


def generate_uuid():
    """ 原js代码
      d.random = function() {
            return "Sif_xxxx-xxxx-4xxx-yxxx-xxxx".replace(/[xy]/g, function(e) {
                var t = 16 * Math.random() | 0;
                return ("x" == e ? t : 3 & t | 8).toString(16)
            })
        }
    转换控制台可输出js代码
    d = {};
d.random = function() {
    return "Sif_xxxx-xxxx-4xxx-yxxx-xxxx".replace(/[xy]/g, function(e) {
        var t = Math.floor(16 * Math.random());
        return (e == "x" ? t : (t & 0x3 | 0x8)).toString(16);
    });
}
console.log(d.random());
    """
    # 通过python实现
    uuid_template = "Sif_xxxx-xxxx-4xxx-yxxx-xxxx"

    def replace_char(c):
        r = random.randint(0, 15)
        if c == 'x':
            return hex(r)[2:]
        elif c == 'y':
            return hex((r & 0x3) | 0x8)[2:]

    return ''.join(replace_char(c) if c in 'xy' else c for c in uuid_template)


def login_slf():
    for i in range(10):
        try:
            int_time = int(time.time() * 1000)
            _m = generate_uuid()
            login_url = f'https://www.sif.com/api/user/login?_t={int_time}&_m={_m}'
            print(login_url)
            headers = {
                "Accept": "application/json, text/plain, */*",
                "Accept-Encoding": "gzip, deflate, br, zstd",
                "Accept-Language": "zh-CN,zh;q=0.9",
                "Cache-Control": "no-cache",
                "Connection": "keep-alive",
                "Content-Length": "44",
                "Content-Type": "application/json;charset=UTF-8",
                "Host": "www.sif.com",
                "Origin": "https://www.sif.com",
                "Pragma": "no-cache",
                "Referer": "https://www.sif.com/",
                "Sec-Ch-Ua": '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
                "Sec-Ch-Ua-Mobile": "?0",
                "Sec-Ch-Ua-Platform": '"Windows"',
                "Sec-Fetch-Dest": "empty",
                "Sec-Fetch-Mode": "cors",
                "Sec-Fetch-Site": "same-origin",
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
            }
            account_name_list = [["13752682896", "FXJ9955"], ['15112376559', 'PYB8899']]
            name_lsit = random.choice(account_name_list)
            data = {"phone": name_lsit[0], "password": name_lsit[1]}
            resp = requests.post(login_url, headers=headers, json=data, timeout=20)
            headers['authorization'] = resp.headers['authorization']
            print(headers)
            print(resp.text)
            redis14_ = db_resin()
            redis14_.set('sif_headers', json.dumps(headers))
            return headers
        except:
            continue
    return {}


def get_redis_sif_headers():
    print('查询 redis中的headers返回')
    try:
        redis14_ = db_resin()
        headers_str = redis14_.get('sif_headers')
        headers = json.loads(headers_str)
    except:
        headers = login_slf()
    return headers


def dow_slf_sp_csv(keyword=None):
    for i in range(5):
        try:
            redis14_ = db_resin()
            headers_str = redis14_.get('sif_headers')
            headers = json.loads(headers_str)
            print(headers)
            data = {"keywords": [f"{keyword}"], "isExpand": True, "granularity": "week"}
            print(data)
            url = 'https://www.sif.com/api/updown/cpcCategory/download?country=US&_t=1722412047703&_m=Sif_b4d3-80c8-43e0-8dad-7296'
            resp = requests.post(url, headers=headers, json=data, timeout=120)
            try:
                resp_json = resp.json()
                print(resp_json)
                if resp_json['code'] == -7:
                    print('重新登录。被挤下线')
                    login_slf()
                    continue
            except:
                pass

            int_time = int(time.time())
            print(int_time)
            print(len(resp.text))
            # 下载文件
            if len(resp.text) > 500:
                with open(rf'D:\新建文件夹\requests_files\cpcCategory_{keyword}_{int_time}.xlsx', 'wb')as f:
                    f.write(resp.content)
                redis14_.close()
                time.sleep(3)

                import pandas as pd

                # Define the file path
                file_path = rf'D:\新建文件夹\requests_files\cpcCategory_{keyword}_{int_time}.xlsx'

                # Use pandas to read the Excel file
                df = pd.read_excel(file_path)

                # Display the content of the DataFrame
                print(df)

                return True
        except Exception as e:
            print(e, f"\n{traceback.format_exc()}")
            login_slf()
            continue


def texts():
    # login_slf()
    redis14_ = db_resin()
    headers_str = redis14_.get('sif_headers')
    headers_dict = json.loads(headers_str)
    print(headers_dict)
    from curl_cffi import requests as r23
    int_time = int(time.time() * 1000)
    _m = generate_uuid()
    # 'https://www.sif.com/api/updown/asinKeywords/download?country=US&_t=1732506642372&_m=Sif_e61f-99f9-4224-90b5-04a9'
    # 'https://www.sif.com/api/updown/asinKeywords/download?country=US&_t=1732506797142&_m=Sif_4a79-9010-465e-a5a0-3450'
    url = f'https://www.sif.com/api/updown/asinKeywords/download?country=US&_t={int_time}&_m=Sif_f560-9ab2-415e-86f0-039e'
    # 'https://www.sif.com/api/updown/asinKeywords/download?country=US&_t=1732001399863&_m=Sif_b4d3-80c8-43e0-8dad-7296'
    # 'https://www.sif.com/api/updown/asinKeywords/download?country=US&_t=1732002068051&_m=Sif_a2ca-b411-4820-8380-721d'
    # print(url)
    #
    #
    # #"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ3ZWNoYXRpZCI6Im90SkwwNTRJamhWc1RKcmlGZFc0dmh2eHd2dUEiLCJ1c2VyU2FsdCI6Ijk4ZFEyUHdsIiwiZXhwIjoxNzMyOTM4NjMxLCJ1c2VyaWQiOiJjcTM4enk0RlU0OTQxSmswNWRMTTNxMjMiLCJwbGF0Zm9ybSI6Im9mZmljaWFsIn0.RRvVKJ7g-WYcruWL-nJZ1IzIOBOzbt2YgzrKWkX_qUk"
    # # "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ3ZWNoYXRpZCI6Im90SkwwNTRJamhWc1RKcmlGZFc0dmh2eHd2dUEiLCJ1c2VyU2FsdCI6InpROVk3TDU2IiwiZXhwIjoxNzMyNjk1ODY4LCJ1c2VyaWQiOiJjcTM4enk0RlU0OTQxSmswNWRMTTNxMjMiLCJwbGF0Zm9ybSI6Im9mZmljaWFsIn0.-GcRkCrrw6OJJIBUgrxkUuthGbgLMMOr-WR3LfSahhY"
    # data = {"asins":"B09XHGG4B8","sortBy":"","conditions":[],"desc":True,"timePieceType":"latelyDay","timePieceValue":"7","isListingSearch":True} # 反查父体
    # # {"asins": "B09XHGG4B8", "sortBy": "", "conditions": [], "desc": True, "timePieceType": "latelyDay","timePieceValue": "7", "isListingSearch": False} # 反查子体
    # resp = r23.post(url, headers=headers_dict, json=data, timeout=300, impersonate="chrome120")
    # print(resp.headers)
    # print(resp.text)
    # with open(rf'D:\新建文件夹\requests_files\cpcCategory_BB0446666.xlsx', 'wb')as f:
    #     f.write(resp.content)
    # 选词
    # url = 'https://www.sif.com/api/search/keywordFunnel/list?country=US&_t=1746499312511&_m=Sif_bd42-81a4-4ce5-a21d-973c'
    # data = {"pageSize": 100, "pageNum": 1, "sortBy": "", "customPrice": "", "customProfitRate": "", "desc": True,
    #         "strategy": "legacyForSales_exact", "matchTypes": [], "keywords": ["resin", "resin molds"]}
    # redis14_ = db_resin()
    # headers_str = redis14_.get('sif_headers')
    # headers = json.loads(headers_str)
    # print(headers)
    # resp = requests.post(url, headers=headers, json=data, timeout=120)
    # print(resp.json())


@app.route('/sif/api/login', methods=['GET'])
def get_args():
    regetFlag = request.args.get('regetFlag')
    if regetFlag == 'true':
        headers = login_slf()
        if headers:
            items = {"code": 200, "message": "success", "headers": headers}
        else:
            items = {"code": 500, "message": "error", "headers": headers}

    else:
        headers = get_redis_sif_headers()
        items = {"code": 200, "message": "success", "headers": headers}
    return jsonify(items)


if __name__ == '__main__':
    # app.run('0.0.0.0', 10248)
    # dow_slf_sp_csv(keyword='chopin mazurkas')
    texts()
    # login_slf()
