# -*- coding:utf-8 -*-
from model_data_api.model.featureData_model import FeatureDataManager
from model_data_api.handler.Base_Handler import BaseHandler
from model_data_api.views import *
from model_data_api.handler.logic import *
import pandas as pd
import json

app = app()
@app.route('/api/feature')
class FeatureDataHandler(BaseHandler):
    def initialize(self):
        self.session = FeatureDataManager()
        pass
    def on_finish(self):
        self.session.close()

    def post(self,*args,**kwargs):
        """
            [{"feature_name":"f1","feature_content":"测试使用","assert_name":"模型测试"}]
        """
        try :
            data = []
            if self.request.body:
                data = json.loads(str(self.request.body, encoding = "utf-8"))

            result = add_features_logic(self.session,data)
            self.write(JsonUtil.build_json_data(code=result['code'],
                                                message=result['message'],
                                                result = result['result'],
                                                data = data
                                                ))
            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 get(self, *args, **kwargs):

        try:
            feature_name = self.get_argument('feature_name',default=None)

            result = get_features_logic(self.session,feature_name)
            # if feature_name:
            #     result = self.session.find_single(feature_name)
            # else:
            #     result = self.session.find_all()
            # 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')
            #     code = JsonUtil.Constants.Code_Success
            #     msg = JsonUtil.Constants.Msg_Success
            #
            # else:
            #     code = JsonUtil.Constants.Code_Result_Error
            #     msg = JsonUtil.Constants.Msg_Result_Error

            self.write(JsonUtil.build_json_data(code=result['code'],
                                                message=result['message'],
                                                result=result['result'],
                                                feature_name = feature_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 Exception as e:
            # == 报异常，查询失败
            self.write(JsonUtil.build_json(JsonUtil.Constants.Code_Error, JsonUtil.Constants.Msg_Error))
            self.flush()



def assert_value(x):
    _type = x['feature_type']
    _value = x['feature_value']
    _error = ''
    if _type == '区间':
        try:
            int(x['data_type'])
        except:
            _error += "value :"+str(_value)+ " 是区间值,需要设置类型(data_type); "
        else:
            try :
                if x['data_type'] == 2:
                    int(x['data_round'])
            except:
                _error = _error.join("value :"+str(_value)+ " 小数区间,需要设置小数位数(data_type); ")
    if _error != '' :
        return _error
