# -*- coding: utf-8 -*-
import json
# from auth import AuthenticationController, Sign
from lib.oauth import Sign,OAuth2SessionManager
from cacheout import LFUCache
from furl import furl
from torndsession.sessionhandler import SessionBaseHandler
from src.object import LaneSoftwareMsg
from log import app_log

logger = app_log(__name__)

cache = LFUCache()
P1 = "167B73291C3E60979B5CEE5FD9E8FABC3D2B02D6A5D945241C01C62748C8E055"
P2 = "1DFB4C642898B2EF3027719DF46FEED85C7862403D3BB223BAB8E8D2ED32098F0B55A05B5BF3632EAE4DF0307E82861A927FB7F3A691ECB9722EF0CA12CFCEC2"

class BaseHandler(SessionBaseHandler):
    def __init__(self, application, request, **kwargs):
        super(BaseHandler, self).__init__(application, request, **kwargs)

    def SetDownLoadHeadler(self, fileName):
        fileName = fileName.encode("gb2312").decode('latin-1')  # 支持中文文件名
        self.set_header('Content-Type',
                        'application/octet-stream charset=utf-8')
        self.set_header('Content-Disposition',
                        f"attachment; filename= {fileName}")

    def write_resp200(self, response,err_code=0,_err=''):
        self.set_header('Content-type', 'application/json')
        _response = {
            "err_code": err_code,
            "data": response,
            "err_msg": _err
        }
        self.write(json.dumps(_response))
        self.finish()

    def write_resp400(self, _err,response="", err_code=400):
        self.set_header('Content-type', 'application/json')
        _response = {
            "data": response,
            "err_code": err_code,
            "err_msg": _err
        }
        self.write(json.dumps(_response))
        self.finish()

    def write_resp500(self,_err='',response="", err_code=500):
        self.set_header('Content-type', 'application/json')
        _response = {
            "err_code": err_code,
            "data": response,
            "err_msg": _err
        }
        self.write(json.dumps(_response))
        self.finish()

    def json(self):
        return json.loads(self.request.body)


    async def init_client_param(self,sm2):
        data = self.json()
        try:
            sm2.ciphertext = data.get("ciphertext")
        except Exception as e:
            logger.error(f"客户端密文不合法:{e}")
            return -1

        lsm = LaneSoftwareMsg()
        try:
            lsm.data = await sm2.dec()
        except Exception as e:
            logger.error(f"客户端密文数据异常:{e}")
            return -1
        return lsm

    def get_current_user(self):
        #----------------公共请求鉴权---------------------------
        # logger.info(f"*********headers:{self.request.headers}**********")
        # sign = Sign()
        # if self.request.method in ['GET', 'DELETE']:
        #     f = furl(self.request.uri)
        #     param = f.args
        # elif self.request.method in ['POST', 'PUT']:
        #     param = self.json()
        # sign.param = param
        # auth = AuthenticationController()
        # try:
        #     auth.devType = self.request.headers.get("Dev-Type")
        #     auth.reqSign = self.request.headers.get("Authorization")
        #     auth.sign = sign
        #     auth.session = self.session
        #     auth.token = self.request.cookies.get("token")
        #     auth.auth()
        # except Exception as e:
        #     logger.error(f"通用鉴权时异常:{e}")
        #     return
        # logger.info(f"鉴权结果:{auth.errMsg};body:{sign.param}")
        # res = "ok" if auth.isPass else None
        # return res
        sign_manger = Sign()
        if self.request.method in ["POST","PUT"]:
            sign_manger.param = self.json()
        elif self.request.method in ["GET","DELETE"]:
            f = furl(self.request.uri)
            sign_manger.param = f.args
            logger.info(f"sign_param:{sign_manger.param}")
        local_sign = sign_manger.sign()
        request_sign = self.request.headers.get("Authorization").split(' ')[1]
        if local_sign!=request_sign:
            logger.error(f"签名比对失败:request_sign:{request_sign};local_sign:{local_sign}")
            return
        client_id = self.request.headers.get("client-id","")
        client_secret = self.request.headers.get("client-secret","")
    
        token = self.request.headers.get("token","")
        oauth2_session_manager = OAuth2SessionManager(client_id,client_secret)
        if not oauth2_session_manager.check_token(token):
            logger.error(f"token:{token}不合法;client_id:{client_id};client_secret:{client_secret}")
            return
        return "success"

class OtherBaseHandler(SessionBaseHandler):
    def __init__(self, application, request, **kwargs):
        super(OtherBaseHandler, self).__init__(application, request, **kwargs)

    def write_resp200(self, response,err_code=0,_err=''):
        self.set_header('Content-type', 'application/json')
        _response = {
            "resCode": err_code,
            "data": response,
            "resMsg": _err
        }
        self.write(json.dumps(_response))
        self.finish()

    def write_resp400(self, _err,response="", err_code=400):
        self.set_header('Content-type', 'application/json')
        _response = {
            "data": response,
            "resCode": err_code,
            "resMsg": _err
        }
        self.write(json.dumps(_response))
        self.finish()

    def write_resp500(self,_err='',response="", err_code=500):
        self.set_header('Content-type', 'application/json')
        _response = {
            "resCode": err_code,
            "data": response,
            "resMsg": _err
        }
        self.write(json.dumps(_response))
        self.finish()

    def json(self):
        return json.loads(self.request.body)