# encoding: UTF-8
from ....common.sqlSession import SqlSession

from ..service.createDataResultService import CreateResultService
from ..service.createDataInfoService import CreateInfoService
from ..service.createDataDetailService import CreateDetailService
from ..service.createDataGroupService import CreateGroupService

from ..controller import commonController
from ..model.createResultInfo import CreateResult
from logger import logger
import json


class CreateDataResultController(object):
    def __init__(self, req_json, token):
        self.session = SqlSession()
        self.page = req_json.get('pageNo')
        self.limit = req_json.get('pageSize')
        self.create_data_result_id = req_json.get('create_data_result_id')
        self.create_data_info_id = req_json.get('create_data_info_id')
        self.create_data_detail_id = req_json.get('create_data_detail_id')
        self.team_name = req_json.get('team_name')
        self.file_name = req_json.get('file_name')
        self.module_name = req_json.get('module_name')
        self.class_name = req_json.get('class_name')
        self.method_name = req_json.get('method_name')
        self.tag = req_json.get('get_tag')
        self.status = req_json.get('status')
        self.method_function_detail = req_json.get('method_function_detail')
        self.detail_name = req_json.get('detail_name')
        self.request_parameter = req_json.get('request_parameter')
        self.result_info = req_json.get('result_info')
        self.creator = req_json.get('creator')
        self.email = req_json.get('email')
        self.token = token
        self.del_flag = 0
        self.req_json = req_json

    def create_result_data(self, add_data):
        """
        对造数结果进行新增
        :return:
        """
        add_data["del_flag"] = self.del_flag
        create_result_service = CreateResultService()
        create_data_info_id = create_result_service.create_result_data(session=self.session,
                                                                       create_info=add_data)
        return create_data_info_id

    def update_result_data(self, sid, status, result_info):
        """
        对返回结果进行编辑
        """
        edit_data = {'result_info': result_info, 'status': status}
        create_result_service = CreateResultService()
        err_msg = create_result_service.update_service_result_data(session=self.session, update_info=edit_data,
                                                                   sid=sid)
        if err_msg:
            return err_msg

    def get_method_request_parameter(self, create_data_info_id, request_param):
        """
        组装方法的请求参数
        :param parameter:
        :return:
        """
        # 定义请求的json
        json_data = {}
        # 查询抓取的请求参数信息
        create_info_service = CreateInfoService()
        get_data_info = create_info_service.get_create_data_info_by_id(session=self.session, sid=create_data_info_id)

        get_db_parameter = get_data_info.request_parameter
        # 判断如果请求参数里面含有**kwargs，组装请求
        if "is_kwargs" in get_db_parameter:
            json_data = request_param
        else:
            # 定义请求的json如果是json格式的参数，则组装json
            post_data_input = {}
            for key, value in request_param.items():
                if key in get_db_parameter.keys():
                    json_data[key] = value
                else:
                    post_data_input[key] = value
            if "post_data_input" in get_db_parameter:
                json_data["post_data_input"] = post_data_input
        return json_data

    def get_result_query_list(self):
        """
        结果列表页查询
        :return:
        """
        create_group_service = CreateGroupService()
        if self.page is None:
            self.page = 1
        if self.limit is None:
            self.limit = 10
        create_result_service = CreateResultService()
        common_controller = commonController.CommonController()
        get_group_data = create_group_service.get_service_group_info_data_by_email(self.session, email=self.email)
        filter_list = []
        team_name = self.team_name
        get_tag = self.tag
        detail_name = self.detail_name
        list_group_user = ["ALL"]
        if team_name:
            filter_list.append(CreateResult.team_name == team_name)
        if detail_name:
            filter_list.append(CreateResult.method_function_detail.like('%' + detail_name + '%'))
        if get_tag:
            filter_list.append(CreateResult.tag.like('%' + get_tag + '%'))

        if filter_list:
            if get_group_data:
                list_group_user.append(get_group_data.team_name)
            detail_list, total = create_result_service.get_result_list_by_team_filters_page(self.session, filter_list,
                                                                                            list_group_user,
                                                                                            self.page, self.limit)
        else:
            if get_group_data:
                list_group_user.append(get_group_data.team_name)
            detail_list, total = create_result_service.get_result_list_no_team_filters_page(self.session,
                                                                                            list_group_user, self.page,
                                                                                            self.limit)
        ret_ls = []
        for obj in detail_list:
            ret_ls.append({
                'create_data_result_id': obj.create_data_result_id,
                'create_data_info_id': obj.create_data_info_id,
                'create_data_detail_id': obj.create_data_detail_id,
                'team_name': common_controller.get_team_name(obj.team_name),
                'request_parameter': json.dumps(obj.request_parameter),
                'result_info': obj.result_info,
                'tag': obj.tag,
                'class_name': obj.class_name,
                'module_name': obj.module_name,
                'method_name': obj.method_name,
                'method_function_detail': obj.method_function_detail,
                'creator': obj.creator,
                'created_time': obj.created_time,
                'modified_time': obj.modified_time
            })
        return {"list": ret_ls, "total": total}

    def get_result_advance(self):
        """
        关键字造数结果详情页查询
        :return:
        """
        create_result_service = CreateResultService()
        get_data_result = create_result_service.get_create_result_by_id(session=self.session,
                                                                        create_data_result_id=self.create_data_result_id)
        create_detail_service = CreateDetailService()
        get_detail_info = create_detail_service.get_create_detail_info_by_id(session=self.session,
                                                                             create_data_detail_id=get_data_result.create_data_detail_id)

        common_controller = commonController.CommonController()
        try:
            is_json = True
            get_result = json.dumps(eval(get_data_result.result_info), ensure_ascii=False)
        except:
            is_json = False
            get_result = get_data_result.result_info
        _data = {'create_data_result_id': get_data_result.create_data_result_id,
                 'create_data_detail_id': get_data_result.create_data_detail_id,
                 'team_name': get_detail_info.team_name,
                 'file_name': common_controller.get_model_name(team=get_detail_info.team_name,
                                                               dict_key=get_detail_info.file_name),
                 'module_name': get_data_result.module_name,
                 'class_name': get_data_result.class_name,
                 'method_name': get_data_result.method_name,
                 'method_detail': get_detail_info.method_detail,
                 'request_parameter': get_data_result.request_parameter,
                 # 'method_function_detail': CreateDictData.query.filter_by(del_flag=0, data_type=2,
                 #                                                          dict_key=get_detail_info.method_name).first().dict_value,
                 'method_function_detail': get_detail_info.method_function_detail,
                 'result_info': get_result,
                 'creator': get_data_result.creator,
                 'get_tag': get_data_result.tag,
                 'is_json': is_json,
                 'created_time': get_data_result.created_time,
                 'modified_time': get_data_result.modified_time}

        return _data
