# -*- coding:utf-8 -*-

'''
json 组装
'''
import json
import pandas as pd

## 常数变量定义
## json 返回中的 错误码定义
class Constants:
    Code_Success = 200
    Msg_Success = 'SUCCESS'
    Msg_Success_ParamsIn = "数据已存在"
    Msg_Success_ParamsNot = '未查询到数据'


    Code_Fail = 1
    Msg_Fail = '失败'

    Code_Param_Error = -1
    Msg_Param_Error = '参数错误'
    Msg_Param_Assert_Error = "校验集不存在"
    Msg_Param_Structure_Error = "入参结构体错误"
    Msg_Param_Data_Error = "数据不存在"


    Code_LoginToken_Auth_Error = -2
    Msg_LoginToken_Auth_Error = 'token登陆认证错误'

    Code_Error = -3
    Msg_Error = '数据异常'

    Code_Params_Error = -4
    Msg_Params_Error = '{0} is error,{0} is {1}'

    Code_File_Error = -5
    Msg_File_Error = "文件读写操作异常"


    Code_Query_Fail = 4
    Msg_Query_Fail = '数据库连接失败'
    Msq_Query_Witer_Error = "数据写入有错"

    # Code_Query_Empty = 5
    # Msg_Query_Empty = '数据为空'

    Code_Error_Value = 506
    Msg_Error_Value = '没找到指定参数的返回值'





def build_json_data(code=None,message=None,result =None,**kwargs):

    if result == None:
        result = []

    body = {}
    for key,value in kwargs.items():
        body[str(key)] = value
    try :
        data = {'result':result}
        ddata = {'code':code,'message':message,'data':dict(dict(subInfo = body),**data)}
    except Exception as e:
        print(e.args)

    return json.dumps(ddata,ensure_ascii=False)

# businessType=int(_business_type), orderId=_orderId, loanId=_loanId,uuid = _uuid,
# data=_result, flag=True)
#
# def build_json_feature (features=None, code=Constants.Code_Success, msg=Constants.Msg_Success):
#
#     if data == None:
#         data = []
#     ddata = dict(code=code, businessCode=code, msg=msg, features=features)

def build_json_feature_two(data):
    return json.dumps(data,ensure_ascii=False)

"""
只返回 错误码 + 错误提示
"""
def build_json(code, msg):
    ddata = dict(code=code, msg=msg)
    # return json.dumps(ddata,encoding='UTF-8',ensure_ascii=False) #python2
    return json.dumps(ddata, ensure_ascii=False)  # python3


"""
错误码 默认为 成功；
data may be dict array
"""


def build_json_with_data(data=None, code=Constants.Code_Success, msg=Constants.Msg_Success,message=None):
    if data == None:
        data = []
    ddata = dict(code=code, businessCode=code, msg=msg,message=message, data=data)
    # return json.dumps(ddata,encoding='UTF-8',ensure_ascii=False) # python2
    return json.dumps(ddata, ensure_ascii=False)  # python3


def build_json_with_data_page(data=None, total=0, page_no=1, page_size=20, code=Constants.Code_Success,
                              msg=Constants.Msg_Success):
    page_no = int(page_no)
    page_size = int(page_size)
    total = int(total)
    if total % page_size == 0:
        _page_total = total / page_size
    else:
        _page_total = total / page_size + 1
    # ==没有查询到数据，则data 为空
    if total == 0:
        data = []
    _data = dict(data=data, page_no=int(page_no), page_size=int(page_size), page_total=int(_page_total),
                 total=int(total))
    ddata = dict(code=code, businessCode=code, msg=msg, data=_data)
    # return json.dumps(ddata,encoding='UTF-8',ensure_ascii=False) # python2
    return json.dumps(ddata, ensure_ascii=False)  # python3


def build_json_with_block(data=None, code=Constants.Code_Success, msg=Constants.Msg_Success):
    ddata = dict(code=code, businessCode=code, msg=msg, data=data)
    # return json.dumps(ddata,encoding='UTF-8',ensure_ascii=False) # python2
    return json.dumps(ddata, ensure_ascii=False)  # python3


"""
转换为 dict 对象; 直接 json.key 获取数据
如果data 为空，返回一个空的data数据
"""


def str_parse_json(data):
    if any(data):
        return json.loads(data, encoding='UTF-8')
    return dict()


def build_json_models(data):
    import hashlib
    def get_change(x):
        _dict = {
            "code": 200,
            "data": {"features": None}
        }
        _list = {}
        for key ,value in zip(x.keys(),x.values):
            _list = dict(_list, **{key:{'state':200,'value':value}})
        _dict['data']['features'] = _list
        return _dict
    _df = pd.DataFrame(data['result'])
    _df['result'] = _df.apply(lambda x : get_change(x),axis=1)
    _df.reset_index(inplace = True)
    _df['batchUuid']  = _df['index'].apply(lambda x : hashlib.md5(str(x).encode(encoding='UTF-8')).hexdigest())
    del _df['index']
    _json = _df.to_dict(orient='records')
    return _json