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

import pandas as pd
from utils import JsonUtil
from utils.tools import *
import datetime
import json
import hashlib

def add_models_logic(session,models_name,content=None,create_name=None,el_expression=None):
    """创建模型"""
    if models_name:
        if not session.find_single(models_name):
            session.create_obj(models_name, content,create_name,el_expression)
            return {'result':[],'code':JsonUtil.Constants.Code_Success, 'message':JsonUtil.Constants.Msg_Success}
        else:
            return {'result':[],'code':JsonUtil.Constants.Code_Success, 'message':JsonUtil.Constants.Msg_Success_ParamsIn}
    return {'result':None,'code':JsonUtil.Constants.Code_Param_Error, 'message':JsonUtil.Constants.Msg_Param_Error}


def get_models_logic(session,models_name = None):
    """获取模型信息"""
    if not models_name:
        result = session.find_all()
    else:
        result = session.find_single(models_name)
    if result:
        df = pd.DataFrame(result)
        df['create_at'] = df['create_at'].astype(str)
        df['update_at'] = df['update_at'].astype(str)
        result = df.to_dict(orient = 'records')
        return {'result':result,'code':JsonUtil.Constants.Code_Success,'message':JsonUtil.Constants.Msg_Success}
    else:
        return {'result':result,'code':JsonUtil.Constants.Code_Success,'message':JsonUtil.Constants.Msg_Success_ParamsNot}

def add_features_logic(session,data=None):
    """添加特征信息"""
    if data:
        data_detail = None
        for v in data:
            if v['assert_name'] and v['feature_name']:
                # l_featrue = session.find_single(v['feature_name'])
                data_detail = session.find_single_assert(v['assert_name'])
                # if data_detail
                #     if l_featrue :
                #         session.update_obj(feature_name = v['feature_name'])
                # else:
                #     return {'result':None,'code':JsonUtil.Constants.Code_Param_Error,'message':JsonUtil.Constants.Msg_Param_Assert_Error}

        if data_detail:
            _df_detail = pd.DataFrame(data_detail)
            _df_detail.loc[_df_detail['data_type'].isnull(),'data_type'] = 0
            if 'data_round' not in _df_detail.columns.tolist():
                _df_detail['data_round'] = 0
            else:
                _df_detail.loc[_df_detail['data_round'].isnull(),'data_round'] = 0
            _df_detail.loc[_df_detail['assert_value'].isnull(),'assert_value'] = None
            _df_detail['data_type'] = _df_detail['data_type'].astype(int)
            _df_detail['data_round'] = _df_detail['data_round'].astype(int)
            _df_data = pd.DataFrame(data)
            _df_mer = pd.merge(_df_data,_df_detail,on='assert_name')
            _data = _df_mer.to_dict(orient='records')
            session.create_obj(_data)
            return {'result':_data,'code':JsonUtil.Constants.Code_Success,'message':JsonUtil.Constants.Msg_Success}
    else:
        return {'result':data,'code':JsonUtil.Constants.Code_Param_Error,'message':JsonUtil.Constants.Msg_Param_Error}

def get_features_logic(session,feature_name):
    """获取特征信息"""
    if feature_name:
        result = session.find_single(feature_name)
    else:
        # result = session.find_all()
        return  {'result':None,'code':JsonUtil.Constants.Code_Param_Error,'message':JsonUtil.Constants.Msg_Param_Error}

    if result:
        df = pd.DataFrame(result)
        df['create_at'] = df['create_at'].astype(str)
        df['update_at'] = df['update_at'].astype(str)
        result = df.to_dict(orient = 'records')
        return  {'result':result,'code':JsonUtil.Constants.Code_Success,'message':JsonUtil.Constants.Msg_Success}
    return  {'result':None,'code':JsonUtil.Constants.Code_Success,'message':JsonUtil.Constants.Msg_Success_ParamsNot}

def set_modelsAndfeature_logic(session,data = None):
    """设置模型和特征挂钩"""
    if isinstance(data,dict):
        if data:
            if 'data_basic' in data.keys() and 'data_detail' in data.keys():
                session.create_obj(data['data_basic'],data['data_detail'])
                return {'result':[],'code':JsonUtil.Constants.Code_Success,'message':JsonUtil.Constants.Msg_Success}

    return {'result':None,'code':JsonUtil.Constants.Code_Param_Error,'message':JsonUtil.Constants.Msg_Param_Structure_Error}

