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

from model_data_api.model.assertData_model import AssertDataManager
from model_data_api.handler.Base_Handler import BaseHandler
from model_data_api.views import *
from utils import JsonUtil
import pandas as pd
import json
app = app()

@app.route('/api/assertdata')
class AssertDataHandler(BaseHandler):
    def initialize(self):
        self.session = AssertDataManager()
        pass
    def on_finish(self):
        self.session.close()

    def post(self,*args,**kwargs):
        try :
            data = []
            if self.request.body:
                data = json.loads(str(self.request.body, encoding = "utf-8"))
            if data:
                _name =data['data_basic']['assert_name']
                if not self.session.find_single(_name):
                    _df = pd.DataFrame(data['data_detail'])
                    assert_type = _df.apply(lambda x : assert_value(x),axis=1)
                    msg = ','.join([i for i in assert_type.tolist() if i])
                    if msg:
                        self.write(JsonUtil.build_json_data(code=JsonUtil.Constants.Code_Param_Error,
                                                            msg=JsonUtil.Constants.Msg_Param_Error,
                                                            message = msg
                                                            ))
                    else:
                        _df_detail = pd.DataFrame(data['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)
                        data_detail = _df_detail.to_dict(orient='records')
                        self.session.create_obj(data['data_basic'],data_detail)
                        self.write(JsonUtil.build_json_data(code=JsonUtil.Constants.Code_Success,
                                                            msg=JsonUtil.Constants.Msg_Success,
                                                            message = "测试数据集创建成功"
                                                            ))
                else:
                    self.write(JsonUtil.build_json_data(code=JsonUtil.Constants.Code_Success,
                                                        msg=JsonUtil.Constants.Msg_Success,
                                                        message = "测试数据集已存在"
                                                        ))
                self.flush()
                self.finish()


            # if assert_name and assert_type:
            #     self.session.create_obj(assert_name=assert_name,assert_content=assert_content,
            #                             assert_value=assert_value,assert_type=assert_type)
            #
            #     self.write(JsonUtil.build_json(code=JsonUtil.Constants.Code_Success,
            #                                    msg=JsonUtil.Constants.Msg_Success
            #                                    ))
            #     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:
            id = self.get_argument('id',default=None)
            if id:
                result = self.session.find_single(id)
            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=code,
                                                msg=msg,
                                                result=result
                                                ))
            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['assert_type']
    _value = x['assert_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