#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import base64
import json
import os
import time
import math
from django.views.generic.base import View
from Model.models import CouponModel,Device_User
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from django.db.models import Q, F, Count
from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
from Service.CommonService import CommonService


# 优惠券
class CouponView(View):

    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')
        if operation == 'generateCoupon':  # 用户优惠券
            return self.generate_coupon(request_dict, response)

        else:
            token = request_dict.get('token', None)
            tko = TokenObject(token)
            response.lang = tko.lang
            if tko.code != 0:
                return response.json(tko.code)
            userID = tko.userID
            if operation == 'UserCoupon':  #用户优惠券
                return self.query_user_coupon(request_dict, userID, response)
            else:
                return response.json(414)

    def generate_coupon(self,request_dict,response):
        username = request_dict.get('username', None)
        num = request_dict.get('num', None)
        userID = Device_User.objects.filter(username=username).values('userID')[0]['userID']

        try:
            data = []
            for i in range(int(num)):
                if i % 2 == 0:
                    data.append(CouponModel(
                        userID_id=userID,
                        use_status=0,
                        type=1,
                        coupon_discount=7,
                        distributeTime=int(time.time()),
                        valid_time=int(time.time()) + 8640000,
                        addTime=int(time.time())
                    ))
                else:
                    data.append(CouponModel(
                        userID_id=userID,
                        use_status=0,
                        type=2,
                        coupon_discount=0.01,
                        distributeTime=int(time.time()),
                        valid_time=int(time.time()) + 8640000,
                        addTime=int(time.time())
                    ))
            CouponModel.objects.bulk_create(data)
            return HttpResponse('success')
        except Exception as e:
            return HttpResponse(repr(e))







    def query_user_coupon(self, request_dict, userID, response):  #用户优惠券列表
        nowTime = int(time.time())
        couponObj = CouponModel.objects.filter(userID_id=userID,use_status=0,distributeTime__lte=nowTime,
                                               valid_time__gt=nowTime).annotate(coupon_id=F('id')).values(
                                               "coupon_id","type","coupon_discount","valid_time")
        for couponList in couponObj:
            couponList['valid_time'] =  CommonService.timestamp_to_str(couponList['valid_time'])
        result = {
            'count':couponObj.count(),
            'couponList':list(couponObj),
        }
        return response.json(0, result)
