# -*- coding: utf-8 -*-
# @Time : 2021/11/4 10:29
# @Author : wangyinghao
# @Site : 
# @File : api_utils.py
# @Software: PyCharm
import re
from faker import Faker
# from automated_main.models.api_automation.api_test_case import ApiParameterExtraction
from automated_main.models.api_automation.api_interfaces_case import ApiInterfacesParameterExtraction
from automated_main.models.api_automation.api_environment import APIGlobalVariable
import logging
import requests
import json

logger = logging.getLogger('django')
fake = Faker(locale='zh_CN')


def RegularMatch(data, api_environment_id, api_task=None, regular=None, **kwargs):
    """
    正则提取
    :param api_task: api任务
    :param api_environment_id: 环境id
    :param data:
    :param regular:正则表 8.4更新
    :return:
    """
    if "${" in data and "}" in data:
        key = re.findall(r"\${(.+?)}", data)
        for a in range(len(key)):
            key1 = "${" + key[a] + "}"

            if key1 == "${random_name}":
                # 随机名字
                data = data.replace(key1, fake.name())
            elif key1 == "${random_email}":
                # 随机email
                data = data.replace(key1, fake.email())
            elif key1 == "${random_sfz}":
                # 随机身份证
                data = data.replace(key1, fake.ssn())
            elif key1 == "${random_phone_number}":
                # 随机手机号
                data = data.replace(key1, fake.phone_number())
            elif key1 == "${random_address}":
                # 随机地址
                data = data.replace(key1, fake.address())
            elif key1 == "${random_company}":
                # 随机公司名称
                data = data.replace(key1, fake.company())
            elif key1 == "${random_city}":
                # 随机城市
                data = data.replace(key1, fake.city())
            elif key1 == "${random_number}":
                # 随机数
                data = data.replace(key1, str(fake.random_int()))

            else:
                api_global_variable = APIGlobalVariable.objects.filter(api_global_variable_name=key1,
                                                                       api_environment_id=api_environment_id)
                if api_global_variable.count() > 0:
                    variable = api_global_variable[0].api_global_variable_value
                    data = data.replace(key1, variable)
                else:
                    if regular is None:
                        value_variable = ApiInterfacesParameterExtraction.objects.filter(api_key_variable=key1)
                    else:
                        value_variable = ApiInterfacesParameterExtraction.objects.filter(api_key_variable=key1)
                    if value_variable.count() > 0:
                        variable = value_variable[0].api_variable_results
                        data = data.replace(key1, variable)
                    else:
                        if api_task is not None:
                            return data
                        else:
                            logger.info("该变量数据库未找到：" + str(key1))
                            data = ["该变量数据库未找到", str(key1)]
        return data
    else:
        return data


def ExtractParameters(v_text, api_result):
    """
    json提取参数值
    :param api_result:
    :param v_text:
    :return:
    """
    for a in v_text:
        if "[" in a and "]" in a:
            variable_1 = a.split('[')[0]
            if variable_1 == "" or None:
                variable_1 = int(a[1:2])
                api_result = api_result[int(variable_1)]
            else:
                variable_2 = a.split('[')[1].split(']')[0]
                api_result = api_result[variable_1][int(variable_2)]
        else:
            api_result = api_result[a]
    return api_result


