import os
import sys
from lxml import etree
import random
import pandas as pd
import uuid

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

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
sess = requests.Session()
urllib3.disable_warnings()
app = Flask(__name__)


# 获取从QA邮件中解析到的url。 获取asin

def db_mysql():
    mysql_engine = BaseUtils().mysql_connect()
    return mysql_engine


def get_headers(site_name):
    mysql_engine = db_mysql()
    sql_read = f"SELECT cookies FROM {site_name}_cookies limit 100;"
    df_cookies = pd.read_sql(sql_read, con=mysql_engine)
    cookies_list = list(df_cookies['cookies'])
    for cookie_str in cookies_list:
        if len(cookie_str) > 50:
            try:
                cookie_lsit = json.loads(cookie_str)
            except:
                cookie_lsit = eval(cookie_str)
            cookie_dic = {}
            try:
                for i in cookie_lsit:
                    if i:
                        cookie_dic[i["name"]] = i["value"]
                    else:
                        continue
                cookie_str = ''
                for k, v in cookie_dic.items():
                    cookie_str = cookie_str + str(k) + '=' + str(v) + ';'
                break
            except:
                cookie_str = ''
                for k, v in cookie_lsit.items():
                    cookie_str = cookie_str + str(k) + '=' + str(v) + ';'
                break
    n = random.randint(118, 124)
    ua = f'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{n}.0.{random.randint(1000, 5000)}.{random.randint(1, 181)} Safari/537.36'
    headers = {
        'connection': 'close',
        'accept': 'text/html,*/*',
        'accept-language': 'zh-CN,zh;q=0.9',
        'cache-control': 'no-cache',
        'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
        'sec-ch-ua-mobile': '?0',
        'user-agent': ua,
        "Pragma": "no-cache",
        "Sec-Fetch-Mode": "navigate",
        "Sec-Fetch-Site": "none",
        "Sec-Fetch-User": "?1",
        "Upgrade-Insecure-Requests": "1",
    }
    if site_name == "us":
        site_url = 'https://www.amazon.com/'
    elif site_name == 'uk':
        site_url = 'https://www.amazon.co.uk/'  # 站点url
    elif site_name == 'de':
        site_url = 'https://www.amazon.de/'
    elif site_name == 'fr':
        site_url = 'https://www.amazon.fr/'
    elif site_name == 'es':
        site_url = 'https://www.amazon.es/'
    elif site_name == 'it':
        site_url = 'https://www.amazon.it/'
    headers['origin'] = site_url
    headers['referer'] = site_url
    headers["cookie"] = cookie_str
    alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
                's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    k = ""
    for i in (0, random.randint(0, 26)):
        k += random.choice(alphabet)
    headers[k] = str(uuid.uuid4())
    return headers, site_url


def requests_url(site_name, url):
    for i in range(3):
        try:
            headers, site_url = get_headers(site_name)
            sess.mount(site_url, py_ja3.DESAdapter())
            resp = sess.get(url, headers=headers,
                            timeout=10, verify=False)
            html_xpath = etree.HTML(resp.text)
            divs = html_xpath.xpath("//div[@id='a-page']")
            if divs:
                asins_list = html_xpath.xpath("//div[@id='a-page']//div[@class='a-column a-span3']//a/@href")
                print(asins_list)
                if asins_list:
                    asin = re.findall(r'product/(.*?)/ref=', asins_list[0])
                    return asin
        except:
            pass
    return None

#
# @app.route('/amazon/ask/question', methods=['POST'])
# def get_args():
#     data = request.get_json()
#     site_name = data['site_name']
#     url = data['url']
#     if site_name and url:
#         asin = requests_url(site_name, url)
#         if asin:
#             items = {"code": 200, "message": "success", "asin": asin[0]}
#         else:
#             items = {"code": 200, "message": "No data", "asin": None}
#     else:
#         items = {"code": 500, "message": "error", "asin": None}
#     return jsonify(items)
#
#
# if __name__ == '__main__':
#     app.run('0.0.0.0', 10249)
#     # asin = requests_url('us','https://sellercentral.amazon.com/nms/redirect/52fa5b2e-d6ba-3e4b-9e81-fc77458c8ee5?nt=ASK_THE_SELLER&amp;sk=xKNoM-iJITJ4P0izQupyQeoqK25AfteSfGGJqYdXvwq7XrtXNz5Y9G_bhfbPZajQJbHfnDwMOn3okFY5viaBVQ&amp;n=1&amp;u=aHR0cHM6Ly93d3cuYW1hem9uLmNvbS9hc2svcXVlc3Rpb24vVHhUNlgyRlYySkoyNDY_X2VuY29kaW5nPVVURjgmYXV0aFRva2VuPWZiMGQ2ZDRkLTBhNmUtNDU2Mi05YzkxLTJiNzE0YTRmNDQ1NyZyZWZfPXNfcmVzcG9uZCZhbnN3ZXJTb2xpY2l0YXRpb25Tb3VyY2VUeXBlPUVNQUlMJmFuc3dlclNvbGljaXRhdGlvbkxhbmd1YWdlPWVuX1VT')
#     # print(asin)