#!/usr/bin/env python3  
# -*- coding: utf-8 -*-  
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@AUTHOR: ASJRD018
@NAME: AnsjerFormal
@software: PyCharm
@DATE: 2020/2/27 9:38
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: AppSetController.py
@Contact: chanjunkai@163.com
"""
from Ansjer.config import SERVER_TYPE
from Model.models import AppSetModel
from django.views.generic.base import View
from Object.RedisObject import RedisObject
from Object.TokenObject import TokenObject
from Service.ModelService import ModelService
import time,json
from Object.ResponseObject import ResponseObject
class AppSetView(View):
    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation', None)
        return self.validation(request.GET, operation)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation', None)
        return self.validation(request.POST, operation)

    def validation(self, request_dict, operation):
        response = ResponseObject()
        if operation == 'query':
            return self.do_query(request_dict, response)
        if operation == 'admin_query':
            token = request_dict.get('token', None)
            tko = TokenObject(token)
            if tko.code == 0:
                userID = tko.userID
                return self.do_admin_query(userID, request_dict, response)
            else:
                return response.json(tko.code)
        elif operation == 'admin_update':
            token = request_dict.get('token', None)
            tko = TokenObject(token)
            if tko.code == 0:
                userID = tko.userID
                return self.do_admin_update(userID, request_dict, response)
            else:
                return response.json(tko.code)
        else:
            return response.json(414)

    # 查询
    def do_query(self, request_dict, response):
        lang = request_dict.get('lang', None)
        appBundleId = request_dict.get('appBundleId', None)
        if not appBundleId:
            return response.json(444,'appBundleId')
        redis = RedisObject()

        if SERVER_TYPE != "Ansjer.formal_settings":
            key_id= "www"+appBundleId
        else:
            key_id = "test" + appBundleId
        #redis_value = redis.get_data(key=key_id)  去除到缓存中找
        redis_value = False
        if redis_value == False:
            print('添加到缓存')
            # 查数据库
            sm_qs = AppSetModel.objects.filter(appBundleId=appBundleId)
            count = sm_qs.count()
            if count > 0:

                sm_qs = sm_qs.values("content")
                # 添加到缓存，缓存时间为3600秒------指的是一个钟后再次访问，就会刷新缓存一次
                dict_json = json.loads(sm_qs[0]['content'])
                if 'editionUpgrading' in dict_json :
                    if  dict_json['editionUpgrading'] == 1:
                        if lang !='cn':
                            dict_json['editionUpgrading'] = 'Upgrading, please sign in later'
                        else:
                            dict_json['editionUpgrading'] = '正在升级，请稍后登录'
                    else:
                        dict_json['editionUpgrading'] = ''



                content_json_str = dict_json

                redis.set_data(key=key_id, val=content_json_str, expire=3600)
                # 返回固定值
                return response.json(0, content_json_str)
            else:
                return response.json(173)
        else:
            print('去缓存找')
            # 返回固定值
            return response.json(0, json.loads(redis_value))

        # res = {}
        # res['grade'] = 1
        # #     # 用户帮助
        # res['usingHelp'] = 0
        # #     # AP添加方式
        # res['apAdd'] = 1
        # #     # AP工具
        # res['apTool'] = 1
        # #     # 广告模块
        # res['ad_module'] = {
        #     "time": 0,
        #     "ad_path": [
        #         "https://test.dvema.com/web/static/image/default_ad1",
        #         "https://test.dvema.com/web/static/image/default_ad2",
        #         "https://test.dvema.com/web/static/image/default_ad3",
        #     ]
        # }
        # res['init_img'] = 'https://test.dvema.com/web/static/image/default_start'
        # return response.json(0, res)

    def do_admin_query(self, userID, request_dict, response):
        # 查询和添加权限
        own_perm = ModelService.check_perm(userID, 40)
        if not own_perm:
            return response.json(404)
        appBundleId = request_dict.get('appBundleId', None)
        sm_qs = AppSetModel.objects.filter(appBundleId=appBundleId)
        count = sm_qs.count()
        nowTime = int(time.time())
        if count>0:
            sm_qs = sm_qs.values('id', 'appBundleId', 'content', 'addTime', 'updTime')
            return response.json(0, {'data': list(sm_qs), 'count': count})
        else:
            AppSetModel.objects.create(
                appBundleId=appBundleId,
                addTime=nowTime,
                updTime=nowTime
            )
            return response.json(0)

    def do_admin_update(self, userID, request_dict, response):
        # 修改的权限
        own_perm = ModelService.check_perm(userID, 50)
        if not own_perm:
            return response.json(404)
        appBundleId = request_dict.get('appBundleId', None)
        content = request_dict.get('content', None)
        nowTime = int(time.time())
        sm_qs = AppSetModel.objects.filter(appBundleId=appBundleId)
        redis = RedisObject()
        if SERVER_TYPE != "Ansjer.formal_settings":
            key_id= "www"+appBundleId
        else:
            key_id = "test" + appBundleId
        redis.del_data(key=key_id)
        if sm_qs.exists():
            sm_qs.update(content=content, updTime=nowTime)
            return response.json(0)
        else:
            return response.json(173)