def InterfaceRequest(api_method, api_parameter_types, api_url, header=None, payload=None, api_parameter=None):
    """
    常用接口请求封装
    :param api_method: 请求方式类型
                        1:get
                        2:post
                        3:put
                        4:delete
    :param api_parameter_types: 请求参数类型
                        1:form-data
                        2:JSON
                        3.x-www-form-urlencoded
                        4.none
    :param api_url: 请求URL
    :param payload: 请求参数
    :param api_parameter: parameter参数
    :param header: 请求头
    :return:
    """
    header['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' \
                           'Chrome/102.0.0.0 Safari/537.36 '
    r = None
    try:
        # Get
        if api_method == "1":
            if api_parameter_types == "1":
                r = requests.get(api_url, params=api_parameter, headers=header, timeout=(6, 18))
            if api_parameter_types == "2":
                r = requests.get(api_url, json=payload, params=api_parameter, headers=header, timeout=(6, 18))
            if api_parameter_types == "3":
                r = requests.get(api_url, data=payload, params=api_parameter, headers=header, timeout=(6, 18))

        # Post
        if api_method == "2":
            if api_parameter_types == "1":
                r = requests.post(api_url, data=payload, params=api_parameter, headers=header, timeout=(6, 18))
            if api_parameter_types == "2":
                r = requests.post(api_url, json=payload, params=api_parameter, headers=header, timeout=(6, 18))
            if api_parameter_types == "3":
                r = requests.post(api_url, data=payload, params=api_parameter, headers=header, timeout=(6, 18))

        # Put
        if api_method == "3":
            if api_parameter_types == "1":
                r = requests.put(api_url, data=payload, params=api_parameter, headers=header, timeout=(6, 18))
            if api_parameter_types == "2":
                r = requests.put(api_url, json=payload, params=api_parameter, headers=header, timeout=(6, 18))
            if api_parameter_types == "3":
                r = requests.put(api_url, data=payload, params=api_parameter, headers=header, timeout=(6, 18))

        # Delete
        if api_method == "4":
            if api_parameter_types == "1":
                r = requests.delete(api_url, data=payload, params=api_parameter, headers=header, timeout=(6, 18))
            if api_parameter_types == "2":
                r = requests.delete(api_url, json=payload, params=api_parameter, headers=header, timeout=(6, 18))
            if api_parameter_types == "3":
                r = requests.delete(api_url, data=payload, params=api_parameter, headers=header, timeout=(6, 18))

        # PATCH
        if api_method == "5":
            if api_parameter_types == "1":
                r = requests.patch(api_url, data=payload, params=api_parameter, headers=header, timeout=(6, 18))
            if api_parameter_types == "2":
                r = requests.patch(api_url, json=payload, params=api_parameter, headers=header, timeout=(6, 18))
            if api_parameter_types == "3":
                r = requests.patch(api_url, data=payload, params=api_parameter, headers=header, timeout=(6, 18))
    except requests.exceptions.RequestException as e:
        r = "请求超时"

    return r


def querry_diff(env, api):
    source = env.get('source_url')
    target = env.get('target_url')

    header = {"apikey": "$2a$10$ucmK9tcKdyLpzeYYeNxBfeDWgtLjFq5UYiyLFfaJYMyHloaOi3AB.",
              "Content-Type": "application/x-www-form-urlencoded"}
    # source_result = requests.get("http://qa.rd.com/sonar/project/config/queryCrNameByProjectAddr?projectAddr=ssh://git@gitlab.rd.com:2299/qike_back_end/qike-bid.git")
    # target_result = requests.get("http://qa.rd.com/sonar/project/config/queryCrNameByProjectAddr?projectAddr=ssh://git@gitlab.rd.com:2299/ecd/hubble/hubble-operation-center.git")

    source_result = InterfaceRequest(str(api.get('method')), "3", source + api.get('api_url'), header,
                                     api_parameter=json.loads(api.get('param')))
    target_result = InterfaceRequest(str(api.get('method')), "3", target + api.get('api_url'), header,
                                     api_parameter=json.loads(api.get('param')))

    api['status'] = 1
    # 状态码不一致
    if source_result.status_code != target_result.status_code:
        logger.error("接口{},结果状态码不一致".format(api['id']))
        api['status'] = 2
        api['result'] = "请求状态码不一致 target：{},source: {}".format(target_result.status_code, source_result.status_code)

        return api

    if source_result.text != target_result.text:
        logger.error("接口{}，结果不一致".format(api['id']))
        api['status'] = 2
        api['result'] = "请求结果对比失败 target：{},source: {}".format(json.dumps(target_result.json(), ensure_ascii=False),
                                                               json.dumps(source_result.json(), ensure_ascii=False))

    return api
