#!/usr/bin/python
# encoding:utf-8

from curses import nocbreak
import sys

from tornado import gen
from tornado.web import RequestHandler
from tornado.escape import json_decode, json_encode, utf8
import json, simplejson


class BaseHandler(RequestHandler):
    """解决JS跨域请求问题"""

    def set_default_headers(self):
        # 设置允许请求的方法
        self.set_header('Access-Control-Allow-Methods', 'POST, DELETE, PUT, GET, OPTIONS')

        # Tornado获取请求'origin'的方法
        origin = self.request.headers.get('Origin', '')

        # 设置允许的'origin'，只设置'*'时某些特定情况下会失败故最好优先获取请求的域加入允许组中
        self.set_header('Access-Control-Allow-Origin', origin or "*")

        # 设置是否允许客户端携带证书式访问。通过对 Credentials 参数的设置，就可以保持跨域 Ajax 时的 Cookie
        self.set_header('Access-Control-Allow-Credentials', 'true')

        self.set_header('Access-Control-Allow-Headers', '*')

        self.set_header("Access-Control-Max-Age", 1000)
        self.set_header("Content-type", "application/json")

    # vue一般需要访问options方法， 如果报错则很难继续，所以只要通过就行了，当然需要其他逻辑就自己控制。因为vue访问时，会先执行一次预加载，直接放过就好了
    def options(self):
        # 返回方法1
        self.set_status(204)  # 这里的状态码一定要设置200，建议
        self.finish()

    def get_post_data(self, *params):
        post_data = self.request.body_arguments
        post_data = {x: post_data.get(x)[0].decode("utf-8") for x in post_data.keys()}
        if not post_data:
            post_data = self.request.body.decode('utf-8')
            post_data = simplejson.loads(post_data)

        print("post_data", post_data)

        valus = {}
        msg = ''
        for key in params:
            if key in post_data:
                valus[key] = post_data[key]
            else:
                msg = key + ' not found'
                break

        return msg, valus

    def get_get_data(self, *params):
        valus = {}
        msg = ''
        for key in params:
            value = self.get_argument(key, None)
            if value != None:
                valus[key] = value
            else:
                msg = key + ' not found'
                break

        return msg, valus

    def error(self, code, msg):
        result = {
            'status': False,
            'code': code,
            'msg': msg
        }
        self.write(json_encode(result))