def create_dataSet_logic(session,model_name,common):
    """生成测试数据,创建测试数据目录备份测试数据文件"""
    if model_name:
        _json = session.find_single_FeatureData(model_name)
    if not _json:
        return  {'result':None,'code':JsonUtil.Constants.Code_Param_Error,'message':JsonUtil.Constants.Msg_Param_Data_Error,'model_id':None}
    else:
        model_name = _json['model_name']
        model_id = _json['model_id']
        count = _json['user_count']
        _df_json = pd.DataFrame(_json['data'])
        feature_name = list(set(_df_json['feature_name']))
        result = {}
        for k ,v in _df_json.groupby('feature_name'):
            _df = pd.DataFrame(v)
            _df.sort_values(by=['feature_gdp','id'],inplace=True,ascending=False)

            _df['user_count'] = round(count*_df['feature_gdp']/100,0)
            _count_sum = _df['user_count'].astype(int).tolist()
            _diff = sum(_count_sum) - count
            _id = _df['id'].tolist()
            _gdp = _df['feature_gdp'].tolist()
            _type = _df['feature_type'].tolist()
            _value = _df['feature_value'].tolist()
            _data_type = _df['data_type'].tolist()
            _data_round = _df['data_round'].tolist()

            # _gdp = sorted(_gdp,reverse=True)
            # _gdp_num = set_allocation_num(_gdp,_json['count'])

            if _diff >0:
                _df['user_count'] = lst_Covering( _df['user_count'].tolist(),_diff,istrue=False)
            elif _diff < 0:
                _df['user_count'] = lst_Covering( _df['user_count'].tolist(),abs(_diff))
            _gdp_num = _df['user_count'].tolist()

            _result  = get_array(_id,_gdp_num,_type,_value,_data_type,_data_round)
            result[k] = _result
        print('1----')
        _path ,_tree,_treeDetail = create_suiteFile(common,model_name,datetime.datetime.now())
        _data = os.path.join(_treeDetail['path'],_treeDetail['name'][0],'data_%s.json'%(model_name))
        _detail = os.path.join(_treeDetail['path'],_treeDetail['name'][1],'detail_%s.json'%(model_name))



        with open(os.path.join(_path,_data), 'w',encoding='utf8') as f:
            f.write(json.dumps(_json,indent=4,ensure_ascii=False))
            f.close()
            print("汇总写入完成...")

        with open(os.path.join(_path,_detail), 'w',encoding='utf8') as f:
            f.write(json.dumps(result,indent=4,ensure_ascii=False))
            f.close()
            print("明细写入完成...")



        session.create_obj_single(model_id=int(model_id),model_name=model_name,
                                       user_count = count,feature_name = ','.join(feature_name),
                                       report_type = 1,data_path = _data)

        session.create_obj_single(model_id=int(model_id),model_name=model_name,
                                       user_count = count,feature_name = ','.join(feature_name),
                                       report_type = 2,data_path = _detail)

        data_set_datail_id_list = session.find_single(model_name=model_name,data_path=_detail,report_type = 2)
        data_set_datail_id = None
        if data_set_datail_id_list:
            data_set_datail_id = data_set_datail_id_list[0]['id']
        return {'result':{'data_path':_path , 'detail_path':_detail,'model_id':model_id,'data_set_datail_id':data_set_datail_id},

                'code':JsonUtil.Constants.Code_Success,'message':JsonUtil.Constants.Msg_Success}


def add_userTest_logic(session,file_path,common,count,isTrue=True):
    result = {}
    if file_path:
        with open(get_path(common,'suite',file_path), 'r',encoding='utf8') as f:
            result = json.loads(f.read())
            f.close()

    _df_result = pd.DataFrame(result)
    _df_result['result'] = _df_result.apply(lambda x : get_change(x),axis=1)
    _df_result['batch_uuid'] = None
    if not isTrue:
        _df_result['batch_uuid']  = _df_result['batch_uuid'] .apply(lambda x : hashlib.md5(str(datetime.datetime.now()).encode(encoding='UTF-8')).hexdigest())
    else:
        uuid_path=get_path(common,'DATA','uuid1.csv')
        temp_uuid=pd.read_csv(uuid_path,encoding='utf-8')['uuid']
        _df_result['batch_uuid']=temp_uuid[:int(count)]
        # print('uuid==',_df_result['batch_uuid'])
        # print(len(result))
        # print(len(result))

    batch_uuid = _df_result['batch_uuid'].tolist()
    data_detail = _df_result['result'].tolist()

    set_detail = session.find_single_model(file_path)
    session.create_obj_all(set_detail['id'],set_detail['model_name'],batch_uuid,data_detail)
    return {'result':[],'code':JsonUtil.Constants.Code_Success,'message':JsonUtil.Constants.Msg_Success,'set_datail_id':set_detail['id']}

def get_userTest_logic(session,model_name,data_set_datail_id):
    result = session.find_single_data_set_datail_id(model_name,data_set_datail_id)
    if result:
        return {'result':result,'code':JsonUtil.Constants.Code_Success,'message':JsonUtil.Constants.Msg_Success}
    else:
        return {'result':result,'code':JsonUtil.Constants.Code_Param_Error,'message':JsonUtil.Constants.Msg_Param_Data_Error}
