# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName:   test65
# FileName:      requests_method.py
# Author:       lao_zhao
# Datetime:     2025/3/12 14:09
# Description:
# 
# ---------------------------------------------------------------------------
import requests
from APIAutoTest_v3 import log_decorator
from APIAutoTest_v3.common.db import DB
from APIAutoTest_v3.common.read_system_ini import ReadSystemIni


class RequestsMethod:

    @log_decorator
    def __init__(self):
        """管理登录成功的状态"""
        self.db = DB()
        login_url = ReadSystemIni().get_server_value("host")+"/auth"
        login_data = {"username":"admin","password":"ReTD+PMGuwsQsk5mIeftmdgn11TSZLaUlltu1bBj8qjJih/qubrUISuePL82azz5Al3CL5CXcSz/K3gvdz5IMKaR7YPzldOwFyXbObJoJzkruT5PB0+kwP0wQX8qfu9pAAiyZBAA1Ikk6xzQWT2N6v5hmQw6pehUfnssbqjsI3M="}
        self.bpm_session = requests.sessions.Session()
        self.header = {"Authorization": "Bearer "+self.bpm_session.post(url=login_url, json=login_data).json().get("token")}
        self.bpm_session.headers.update(self.header)

    @log_decorator
    def request_all(self, req_method, req_url, req_mime, case_data, sql_data, sql_type, update_key):
        """
        封装一个公共的请求方法，发送请求前置该执行sql语句的就要执行sql语句，该更新用例数据的更新用例数据
        :param req_method: 请求方法
        :param req_url: 请求url
        :param req_mime: 请求的媒体类型
        :param case_data: 请求的用例数据
        :param sql_data: 执行的sql语句
        :param sql_type: sql语句的类型
        :param update_key: 更新的key
        :return: Response type
        """
        if sql_type == "delete":
            self.db.delete(sql_data)

        elif sql_type == "select":
            select_result = self.db.select(sql_data)
            if update_key == "需要更新":
                case_data = case_data.replace("需要更新", select_result)
            elif isinstance(case_data, dict):
                case_data[update_key] = select_result

        elif sql_type == "select|delete" or sql_type == "delete|select":
            self.db.delete(sql_data["delete"])

            select_result = self.db.select(sql_data["select"])
            if update_key == "需要更新":
                case_data = case_data.replace("需要更新", select_result)
            elif isinstance(case_data, dict):
                case_data[update_key] = select_result


        if req_mime == "application/json" or req_mime == "json":
            self.bpm_session.headers["content-type"] = "application/json"
            if isinstance(case_data, str):
                return self.bpm_session.request(method=req_method, url=req_url, data=case_data)
            elif isinstance(case_data, (dict, list)):
                return self.bpm_session.request(method=req_method, url=req_url, json=case_data)

        elif req_mime == "application/x-www-form-urlencoded" or req_mime == "x-www-form-urlencoded" or req_mime == "form":
            self.bpm_session.headers["content-type"] = "application/x-www-form-urlencoded"
            if isinstance(case_data, (dict, list, str)):
                return self.bpm_session.request(method=req_method, url=req_url, data=case_data)

        elif req_mime == "multipart/form-data" or req_mime == "form-data":
            return requests.request(method=req_method, url=req_url, files=case_data, headers=self.header)

        elif req_mime == "query":
            if isinstance(case_data, str):
                req_url = req_url + "?" + case_data
                return self.bpm_session.request(method=req_method, url=req_url)
            elif isinstance(case_data, dict):
                return self.bpm_session.request(method=req_method, url=req_url, params=case_data)

        elif req_mime is None:
            return self.bpm_session.request(method=req_method, url=req_url)

        elif req_mime == "text/plain" or req_mime == "text":
            self.bpm_session.headers["content-type"] = "text/plain"
            return self.bpm_session.request(method=req_method, url=req_url, data=case_data)

        elif req_mime == "query|json" or req_mime == "json|query":
            self.bpm_session.headers["content-type"] = "application/json"

            query_data = case_data["query"]
            body_data = case_data["body"]

            if isinstance(query_data, str):
                req_url = req_url + "?" + query_data
                if isinstance(case_data["body"], str):
                    return self.bpm_session.request(method=req_method, url=req_url, data=body_data)
                elif isinstance(case_data["body"], (dict, list)):
                    return self.bpm_session.request(method=req_method, url=req_url, json=body_data)

            elif isinstance(query_data, dict):
                if isinstance(body_data, str):
                    return self.bpm_session.request(method=req_method, url=req_url, params=query_data, data=body_data)
                elif isinstance(case_data["body"], (dict, list)):
                    return self.bpm_session.request(method=req_method, url=req_url, params=query_data, json=body_data)

        else:
            raise ValueError("媒体类错误")