# -*- coding: utf-8 -*-
# @Time : 2022/5/24 21:30
# @Author : wangyinghao
# @Site : 
# @File : api_management_list_view.py
# @Software: PyCharm
import requests
from django.views.generic import View
import json
from automated_main.utils.http_format import response_success, response_failed
from automated_main.exception.my_exception import MyException
from automated_main.models.api_automation.api_management import ApiManagement, IS_ROOT
from automated_main.models.api_automation.api_interfaces_case import ApiInterfacesCase
from datetime import datetime
from automated_main.utils.api_yapi_util import ApiYapiServer
from automated_main.form.api_management import ApiManagementForm


class ApiManagementListView(View):

    def get(self, request, *args, **kwargs):
        """
        代表获取服务列表
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        api_management_data = ApiManagement.objects.filter(parent=0)

        api_management_list = []

        for api_management in api_management_data:
            api_management_dict = {
                "id": api_management.id,
                "name": api_management.name,
                "parent": api_management.parent,
                "description": api_management.description,
                "icon": "el-icon-folder-opened"

            }
            api_management_list.append(api_management_dict)

        return response_success(api_management_list)

    def put(self, request, *args, **kwargs):
        """
        创建服务
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        body = request.body
        params = json.loads(body)
        form = ApiManagementForm(params)
        result = form.is_valid()
        if result:
            api_management = ApiManagement.objects.create(**form.cleaned_data)
            if api_management:
                return response_success()
            else:
                raise MyException("创建失败")
        else:
            return response_failed()

    def post(self, request, *args, **kwargs):
        """
        获取服务下一级别的服务
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        body = request.body
        params = json.loads(body)
        api_management_list = []

        if params == {}:
            pass

        else:
            api_management_data = ApiManagement.objects.filter(parent=params['parent'])
            if params['isLeaf'] == "false":
                for api_management in api_management_data:
                    api_management_dict = {
                        "id": api_management.id,
                        "name": api_management.name,
                        "parent": api_management.parent,
                        "description": api_management.description,
                        "icon": "el-icon-folder-opened"

                    }
                    api_management_list.append(api_management_dict)
            else:
                for api_management in api_management_data:
                    api_management_dict = {
                        "id": api_management.id,
                        "name": api_management.name,
                        "parent": api_management.parent,
                        "description": api_management.description,
                        "isParent": True,
                        "icon": "el-icon-lx-text"

                    }

                    api_management_list.append(api_management_dict)

        return response_success(api_management_list)


class ApiManagementSearchView(View):

    def post(self, request, *args, **kwargs):
        """
        搜索服务
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        body = request.body
        params = json.loads(body)
        print(params)

        api_management_list = []
        management_data = ApiManagement.objects.filter(name__icontains=params['management_name'])
        for management in management_data:
            print(management.name)

            # if management.parent != 0:
            #     api_data = ApiManagement.objects.filter(id=management.parent)
            #     for api in api_data:
            #         if api.parent != 0:
            #             api2_data = ApiManagement.objects.filter(id=api.parent)
            #             for api3 in api2_data:
            #                 if api3.parent != 0:
            #                     print("我没有父节点")
            #                 else:
            #                     print("**********3")
            #                     print(api3.name)
            #
            #         else:
            #             print("**********2")
            #             print(api.name)
            # else:
            #     print("******1")
            #     print(management.name)

        return response_success(api_management_list)


