import json
import random
import string
import requests
import yaml
from jsonpath import jsonpath
from login_session_function import LoginFunction
# from pymysql import OperationalError

import path_setting


class BaseRequest:

    params = {}
    data = {}

    @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):
        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 get_cookie(self, req: dict):

        host = self.api_load(path_setting.HOSTYAML_CONFIG)
        print(host)
        r = requests.request(
            req['method'],
            url=host['develop_host']['url'] + 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

    def read_header(self):
        with open("../in_common/get_cookie.txt", 'r', encoding='utf-8') as f:
            cookies = f.read()
        headers = {"cookie": cookies}
        return headers
    '''

    def api_send(self, req: dict):
        host = self.api_load(path_setting.HOSTYAML_CONFIG)
        url_host = ""
        # 获取调用该方法的路径
        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]

        # 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)

        s = requests
        if req.get('isLogin'):
            s = LoginFunction().get_session()

        # 调用具体case的url
        print(req['method'])
        print(url_host + req['url'])
        print(req.get('params'))
        print(req.get('data'))
        r = s.request(
            req['method'],
            url=url_host + req['url'],
            params=req.get('params'),
            # headers=user_headers,
            data=req.get('data'),
            json=req.get('json'),
            # proxies={"http":"172.30.9.226:8888"}
        )
        print(r)
        print(r.content)
        return r.json()

    # 随机生成trace_id
    def trace_id(self):
        return ''.join(random.sample(string.ascii_lowercase + string.digits, 32))

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

