# -*- coding: utf-8 -*-
import time
import scrapy
import logging
import sys, os
from scrapy import signals
from func_timeout import func_set_timeout
sys.path.append(os.path.dirname(os.path.dirname(sys.path[0])))  # 上级目录


@func_set_timeout(3)
def get_sign(data, token, t):
    import execjs
    import platform
    import js2py
    cwd = os.path.dirname(__file__)
    logging.info(f"{data}, {token}, {t}")
    # with open(cwd + '\\js\\17encrypt.js', 'r') as f:
    if "Windows" == platform.system():
        with open(cwd + '\\js\\sign_1688.js', 'r', encoding="utf-8") as f:
            # ctx = execjs.compile(f.read())
            # anti_content = ctx.call('getCookie', data, token, t)
            # return anti_content
            m = js2py.EvalJs()
            m.execute(f.read())
            anti_content = m.get_cc(data, token, t)
            return anti_content
    else:
        with open(cwd + '/js/sign_1688.js', 'r', encoding="utf-8") as f:
            # ctx = execjs.compile(f.read())
            # anti_content = ctx.call('getCookie', data, token, t)
            # return anti_content
            m = js2py.EvalJs()
            m.execute(f.read())
            anti_content = m.get_cc(data, token, t)
            return anti_content


class AddSignMiddleware:
    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def get_cookies(self, request):
        import requests
        headers = {
            "accept": "*/*",
            "accept-language": "zh-CN,zh;q=0.9",
            "cache-control": "no-cache",
            "pragma": "no-cache",
            "referer": "https://sale.1688.com/",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36"
        }
        b = "undefined"
        new_time = round(time.time() * 1000)
        data = "^%^7B^%^22type^%^22^%^3A^%^22canView^%^22^%^7D^"
        logging.info("获取参数")
        sign = get_sign(data, b, new_time)
        logging.info("获取参数成功")
        params = {
            "appKey": "12574478",
            "t": f'{new_time}',
            "sign": f'{sign}',
            "api": "mtop.cbu.overseas.site.ip.business.check",
            "v": "1.0",
            "timeout": "3000",
            "data": "^%^7B^%^22type^%^22^%^3A^%^22canView^%^22^%^7D^"
        }
        url = "https://h5api.m.1688.com/h5/mtop.cbu.overseas.site.ip.business.check/1.0/"
        response = requests.get(url, headers=headers, params=params, verify=False, timeout=6)
        cookies = dict(response.cookies)
        headers = {
            "Host": "dcms.1688.com",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
            "accept": "*/*",
            "referer": "https://shop3413081512086.1688.com/",
            "accept-language": "zh-CN,zh;q=0.9"
        }
        url = "https://dcms.1688.com/open/jsonp/old-pm-qyzx.json"
        params = {
        }
        response = requests.get(url, headers=headers, params=params, verify=False, timeout=6)
        cookies.update(dict(response.cookies))
        cookies = dict(response.cookies)
        return cookies

    def get_cookies_news(self, request):
        import requests
        os.environ['NO_PROXY'] = 'stackoverflow.com'
        requests = requests.session()
        headers = {
            "accept": "*/*",
            "accept-language": "zh-CN,zh;q=0.9",
            "cache-control": "no-cache",
            "pragma": "no-cache",
            "referer": "https://sale.1688.com/",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36"
        }
        url = "https://h5api.m.1688.com/h5/mtop.cbu.overseas.site.ip.business.check/1.0/"

        b = "undefined"
        new_time = round(time.time() * 1000)
        sign = get_sign("^%^7B^%^22type^%^22^%^3A^%^22canView^%^22^%^7D^", b, new_time)
        params = {
            "appKey": "12574478",
            "t": f'{new_time}',
            "sign": f'{sign}',
            "api": "mtop.cbu.overseas.site.ip.business.check",
            "v": "1.0",
            "timeout": "3000",
            "data": "^%^7B^%^22type^%^22^%^3A^%^22canView^%^22^%^7D^"
        }
        response = requests.get(url, headers=headers, params=params, verify=False, timeout=6)

        cookies = dict(response.cookies)
        _m_h5_tk = response.cookies['_m_h5_tk']
        headers = {
            "Host": "dcms.1688.com",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
            "accept": "*/*",
            "referer": "https://shop3413081512086.1688.com/",
            "accept-language": "zh-CN,zh;q=0.9"
        }
        url = "https://dcms.1688.com/open/jsonp/old-pm-qyzx.json"
        params = {
        }
        response = requests.get(url, headers=headers, params=params, verify=False, timeout=6)
        cookies.update(dict(response.cookies))
        b = _m_h5_tk.split("_")[0]

        new_time = round(time.time() * 1000)

        memberid = request.meta.get('memberId')
        data = '{"componentKey":"wp_pc_contactsmall","params":"{\\"memberId\\":\\"%s\\"}"}' % memberid
        sign = get_sign(data, b, new_time)

        url = 'https://h5api.m.1688.com/h5/mtop.alibaba.alisite.cbu.server.pc.moduleasyncservice/1.0/'

        params = (
            ('appKey', '12574478'),
            ('t', str(new_time)),
            ('sign', sign),
            ('api', 'mtop.alibaba.alisite.cbu.server.pc.ModuleAsyncService'),
            ('data', data),
        )

        headers = {
            "Host": "h5api.m.1688.com",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
            "accept": "*/*",
            "referer": "https://shop3413081512086.1688.com/",
            "accept-language": "zh-CN,zh;q=0.9"
        }
        response = requests.get(url, headers=headers, params=params, cookies=cookies, timeout=6, verify=False)
        return response

    def process_request(self, request, spider):
        if request.meta.get('sign_1688'):
            logging.info("开始获取response -->")
            cookies = self.get_cookies_news(request)
            logging.info("response --> scrapy response")
            response = scrapy.http.HtmlResponse(
                url=request.url,
                status=cookies.status_code,
                headers=request.headers,
                body=cookies.text,
                request=request,
                # encoding=resp.get_encoding(),
                encoding="utf-8",
            )
            # logging.info(f"获取cookie成功 {cookies}")
            return response
            # request.cookies = cookies
            # new_time = round(time.time() * 1000)
            # b = cookies["_m_h5_tk"].split("_")[0]
            # data = '{"componentKey":"wp_pc_contactsmall","params":"{\\"memberId\\":\\"%s\\"}"}' % request.meta.get('memberId')
            # logging.info("获取sign成功")
            # sign = get_sign(data, b, new_time)
            # logging.info("开始获取sign")
            # url = f'https://h5api.m.1688.com/h5/mtop.alibaba.alisite.cbu.server.pc.moduleasyncservice/1.0/?appKey=12574478&t={new_time}&sign={sign}&api=mtop.alibaba.alisite.cbu.server.pc.ModuleAsyncService&data={data}'
            # request._set_url(url)
            # logging.info(f"装载 sign参数:{sign} 拼接 url 添加cookie: {cookies}")
            # return None

    def process_response(self, request, response, spider):
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)
