import requests

from API2 import log_decorator
from API2.common.db import DB
from API2.common.read_ini import ReadIni


class RequestMethod:
    @log_decorator
    def __init__(self):
        """关联被测系统状态"""
        loger=ReadIni().get_host('host') + "/auth"
        log_data = {
            "username": "admin",
            "password": "fWwO5OcV0c5AZfgOohpm4OE/FjKMc5wcjjaJvfbnrTIQMG5d3htn2aFA2iZGkSgYZ+9liGgmple6bCp+NT4PnY2Jlov8tV8Q/+nn2IZTuPCMwHqRrUchpPUr4wXWuQ+Gk55DNu4CZgxWQ5HxfzixGHJT29D6TUiz5Ea+mLm3fg8="
        }
        self.bpm_session = requests.sessions.Session()
        self.header={"Authorization": "Bearer " +self.bpm_session.request(method='post',url=loger,json=log_data).json().get('token')}
        self.bpm_session.headers.update(self.header)

        self.db=DB()

    @log_decorator
    def request_all(self,req_method, req_url, req_mime, case_data, sql_type, sql_data, update_key):
        """
        封装一个公共的请求方法
        :param req_method: 请求方法
        :param req_url: 请求的url
        :param req_mime: 请求的媒体类型
        :param case_data: 用例数据
        :param sql_type: sql语句类型
        :param sql_data: sql语句
        :param update_key: 更新的key
        :return: Response Type
        """

        # 先执行sql语句---该删除的就删除，如果有查询就需要更新用例数据，更新时，需要注意用例数据的类型
        if sql_type=='delete':
            self.db.delete(sql_data)
        elif sql_type=='select':
            select_resule=self.db.select(sql_data)
            if isinstance(case_data,str):
                case_data=case_data.replace(update_key,select_resule)
            else:
                case_data[update_key]=select_resule

        # 判断sql语句的类型是否为delete|select，或者为select|delete
        elif sql_type=="delete|select" or sql_type=="select|delete":
            #执行删除
            self.db.delete(sql_data['delete'])
            select_resule=self.db.select(sql_data['select'])
            if isinstance(case_data,str):
                case_data=case_data.replace(update_key,select_resule)
            else:
                case_data[update_key]=select_resule

        #判断媒体类型
        if req_mime=="json" or req_mime =="application/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)
            else:
                return self.bpm_session.request(method=req_method,url=req_url,json=case_data)

        elif req_mime=="text" or req_mime == "text/plain":
            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=="form" or req_mime=="x-www-form-urlencoded" or req_mime == "application/x-www-form-urlencoded":
            self.bpm_session.headers["content-type"]=="application/x-www-form-urlencoded"
            return self.bpm_session.request(method=req_method,url=req_url,data=case_data)

        elif req_mime=='query':
            return self.bpm_session.request(method=req_method,url=req_url,params=case_data)

        #请求体和地址栏同时传参
        elif req_mime=="query|json" or req_mime=="json|query":
            body=case_data.get("body")
            query=case_data.get("query")
            self.bpm_session.headers["content-type"] = "application/json"
            if isinstance(body,str):
                return self.bpm_session.request(method=req_method,url=req_url,data=body,params=query)
            else:
                return self.bpm_session.request(method=req_method,url=req_url,json=body,params=query)

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


        else:
            print("媒体类型错误")

if __name__ == '__main__':
    data = ['get', 'http://36.139.193.99:8088/api/demension/v1/dem/getDem', 'query', 'code=lllqq', {'isDelete': '0'},None, None, None]
    req = RequestMethod()
    requst = req.request_all(req_method=data[0], req_url=data[1], req_mime=data[2], case_data=data[3],sql_type=data[-3], sql_data=data[-2], update_key=data[-1])
    dem = requst.json()['id']
    print(requst.json()['id'])











