
from model_data_api.handler.Base_Handler import BaseHandler
from model_data_api.model.dataSetDetail_model import DataSetDetailManager
from model_data_api.views import *
from model_data_api.handler.logic import *

app = app()

@app.route('/api/datasetDetail')
class DatadetailHandler(BaseHandler):
    """获取数据明细 和 创建明细数据"""
    def initialize(self):
        self.session = DataSetDetailManager()

    def get(self,*args,**kwargs):
        try:
            model_name = self.get_argument('model_name',default=None)
            if model_name:
                result = self.session.find_single(model_name = model_name)
                if result:
                    df = pd.DataFrame(result)
                    df['create_at'] = df['create_at'].astype(str)
                    df['update_at'] = df['update_at'].astype(str)
                    df['file_name'] = df['data_path'].apply(lambda x: "".join(x.split('/')[-1:]))
                    result = df.to_dict(orient = 'records')
            else:
                result = self.session.find_all()

            if result:
                self.write(JsonUtil.build_json_data(code=JsonUtil.Constants.Code_Success,
                                                    msg=JsonUtil.Constants.Msg_Success,
                                                    result = result
                                                    ))
            else:
                self.write(JsonUtil.build_json_data(code=JsonUtil.Constants.Code_Result_Error,
                                                    msg=JsonUtil.Constants.Msg_Result_Error
                                                    ))
            self.flush()
            self.finish()

        except ValueError as e:
            self.write(JsonUtil.build_json(JsonUtil.Constants.Code_Param_Error, JsonUtil.Constants.Msg_Param_Error))
            self.flush()

        except Exception as e:
            # == 报异常，查询失败
            self.write(JsonUtil.build_json(JsonUtil.Constants.Code_Error, JsonUtil.Constants.Msg_Error))
            self.flush()

    def post(self,*args,**kwargs):
        try:
            # data = self.request.body_arguments
            model_name = self.get_argument('model_name',default=None)
            result = create_dataSet_logic(self.session,model_name,common)



            self.write(JsonUtil.build_json_data(code=result['code'],
                                                message=result['message'],
                                                result=result['result'],
                                                model_name = model_name
                                                ))
            self.flush()
            self.finish()

        except ValueError as e:
            self.write(JsonUtil.build_json(JsonUtil.Constants.Code_Param_Error, JsonUtil.Constants.Msg_Param_Error))
            self.flush()
        except IOError as e:
            self.write(JsonUtil.build_json(JsonUtil.Constants.Code_File_Error, JsonUtil.Constants.Msg_File_Error))
            self.flush()
        except Exception as e:
            # == 报异常，查询失败
            self.write(JsonUtil.build_json(JsonUtil.Constants.Code_Error, JsonUtil.Constants.Msg_Error))
            self.flush()



def lst_Covering(lst,num,istrue=True):
    index = 0
    while num>0:
        if istrue:
            lst[index] +=1
        else:
            # print(num,index,lst[index])
            lst[index] -=1
        index+=1
        num = num-1
        if index >= len(lst):
            index = 0
    return lst

def set_allocation_num(gdp,count):
    """分配"""
    res = []
    for i in gdp:
        res.append(round(count*i/100))
    _sum = sum(res)
    if _sum > count:
        _temp = _sum - count
        res = sorted(res,reverse = True)
        res = lst_Covering(res,_temp,False)
    elif _sum < count:
        _temp = count - _sum
        res = sorted(res)
        res = lst_Covering(res,_temp)
    return res

def get_array(name,gdp,type,value,dataType,dataRound):
    lst = []
    for i,(g,t,v,dt,dr) in enumerate(zip(gdp,type,value,dataType,dataRound)):
        temp = [name[i]] * int(g)
        for _t,_temp in enumerate(temp):
            if t=='区间':
                if dt:
                    if v:
                        _v = v.replace('-',',').split(',')
                        if dt == 1:
                            _data = np.random.randint(eval(_v[0]),eval(_v[1])+1)
                        elif dt == 2:
                            _data = round(np.random.uniform(eval(_v[0]),eval(_v[1])),dr)
                    elif dt == 3:
                        _r = np.random.randint(0,2)
                        if _r == 0:
                            _data = np.random.randint(-1000,1000000)
                        elif _r == 1:
                            _data = round(np.random.uniform(-1000,1000000),6)
                    temp[_t] = _data
            elif t == '正数':
                temp[_t] = int(v)
            elif t == '异常空值':
                temp[_t] = eval(v)
            elif t == '字符串':
                temp[_t] = str(v)
        lst.extend(temp)
    random.shuffle(lst)
    return lst
