#!/usr/bin/env python3  
# -*- coding: utf-8 -*-  
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@AUTHOR: ASJRD018
@NAME: Ansjer
@software: PyCharm
@DATE: 2018/6/8 9:10
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: SysManage.py
@Contact: chanjunkai@163.com
"""
import os
import threading
import time

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.base import View

from Ansjer.config import BASE_DIR
from Controller.CouponController import CouponView
from Model.models import SysMsgModel, Device_Info, Ai_Push_Info, UidSetModel, ExperienceContextModel, Order_Model, \
    UID_Bucket
from Object.Enums.ConstantEnum import ConstantEnum
from Object.Enums.RedisKeyConstant import RedisKeyConstant
from Object.RedisObject import RedisObject
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from Service.ModelService import ModelService


@csrf_exempt
def updateLog(request):
    response = ResponseObject()
    request.encoding = 'utf-8'
    if request.method == 'GET':
        request_dict = request.GET
    if request.method == 'POST':
        request_dict = request.POST
    else:
        response.json(404)
    token = request_dict.get('token', None)
    content = request_dict.get('content', None)
    if not content:
        return response.json(444, 'content')
    tko = TokenObject(token)
    response.lang = tko.lang
    if tko.code != 0:
        return response.json(tko.code)
    userID = tko.userID
    own_permission = ModelService.check_perm(userID=userID, permID=50)
    if own_permission is not True:
        return response.json(404)
    file_path = os.path.join(BASE_DIR, 'static/Help/version.txt')
    try:
        with open(file_path, "w", encoding="utf-8") as f:
            f.write(content)
    except Exception as e:
        pass
    return response.json(0)


class getStatView(View):
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        filePath = kwargs.get('filePath', None)
        filePath.encode(encoding='utf-8', errors='strict')
        response = ResponseObject()
        return self.getFile(filePath, response)

    def get(self, request, *args, **kwargs):
        request.encoding = 'gb2312'
        filePath = kwargs.get('filePath', None)
        response = ResponseObject()
        filePath.encode(encoding='gb2312', errors='strict')
        return self.getFile(filePath, response)

    def getFile(self, filePath, response):
        if filePath:
            pass
        else:
            return response.json(800)
        fullPath = os.path.join(BASE_DIR, filePath).replace('\\', '/')
        from var_dump import var_dump
        var_dump(fullPath)
        if os.path.isfile(fullPath):
            try:
                Imagedata = open(fullPath, 'rb').read()
            except Exception as e:
                return response.json(906, repr(e))
            else:
                return HttpResponse(Imagedata, content_type="image/jpeg")
        else:
            return response.json(907)


from Service.EquipmentInfoService import EquipmentInfoService


def initMsgFunc(request):
    response = ResponseObject()
    request.encoding = 'utf-8'
    if request.method == 'GET':
        request_dict = request.GET
    if request.method == 'POST':
        request_dict = request.POST
    else:
        response.json(404)
    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
    seven_days_ago = int(time.time()) - 3600 * 24 * 7  # 过滤七天前数据
    sm_count = SysMsgModel.objects.filter(userID_id=userID, status=0).count()

    kwargs = {
        'device_user_id': userID,
        'event_time__gt': seven_days_ago,
        'status': 0
    }
    eq_count = EquipmentInfoService.count_equipment_info(**kwargs)
    # kwargs['event_type'] = 57
    # rq_count = EquipmentInfoService.count_equipment_info(**kwargs)
    rq_count = 0  # 影响查询性能APP未调用该属性，统一返回0

    ai_count = Ai_Push_Info.objects.filter(userID_id=userID, eventTime__gt=seven_days_ago, status=False).count()
    uid_reset_count = Device_Info.objects.filter(userID_id=userID, isExist=2).count()
    res = {
        'sm_count': sm_count,  # 系统消息未读数量
        'eq_count': eq_count,  # 未读消息总数
        'rq_count': rq_count,  # 人形检测总数
        'ai_count': ai_count,  # AI消息总数
        'uid_reset_count': uid_reset_count,  # 复位的设备数量
    }
    # 如果没有发放过云存优惠券,异步发放
    now_time = int(time.time())
    start_time, end_time = ConstantEnum.PROMOTION_START_TIME.value, ConstantEnum.PROMOTION_END_TIME.value
    # 缓存过期时间
    expire = end_time - now_time
    if expire > 0:
        redis_obj = RedisObject()

        # 加锁
        grant_key = RedisKeyConstant.GRANT_COUPONS_LOCK.value + userID
        lock_success = redis_obj.CONN.setnx(grant_key, 1)
        if lock_success:
            redis_obj.CONN.expire(grant_key, 600)
            distribute_key = RedisKeyConstant.CLOUD_STORAGE_COUPONS.value + userID
            is_distributed = redis_obj.get_data(distribute_key)
            if not is_distributed:
                thread_kwargs = {
                    'user_id': userID,
                    'redis_obj': redis_obj,
                    'distribute_key': distribute_key,
                    'expire': expire,
                    'end_time': end_time,
                    'grant_key': grant_key
                }
                del_push_info_thread = threading.Thread(
                    target=distribute_cloud_storage_coupons,
                    kwargs=thread_kwargs)
                del_push_info_thread.start()
    return response.json(0, res)


def distribute_cloud_storage_coupons(user_id, redis_obj, distribute_key, expire, end_time,  grant_key):
    """
    发放云存优惠券
    满足条件,用户存在以下三种类型的设备:
    1. 未体验云存设备
    2. 体验过未购买过
    3. 购买过且已过期
    @param user_id: 用户id
    @param redis_obj: redis对象
    @param distribute_key: 发放优惠券缓存key
    @param expire: distribute_key过期时间
    @param end_time: 活动结束时间
    @param grant_key: 发放锁
    @return:
    """
    try:
        generate_success = False
        uid_list = Device_Info.objects.filter(userID_id=user_id).values_list('UID', flat=True)
        if uid_list:
            uid_set_qs = UidSetModel.objects.filter(uid__in=uid_list).values('uid', 'ucode', 'device_type')
            if uid_set_qs.exists():
                for uid_set in uid_set_qs:
                    uid = uid_set['uid']
                    # 判断设备是否支持云存
                    is_cloud_vod = CommonService.is_cloud_device(uid_set['ucode'], uid_set['device_type'])
                    if is_cloud_vod:
                        # 未体验云存
                        experience_qs = ExperienceContextModel.objects.filter(uid=uid, experience_type=0)
                        if not experience_qs.exists():
                            # 发放
                            generate_success = CouponView.generate_coupon_by_user(user_id)
                            break
                        else:
                            # 体验过未购买过
                            orders_qs = Order_Model.objects.filter(UID=uid, status=1, payType__in=[1, 4, 5])
                            if not orders_qs.exists():
                                # 发放
                                generate_success = CouponView.generate_coupon_by_user(user_id)
                                break
                            else:
                                # 购买过且已过期
                                # 没有未使用套餐,且过期时间在2024-12-29前
                                vod_uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, has_unused=0, endTime__lte=end_time)
                                if vod_uid_bucket_qs.exists():
                                    # 发放
                                    generate_success = CouponView.generate_coupon_by_user(user_id)
                                    break
        if generate_success:
            redis_obj.set_data(distribute_key, '1', expire)
        else:
            redis_obj.set_data(distribute_key, '0', expire)
        redis_obj.del_data(grant_key)
    except Exception as e:
        redis_obj.del_data(grant_key)
        return
