#!/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: 2018/12/15 15:30
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: VodBucket.py
@Contact: chanjunkai@163.com
"""
import json
import math

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 VodBucketModel, UID_Bucket, Store_Meal, Device_Info, OssCrdModel, VodHlsModel, StsCrdModel, \
    Unused_Uid_Meal
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.ModelService import ModelService
from django.db import transaction
import time


class VodBucketView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(VodBucketView, self).dispatch(*args, **kwargs)

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

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        request_dict = json.loads(request.body.decode('utf-8'))
        return self.validation(request_dict, operation)

    def validation(self, request_dict, 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 == 'add':
            return self.do_add(request_dict, response, userID)
        elif operation == 'delete':
            return self.do_delete(request_dict, response, userID)
        elif operation == 'update':
            return self.do_update(request_dict, response, userID)
        elif operation == 'query':
            return self.do_query(response, userID)
        else:
            return response.json(414)

    def do_add(self, request_dict, response, userID):
        own_perm = ModelService.check_perm(userID, 40)
        if not own_perm:
            return response.json(404)
        request_dict.pop('token')
        nowTime = int(time.time())
        try:
            VodBucketModel.objects.create(addTime=nowTime, updTime=nowTime, **request_dict)
        except Exception as e:
            return response.json(10, repr(e))
        res = list(VodBucketModel.objects.values())
        return response.json(0, res)

    def do_query(self, response, userID):
        own_perm = ModelService.check_perm(userID, 30)
        if not own_perm:
            return response.json(404)
        res = list(VodBucketModel.objects.values())
        return response.json(0, res)

    def do_update(self, request_dict, response, userID):
        own_perm = ModelService.check_perm(userID, 50)
        if not own_perm:
            return response.json(404)
        request_dict.pop('token')
        nowTime = int(time.time())
        id = request_dict.get('id', None)
        try:
            VodBucketModel.objects.filter(id=id).update(updTime=nowTime, **request_dict)
        except Exception as e:
            return response.json(10, repr(e))
        # res = list(VodBucketModel.objects.values())
        return response.json(0, {'updTime': nowTime})

    def do_delete(self, request, response, userID):
        own_perm = ModelService.check_perm(userID, 10)
        if not own_perm:
            return response.json(404)
        id = request.get('id', None)
        try:
            VodBucketModel.objects.filter(id=id).delete()
        except Exception as e:
            return response.json(10, repr(e))
        res = list(VodBucketModel.objects.values())
        return response.json(0, res)


class UidBucketView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(UidBucketView, self).dispatch(*args, **kwargs)

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

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        # request_dict = json.loads(request.body.decode('utf-8'))
        return self.validation(request.POST, operation)

    def validation(self, request_dict, 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 == 'add':
            return self.do_add(request_dict, response, userID)
        elif operation == 'delete':
            return self.do_delete(request_dict, response, userID)
        elif operation == 'update':
            return self.do_update(request_dict, response,userID)
        elif operation == 'query':
            return self.do_query(request_dict, response,userID)
        else:
            return response.json(414)

    def do_add(self, request_dict, response, userID):
        own_perm = ModelService.check_perm(userID, 40)
        if not own_perm:
            return response.json(404)
        rank = request_dict.get('rank', None)
        uid = request_dict.get('uid', None)
        channel = request_dict.get('channel', None)
        if not rank:
            return response.json(444, 'rank')
        dvqs = Device_Info.objects.filter(UID=uid)
        if not dvqs.exists():
            return response.json(10, '设备不存在')
        try:
            smqs = Store_Meal.objects.filter(id=rank).values("bucket__storeDay", "day", "bucket_id")
            if not smqs.exists():
                return response.json(10, '套餐信息不存在')
            bucketId = smqs[0]['bucket_id']
            addDay = smqs[0]['day']
            addTime = addDay * 3600 * 24
            nowTime = int(time.time())
            ubqs = UID_Bucket.objects.filter(uid=uid, channel=channel).values("bucket_id", "endTime",
                                                                              "bucket__storeDay")
            if ubqs.exists():
                if nowTime > ubqs[0]['endTime']:
                    endTime = nowTime + addTime
                    ubqs.update(endTime=nowTime + addTime)
                else:
                    # 同一个bucket续费
                    if bucketId == ubqs[0]['bucket_id']:
                        endTime = ubqs[0]['endTime'] + addTime
                        ubqs.update(endTime=endTime)
                    else:
                        if ubqs[0]['bucket__storeDay'] > smqs[0]['bucket__storeDay']:
                            return response.json(10, '不可降级')
                        else:
                            origin_storeDay = int(ubqs[0]['bucket__storeDay'])
                            upgrade_storeDay = int(smqs[0]['bucket__storeDay'])
                            ctcTime = ubqs[0]['endTime'] - nowTime
                            multiple = math.ceil(upgrade_storeDay / origin_storeDay)
                            ubqs.update(endTime=ctcTime / multiple + addTime + ubqs[0]['endTime'])
            else:
                endTime = nowTime + addTime
                UID_Bucket.objects.create(uid=uid, channel=channel, bucket_id=bucketId, endTime=endTime)
        except Exception as e:
            return response.json(10, repr(e))
        else:
            return response.json(0, {'endTime': endTime})

    def do_query(self, request_dict, response, userID):
        own_perm = ModelService.check_perm(userID, 30)
        if not own_perm:
            return response.json(404)
        page = int(request_dict.get('page', None))
        line = int(request_dict.get('line', None))
        uid = request_dict.get('uid', None)
        ubqs = UID_Bucket.objects
        if uid:
            ubqs = ubqs.filter(uid=uid)
        ubqs = ubqs.values('id', 'uid', 'channel', 'status', 'endTime', 'bucket__bucket',
                           'bucket__storeDay', 'bucket__area')
        res = {
            'datas': list(ubqs[(page - 1) * line:page * line]),
            'count': ubqs.count()
        }
        return response.json(0, res)

    def do_update(self, request_dict, response, userID):
        own_perm = ModelService.check_perm(userID, 50)
        if not own_perm:
            return response.json(404)
        status = request_dict.get('status', None)
        id = request_dict.get('id', None)
        ubqs = UID_Bucket.objects.filter(id=id).values('endTime')
        nowTime = int(time.time())
        endTime = ubqs[0]['endTime']
        if not ubqs.exists():
            return response.json(10, '未购买')
        if endTime > nowTime:
            ubqs.update(status=status)
            return response.json(0)
        else:
            return response.json(10, '过期了')

    def do_delete(self, request_dict, response, userID):
        own_perm = ModelService.check_perm(userID, 10)
        if not own_perm:
            return response.json(404)
        try:
            id = request_dict.get('id', None)
            page = int(request_dict.get('page', None))
            line = int(request_dict.get('line', None))
            uid_bucket_qs = UID_Bucket.objects.filter(id=id)
            uid = uid_bucket_qs[0].uid
            bucket_id = uid_bucket_qs[0].bucket_id
            # channel = uid_bucket_qs[0].channel
            with transaction.atomic():
                uid_bucket_qs.delete()
                # OssCrdModel.objects.filter(uid=uid, channel=channel).delete()
                VodHlsModel.objects.filter(uid=uid).delete()
                StsCrdModel.objects.filter(uid=uid).delete()
                Unused_Uid_Meal.objects.filter(uid=uid).delete()
        except Exception as e:
            return response.json(10, repr(e))
        else:
            ubqs = UID_Bucket.objects.values('id', 'uid', 'channel', 'status', 'endTime', 'bucket__bucket',
                                             'bucket__storeDay', 'bucket__area')
            res = {
                'datas': list(ubqs[(page - 1) * line:page * line]),
                'count': ubqs.count()
            }
            return response.json(0, res)

