import json
import random
import datetime
import requests
import yaml
import os
import sys
# from jsonpath import jsonpath
# from login_session_function import LoginFunction
# from pymysql import OperationalError

import path_setting


class BaseRequest:
    params = {}

    @classmethod
    def format(cls, r):
        cls.r = r
        print(json.dumps(json.loads(r.text), indent=2, ensure_ascii=False))

    # 封装yaml文件读取
    @classmethod
    def yaml_load(cls, path) -> list:
        with open(path, encoding='utf-8') as f:
            return yaml.safe_load(f)

    # 调用yaml加载文件API加载
    def api_load(self, path: object) -> object:
        print("path路径", path)
        return self.yaml_load(path)

    # def jsonpath(self, path, r=None, **kwargs):
    #     if r is None:
    #         r = self.r.json()
    #     return jsonpath(r, path)
    def read_header(self):
        BASE_DIR = os.path.dirname(os.path.dirname(__file__))
        sys.path.append(BASE_DIR)
        print("os.getcwd()",os.getcwd())
        path = os.path.join(BASE_DIR, "in_common/get_cookie.txt")
        print("path---------", path)
        with open(path, 'r', encoding='utf-8') as f:
            cookies = f.read()
        headers = {"cookie": cookies}
        return headers

    def api_send(self, req: object) -> object:
        host = self.api_load(path_setting.HOSTYAML_CONFIG)

        # 获取调用该方法的路径
        import inspect
        ins_file = inspect.stack()[1].filename
        ins_dir = ins_file.split('/')[-2]
        host_service = ins_dir.split('_')[1]
        # default: backend
        if host_service not in host['develop_host']:
            host_service = 'backend'
        url_host = host['develop_host'][host_service]
        print("-----------", url_host)
        # if host["develop_host"].get("doctor") is not None:
        #     url_host = host['develop_host']['doctor']
        # elif host["develop_host"].get("backend") is not None:
        #     url_host = host['develop_host']['backend']

        raw = yaml.dump(req)  # 将一个python对象生成为yaml文档
        for key, value in self.params.items():
            raw = raw.replace(f"${{{key}}}", repr(value))
        req = yaml.safe_load(raw)
        print('req:', req)
        # print("self.read_header()",self.read_header())
        # s = requests
        # if req.get('isLogin'):
        #     s = LoginFunction().get_session()
        # 调用具体case的url
        print("请求开始时间：",datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))
        r = requests.request(
            req['method'],
            url=url_host + req['url'],
            params=req.get('params'),
            headers=self.read_header(),
            data=req.get('data'),
            json=req.get('json'),
            # verify=False
            # proxies={"http":"172.30.9.226:8888"}

        )
        print("请求结束时间：",datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))
        try:
            content_type = r.headers.get("content-type").split(";")[0]
        except:
            content_type = "application/json"
        if content_type == 'application/json':
            print("请求结果验证码***",r.status_code)
            print("请求request数据",r.request)
            print("请求的headers数据",r.headers)
            return r.json()
        print("请求结果验证码***", r.status_code)
        print("请求request数据", r.request)
        print("请求的headers数据", r.headers)
        return r.text

    def get_cookie(self, req: dict):
        host = self.api_load(path_setting.HOSTYAML_CONFIG)
        print(host)
        r = requests.request(
            req['method'],
            url=host['develop_host']['backend'] + req['url'],
            params=req['params'],
            headers=req['headers'],
            data=req['data'],
            json=req['json']
        )
        dict = {}
        for i in r.cookies:
            dict[i.name] = i.value
        headers = '_gtid={};sessionid={}'.format(dict["_gtid"], dict["sessionid"])
        return headers




if __name__ == '__main__':
    # BaseRequest().api_load("../api/api.yaml")
    print(BaseRequest().trace_id())
