import time
import traceback

import simplejson as json
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.base import View

from Model.models import App_Colophon,App_Info
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from Service.ModelService import ModelService

'''
# 管理员获取信息
http://192.168.136.39:8000/appCol/adminQuery?token=local&page=1&line=10
  管理员删除信息
http://192.168.136.39:8000/appCol/adminDelete?token=local&id=2
  管理员添加信息
http://192.168.136.39:8000/appCol/adminAdd?token=local&id=321&app_id=2&lang=cn&newApp_version=1.1.1&content=我马上升级
  管理员编辑信息
http://192.168.136.39:8000/appCol/adminEdit?token=local&id=6&content={"token_val":"9999"}
'''


# 设备信息添加
class AppColView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(AppColView, self).dispatch(*args, **kwargs)

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

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

    def validation(self, request_dict, request, operation):
        response = ResponseObject()
        if operation is None:
            return response.json(444, 'error path')
        token = request_dict.get('token', None)
        # 设备主键uid
        tko = TokenObject(token)
        response.lang = tko.lang
        if tko.code != 0:
            return response.json(tko.code)
        userID = tko.userID
        if operation == 'adminDelete':
            return self.do_admin_delete(request_dict, userID, response)
        elif operation == 'adminQuery':
            return self.do_admin_query(request_dict, userID, response)
        elif operation == 'adminAdd':
            return self.do_admin_add(request_dict, userID, response)
        elif operation == 'adminEdit':
            return self.do_admin_edit(request_dict, userID, response)
        else:
            return response.json(444, 'error path')

    # 管理员删除
    def do_admin_delete(self, request_dict, userID, response):
        own_perm = ModelService.check_perm(userID, 20)
        if own_perm is True:
            id = request_dict.get('id')
            try:
                list = App_Colophon.objects.filter(id=id)
                if list.exists():
                    list.delete()
                    return response.json(0)
                else:
                    return response.json(173)
            except Exception as e:
                print(repr(e))
                return response.json(424, repr(e))
        else:
            return response.json(404)

    # 管理员查询接口
    def do_admin_query(self, request_dict, userID, response):
        own_perm = ModelService.check_perm(userID, 30)
        if own_perm is True:
            page = request_dict.get('page', None)
            line = request_dict.get('line', None)
            app_type = request_dict.get('app_type', None)
            if not app_type:
                omqs = App_Colophon.objects.all().order_by('app_id').values_list(
                    'app_id__appBundleId', flat=True).distinct()
            else :
                omqs = App_Colophon.objects.filter(app_id__app_type=app_type).order_by('app_id').values_list('app_id__appBundleId', flat=True).distinct()
            page = int(page)
            line = int(line)
            if not omqs.exists():
                return response.json(0, [])
            count = omqs.count()
            omqs = list(omqs[(page - 1) * line:page * line])
            # 查询时候用记得用in，查询是多个
            ev_qs = App_Colophon.objects.filter(app_id__appBundleId__in=list(omqs)).values("id", "lang",
                     "newApp_version", "content","version_time", "app_id__appBundleId", "app_id__appName", "app_id__app_type")

            order_list = list(ev_qs)
            datas = {}
            # 组装数据
            for ev in order_list:
                for id in omqs:
                    if id not in datas.keys():
                        datas[id] = []
                    if id == ev['app_id__appBundleId']:

                        datas[id].append(ev)

            for k, v in enumerate(datas):
                new = sorted(datas[v], key=lambda x: x['id'],reverse=True)
                datas[v]=new

            res = {
                'datas': datas,
                'count': count
            }
            return response.json(0, res)

        else:
            return response.json(404)

    # 管理员的添加
    def do_admin_add(self, request_dict, userID, response):
        own_perm = ModelService.check_perm(userID=userID, permID=40)
        if own_perm is not True:
            return response.json(404)
        app_id = request_dict.get('app_id', None)
        newApp_version = request_dict.get('newApp_version', None)
        en_content = request_dict.get('en_content', None)
        content = request_dict.get('content', None)
        version_time = request_dict.get('version_time', None)
        param_flag = CommonService.get_param_flag(
            data=[app_id,en_content,version_time, newApp_version, content])
        if param_flag is not True:
            return response.json(444)
        app_info = App_Info.objects.filter(appBundleId=app_id)
        if app_info.exists():
            print ("ok")
        else :
            return response.json(701)
        try:
            AppColophon = App_Colophon(
                app_id=App_Info.objects.get(appBundleId=app_id),
                lang='cn',
                newApp_version=newApp_version,
                version_time=version_time,
                content=content)
            AppColophon.save()
            AppColophon2 = App_Colophon(
                app_id=App_Info.objects.get(appBundleId=app_id),
                lang='en',
                newApp_version=newApp_version,
                version_time=version_time,
                content=en_content)
            AppColophon2.save()
            return response.json(0)
        except Exception:
            errorInfo = traceback.format_exc()
            print(errorInfo)
            return response.json(500, {'details': errorInfo})

    # 管理员的编辑
    def do_admin_edit(self, request_dict, userID, response):
        own_perm = ModelService.check_perm(userID=userID, permID=50)
        if own_perm is not True:
            return response.json(404)
        lang = request_dict.get('lang', None)
        newApp_version = request_dict.get('newApp_version', None)
        content = request_dict.get('content', None)
        version_time =  request_dict.get('version_time', None)
        id = request_dict.get('id', None)
        if not id:
            return response.json(444, 'id')
        try:
            print (id)
            AppColophon = App_Colophon.objects.filter(id=id)

            if AppColophon.exists():
                AppColophon.update(lang=lang,
                newApp_version=newApp_version,
                version_time=version_time,
                content=content)
                return response.json(0)
            else:
                return response.json(173)
        except Exception:
            errorInfo = traceback.format_exc()
            print(errorInfo)
            return response.json(500, {'details': errorInfo})



