#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time

from django.db.models import F
from django.http import HttpResponse
from django.views.generic.base import View

from Controller.CloudPhoto.CloudServiceController import CloudServiceController
from Model.models import CouponModel, Device_User
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
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']
        coupon_config_id = request_dict.get('coupon_config_id', 1)

        try:
            data = []
            # CouponConfigModel.objects.create(type=1, use_range=1, coupon_discount=8)
            # CouponLangObj = CouponLang.objects.create(
            #     lang='cn',
            #     instruction='用于自动续费套餐的首月',
            #     quota='八',
            #     unit='折',
            #     remark='每台摄像机上只能用一次'
            # )
            # CouponConfigModel.objects.get(id=1).lang.add(CouponLangObj.id)
            now_time = int(time.time())
            CouponModel.objects.create(
                use_status=0,
                distribute_time=now_time,
                valid_time=now_time + 10000000,
                userID=userID,
                coupon_config_id=coupon_config_id,
                update_time=now_time,
                create_time=now_time
            )
            return HttpResponse('success')
        except Exception as e:
            return HttpResponse(
                "错误行数：{errLine}, 错误信息: {errmsg}".format(errLine=e.__traceback__.tb_lineno, errmsg=repr(e)))

    def query_user_coupon(self, request_dict, userID, response):  # 用户优惠券列表
        now_time = int(time.time())
        lang = request_dict.get('lang', 'en')
        coupon_obj = CouponModel.objects.filter(
            userID=userID,
            use_status=0,
            distribute_time__lte=now_time,
            valid_time__gt=now_time,
            coupon_config__lang__lang=lang,
        ).annotate(
            coupon_id=F('id'),
            type=F('coupon_config__type'),
            coupon_discount=F('coupon_config__coupon_discount'),
            instruction=F('coupon_config__lang__instruction'),
            remark=F('coupon_config__lang__remark'),
            quota=F('coupon_config__lang__quota'),
            unit=F('coupon_config__lang__unit'),
            config_id=F('coupon_config_id')
        ).values(
            "coupon_id",
            "type",
            "coupon_discount",
            "valid_time",
            "instruction",
            "remark",
            "quota",
            "unit",
            "config_id"
        )

        for couponList in coupon_obj:
            couponList['valid_time'] = CommonService.timestamp_to_str(couponList['valid_time'])
            couponList['comboList'] = CloudServiceController.get_combo_list(0, couponList['config_id'])

        result = {
            'count': coupon_obj.count(),
            'couponList': list(coupon_obj),
        }
        return response.json(0, result)