class ApiManagementJudgeView(View):

    def post(self, request, *args, **kwargs):
        """
        判断 父节点 是否可创建用例（只有用例节点才可创建用例）
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        body = request.body
        params = json.loads(body)
        try:
            api_management_data_a = ApiManagement.objects.get(id=params['service_id'])
        except ApiManagement.DoesNotExist:
            return response_failed(message="该节点无权限创建用例,请先创建项目节点")
        if api_management_data_a.parent == 0:
            return response_failed(message="该节点无权限创建用例,请先创建服务节点")

        else:
            api_management_data_b = ApiManagement.objects.get(id=api_management_data_a.parent)
            if api_management_data_b.parent == 0:
                return response_failed(message="该节点无权限创建用例,请先创建接口节点")
            else:
                return response_success()


class ApiManagementStructureDataEditView(View):

    def get(self, request, *args, **kwargs):
        """
        tree树结构更改 为二级目录，测试用例变更-8.23修改数据
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        api_management_data = ApiManagement.objects.filter(parent=0)

        api_management = []
        try:
            for api_management_tree in api_management_data:
                # 一级目录
                api_management_tree_data2 = ApiManagement.objects.filter(parent=api_management_tree.id)

                for api_management_tree_2 in api_management_tree_data2:
                    api_management_tree_data3 = ApiManagement.objects.filter(parent=api_management_tree_2.id)

                    # 二级目录
                    for api_management_tree_3 in api_management_tree_data3:
                        api_management_tree_data4 = ApiManagement.objects.filter(parent=api_management_tree_3.id)

                        # 三级目录
                        for api_management_tree_4 in api_management_tree_data4:
                            # 四级目录
                            apimanagement_updata = ApiManagement.objects.get(id=api_management_tree_4.id)
                            apimanagement_updata.parent = api_management_tree_2.id
                            apimanagement_updata.save()
                            # apimanagement_updata.objects.update(parent=api_management_tree_2.id)

        except Exception as e:
            print("************")
            pass

        return response_success(api_management)


class YaPiInterfaceBasicInformationView(View):

    def post(self, request, *args, **kwargs):
        """
        获取YAPI接口基本信息
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        body = request.body
        params = json.loads(body)
        api_management_data = ApiManagement.objects.filter(id=params['serviceId'])

        api = []

        for api_management in api_management_data:
            if api_management.yapi_id is None:
                api_dict = {
                    "yapi_api": 0
                }
                api.append(api_dict)
            else:
                api_yapi_server_data = ApiYapiServer.api_yapi_server_data(api_management.yapi_id)
                api_dict = {
                    "yapi_api": 1,
                    "api_interfaces_case_name": "",
                    "api_environment": "",
                    "api_documentation": api_yapi_server_data['api_documentation'],
                    "api_method": api_yapi_server_data['api_method'],
                    "api_url": api_yapi_server_data['api_url'],
                    "api_parameter_types": api_yapi_server_data['api_parameter_types'],
                    "api_parameter": api_yapi_server_data['api_parameter'],
                    "api_headers": api_yapi_server_data['api_headers'],
                    "api_parameter_body": api_yapi_server_data['api_parameter_body'],
                    "api_assert_type": 1
                }
                api.append(api_dict)

        return response_success(api)


class ApiYaPiInterfaceView(View):

    def put(self, request, *args, **kwargs):
        """
        创建接口-tree树-对接YaPi创建接口
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        body = request.body
        params = json.loads(body)

        server_data = ApiManagement.objects.filter(name=params['server_name'])
        if server_data.count() == 1:
            for api_server_data in server_data:
                ApiManagement.objects.create(name=params['api_name'], parent=api_server_data.id,
                                             yapi_id=params['yapi_id'])
        elif server_data.count() > 1:
            return response_failed(20000, message="服务名称重复,请查看数据")
        else:
            return response_failed(20000, message="请先创建服务")

        return response_success()

    def post(self, request, *args, **kwargs):
        """
        YAPI接口更新接口时间
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        body = request.body
        params = json.loads(body)

        server_data = ApiManagement.objects.filter(yapi_id=params['yap_id'])
        if server_data.count() == 1:
            for api_server_data in server_data:
                api_server_data.update_time = datetime.now()
                api_server_data.save()
            return response_success()
        elif server_data.count() > 1:
            return response_failed(20000, message="接口名id重复,请查看数据")
        else:
            return response_failed(20000, message="平台中暂无该接口id")
