from aiohttp import web

from app import config
from app.Vendor.Utils import Utils
from app.Vendor.Log import log
from app.Vendor.Code import Code 
import json


class ReturnData:

    '''
    * 返回Json数据
    * @param  obj request
    * @param  dict body
    * @return json
    '''
    @staticmethod
    async def json(request, body={}):
        if (config['app']['debug_log']):
            debug_id = Utils.unique_id()
            #这边修改成json格式接收参数
            if request.method == 'GET':
                reqMultiDictValue = request.query
            if request.method == 'POST':
                if  request.content_type == 'application/json':
                    reqMultiDictValue = json.loads(str(await request.content.read(), encoding="utf-8"))
                elif request.content_type == 'application/x-www-form-urlencoded' or request.content_type == 'multipart/form-data':
                    reqMultiDictValue = await  request.post()
            reqVal = {}
            for (k,v) in reqMultiDictValue.items():
                reqVal[k] = v        
            log().debug(
                json.dumps({
                    'LOG_ID': debug_id,
                    'IP_ADDRESS': request.remote,
                    'REQUEST_URL': request.url.path,
                    'REQUEST_METHOD': request.method,
                    'PARAMETERS': reqVal,
                    'RESPONSES': body
                }))
        body['debug_id'] = debug_id
        return web.json_response(body)

    '''
    * 返回错误信息
    * @param  dict req
    * @param  msg  string
    * @param  code int
    * @return json
    '''
    @staticmethod
    async def error(req ,msg='', code=Code.BAD_REQUEST, show=True):
        return await ReturnData.json(req, {'code': code, 'error': True, 'msg': msg, 'show': show})

    '''
    * 返回成功信息
    * @param  dict req
    * @param  msg string
    * @return json
    '''
    @staticmethod
    async def success(req, data='', msg='', show=True):
        return await ReturnData.json(req, {'code': Code.SUCCESS, 'data': data,'msg': msg, 'show': show})
