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)
        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
        r = s.request(
            req['method'],
            url=host['develop_host']['backend'] + req['url'],
            params=req.get('params'),
            # headers=user_headers,
            data=req.get('data'),
            json=req.get('json')
        )
        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()

