#!/usr/bin/env python
# -*- coding:utf-8 -*-

import requests, json
from common.base import Config
from common.error import *
from other_url import OtherUrl
from common.log.loger import Logger

try:
    logDict = Config().get_content("log")
    logPath = logDict['logpath']
    logName = logDict['logname']

except Exception as e:
    logPath = None
    logName = None
my_log = Logger(filepath=logPath, filename=logName)


# 这个接口是权限接口， 分析时候调用的
def analysis_info(UserID, TokenID, TeamID, MessageCondition):
    SubURL = Config().get_content("permissionSystem")['permissionurl']

    URI = OtherUrl.permissionGetSampleInfoMaxUrl
    URL = SubURL + URI
    # -----<得到前端的信息>----- #
    data = {}

    data["TeamID"] = TeamID
    data["UserId"] = UserID
    data["TokenId"] = TokenID

    ret = requests.post(URL, data=data)

    verification_ret_data = ret.text
    verification_ret_data = json.loads(verification_ret_data)

    if int(verification_ret_data["status"]) != 0:
        raise ValueError

    new_sample_li = []
    for i in verification_ret_data["list"]:
        """
            CasesCondition : [{"WhereSubVarName": ID, "WhereSubSymbol": '>', "WhereSubValue": "", "WhereSubType": "INT"}]
            "WhereSubType": ("FLOAT", "VARCHAR", "DATETIME", "INT", "DATE")
        """
        new_sub_sample_dict = {}
        new_sub_sample_dict["WhereSubVarName"] = i["Key"]
        new_sub_sample_dict["WhereSubSymbol"] = i["Operator"]
        new_sub_sample_dict["WhereSubType"] = i["Type"]
        new_sub_sample_dict["WhereSubValue"] = i["Value"]
        new_sub_sample_dict["SampleVariable"] = i["SampleNo"]
        new_sample_li.append(new_sub_sample_dict)

    sort_new_sample_li = sorted(new_sample_li, key=lambda x: x["WhereSubVarName"])

    sort_new_messagecondition_li = MessageCondition if MessageCondition == [{}] else sorted(MessageCondition,
                                                                                            key=lambda x: x[
                                                                                                "WhereSubVarName"])

    sort_new_messagecondition_li2 = []
    for i in sort_new_messagecondition_li:
        """
            CasesCondition : [{"WhereSubVarName": ID, "WhereSubSymbol": '>', "WhereSubValue": "", "WhereSubType": "INT"}]
            "WhereSubType": ("FLOAT", "VARCHAR", "DATETIME", "INT", "DATE")
        """
        sort_new_sub_sample_dict = {}
        sort_new_sub_sample_dict["WhereSubVarName"] = i["WhereSubVarName"]
        sort_new_sub_sample_dict["WhereSubSymbol"] = i["WhereSubSymbol"]
        sort_new_sub_sample_dict["WhereSubType"] = i["WhereSubType"]
        sort_new_sub_sample_dict["WhereSubValue"] = i["WhereSubValue"]
        sort_new_sub_sample_dict["SampleVariable"] = i["SampleVariable"]
        sort_new_messagecondition_li2.append(sort_new_sub_sample_dict)

    my_log.info(sort_new_sample_li)
    my_log.info(sort_new_messagecondition_li2)

    all_data_messagecondition = [
        {'SampleVariable': '', 'WhereSubSymbol': '=', 'WhereSubType': 'INT', 'WhereSubVarName': '1',
         'WhereSubValue': '1'}]

    if not [False for i in sort_new_sample_li if i not in sort_new_messagecondition_li2] or not [False for i in
                                                                                                new_sample_li if
                                                                                                i not in all_data_messagecondition]:
        # if sort_new_sample_li in sort_new_messagecondition_li or new_sample_li in all_data_messagecondition:
        return 1
    else:
        return 0


def verification_infor(UserID, TokenID, ProjectID, MessageCondition, QuesID=None, TeamID=None):
    status = 2000

    MessageCondition = [{'WhereSubType': 'INT', 'WhereSubVarName': '1', 'SampleVariable': '', 'WhereSubSymbol': '=',
                         'WhereSubValue': '1'}] if MessageCondition == [{}] else MessageCondition

    URL = Config().get_content("GetSampleInfo")["getsampleinfourl"]

    # -----<得到前端的信息>----- #
    data = {}
    data["ProjectID"] = ProjectID if ProjectID else ""

    if QuesID:
        data["TeamID"] = QuesID
    else:
        # data["TeamID"] = MessageCondition[0]["TeamID"]
        data["TeamID"] = TeamID

    # data["TeamID"] = "2024407994241625200453414922"
    # data["TeamName"] = MessageCondition[0]["TeamName"]
    data["UserId"] = UserID
    data["TokenId"] = TokenID

    # project_is_public = SelectProjectIsPublic(TeamID)["ProjectPublic"]
    #
    # data["isOpen"] = project_is_public

    ret = requests.post(URL, data=data)

    verification_ret_data = ret.text
    # print(verification_ret_data)
    verification_ret_data = json.loads(verification_ret_data)
    if int(verification_ret_data["status"]) != 0:
        raise ValueError

    sample_data = []

    for i in verification_ret_data["teamlist"]:
        # -----<得到具体的权限列表【{}， {}】>----- #
        sample_data += i["SampleList"]
        # if i["TeamID"] == data["TeamID"]:
        #     sample_data = i["SampleList"]
        # else:
        #     continue
    new_sample_li = []
    for i in sample_data:
        """
            CasesCondition : [{"WhereSubVarName": ID, "WhereSubSymbol": '>', "WhereSubValue": "", "WhereSubType": "INT"}]
            "WhereSubType": ("FLOAT", "VARCHAR", "DATETIME", "INT", "DATE")
        """
        new_sub_sample_dict = {}
        new_sub_sample_dict["WhereSubVarName"] = i["Key"]
        new_sub_sample_dict["WhereSubSymbol"] = i["Operator"]
        new_sub_sample_dict["WhereSubType"] = i["Type"]
        new_sub_sample_dict["WhereSubValue"] = i["Value"]
        new_sub_sample_dict["SampleVariable"] = i["SampleNo"]
        new_sample_li.append(new_sub_sample_dict)

    # print("sample_data", new_sample_li)
    # print(MessageCondition)

    sort_new_sample_li = sorted(new_sample_li, key=lambda x: x["WhereSubVarName"])
    sort_new_messagecondition_li = sorted(MessageCondition, key=lambda x: x["WhereSubVarName"])
    all_data_messagecondition = [
        {'SampleVariable': '', 'WhereSubSymbol': '=', 'WhereSubType': 'INT', 'WhereSubVarName': '1',
         'WhereSubValue': '1'}]
    set_messagecondition_li = []
    for i in sort_new_messagecondition_li:
        if i not in set_messagecondition_li:
            set_messagecondition_li.append(i)

    if sort_new_sample_li == set_messagecondition_li or new_sample_li == all_data_messagecondition:
        return 1
    else:
        return 0


def public_where_data(Public=1):
    if Public == 1:
        public = " True "
    elif Public == 2:
        public = ' mq.QuesPublic = 2 '
    elif Public == 3:
        public = " mq.QuesPublic = 2 AND mp.ProjectPublic=2 "
    else:
        raise ValuePropagetionError
    return public


def getQuesFileList(UserID, TokenID, QuesID):
    subURL = Config().get_content("permissionSystem")["permissionurl"]
    subURL = subURL if subURL[-1] == '/' else subURL + '/'
    URL = subURL + OtherUrl.permissionQuesFileUrl
    data = {
        "UserId": UserID,
        "TokenId": TokenID,
        "TeamID": QuesID
    }
    ret = requests.post(URL, data)
    res_data = json.loads(ret.text)
    if ret.status_code == 200 and res_data["status"] == 0:
        if res_data["isManager"] == True:
            return 1
        else:
            fileIDList = []
            for i in res_data["list"]:
                fileIDList.append(i["FileID"])
    else:
        raise PermissionNotError
    return fileIDList


def getProjectOrQuesList(UserID, TokenID, TeamID):
    subURL = Config().get_content("permissionSystem")["permissionurl"]
    subURL = subURL if subURL[-1] == '/' else subURL + '/'
    URL = subURL + OtherUrl.permissionProjectOrQuesUrl
    data = {
        "UserId": UserID,
        "TokenId": TokenID,
        "TeamID": TeamID
    }
    ret = requests.post(URL, data)
    res_data = json.loads(ret.text)
    if ret.status_code == 200 and res_data["status"] == 0:

        return True
    else:
        return False


def getProjectList(UserID, TokenID):
    subURL = Config().get_content("permissionSystem")["permissionurl"]
    subURL = subURL if subURL[-1] == '/' else subURL + '/'
    URL = subURL + OtherUrl.permissionObtainTeamsUrl
    data = {
        "UserId": UserID,
        "TokenId": TokenID,
    }
    ret = requests.post(URL, data)
    res_data = json.loads(ret.text)
    if ret.status_code == 200 and res_data["status"] == 0:
        projectIDList = []
        for i in res_data["list"]:
            projectIDList.append(i["ProjectID"])

    else:
        raise PermissionNotError
    return projectIDList


def getExistsDownUrlList(UserID, TokenID, FileOrTeamID, Flag=0, DataID=None):  # TokenId，UserId，FileID
    subURL = Config().get_content("permissionSystem")["permissionurl"]
    subURL = subURL if subURL[-1] == '/' else subURL + '/'
    URL = subURL + OtherUrl.permissionExistsDownUrl
    data = {
        "UserId": UserID,
        "TokenId": TokenID,
    }
    if Flag == 0:
        data["FileID"] = FileOrTeamID
    elif Flag == 1:
        if DataID:
            data["DataID"] = DataID
        data["TeamID"] = FileOrTeamID
    ret = requests.post(URL, data)
    res_data = json.loads(ret.text)
    '''
        0（允许下载）
        -1（不允许）
        131（需要完善个人信息）
        132（线上审核后线上下载）
        133（线上审核后邮件发送）
        134（仅供分析探索不提供原始数据）
    '''
    if Flag == 0:
        return res_data["list"], res_data["status"]
    else:
        if ret.status_code == 200 and res_data["status"] == 0:
            return 0
        else:
            return res_data["status"]


if __name__ == '__main__':
    TokenID = "4Qff6xGquoGETFhr03fY1cstTWwJt3LVBVpYYb7y9Fo=",
    UserID = "2023435091200870221887631042",
    TeamID = "2018081709245929810268640601"
    data = analysis_info(UserID, TokenID, TeamID, '')
