# -*- coding: utf-8 -*-
"""
@Time ： 2020/12/16 8:44
@Auth ： Locky
@File ：CloudTransfer.py
@IDE ：PyCharm
"""
import time
from django.db import transaction
from django.views.generic.base import View

from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from Service.ModelService import ModelService
from Object.ResponseObject import ResponseObject
from Model.models import Device_User, Device_Info, Order_Model, UID_Bucket, StsCrdModel, VodHlsModel, Unused_Uid_Meal, \
    VodBucketModel, UIDMainUser


class cloudTestView(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')
        else:
            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 == 'deviceTransfer':
                return self.deviceTransfer(request_dict, response)
            elif operation == 'mealTransfer':
                return self.mealTransfer(request_dict, response, userID)
            elif operation == 'expireMeal':
                return self.expireMeal(request_dict, response)

    def deviceTransfer(self, request_dict, response):
        # 设备转移,一个用户下的设备转移到另一个用户
        oldUserID = request_dict.get("oldUserID", None)
        username = request_dict.get("username", None)
        uid = request_dict.get('uid', None)
        now_time = CommonService.timestamp_to_str(int(time.time()))
        # print('now_time: ', now_time)

        try:
            # 查询该userID下是否存在此设备
            old_deviceInfo_qs = Device_Info.objects.filter(userID_id=oldUserID, UID=uid, isExist=1).values('isShare','vodPrimaryUserID')
            if not old_deviceInfo_qs.exists():
                return response.json(10008)

            newUserID = ModelService.get_userID_byname(username)    # 根据username获取userID
            if newUserID is None:   # 没有此用户
                return response.json(104)
            if newUserID == oldUserID:  # 新用户的userID跟旧用户的一样
                return response.json(10009)
            # 分享的设备不能转移
            isShare = old_deviceInfo_qs[0]['isShare']
            if isShare:
                return response.json(10015)
            # 旧用户是设备主用户才能转移
            vodPrimaryUserID = old_deviceInfo_qs[0]['vodPrimaryUserID']
            if vodPrimaryUserID != '' and vodPrimaryUserID != oldUserID:
                return response.json(10037)

            # uid_mian = UIDMainUser.objects.filter(UID=uid).values('UID', 'user_id')
            # if uid_mian.exists():
            #     vodPrimaryUserID = uid_mian[0]['user_id']
            #     if vodPrimaryUserID != '' and vodPrimaryUserID != oldUserID:
            #         return response.json(10037)

            # 判断新用户是否已有此设备
            new_deviceInfo_qs = Device_Info.objects.filter(userID_id=newUserID, UID=uid, isExist=1)
            if new_deviceInfo_qs:
                return response.json(10009)

            # 获取新设备的username
            newUserName = Device_User.objects.get(userID=newUserID).username
            vodPrimaryUserID = newUserID
            vodPrimaryMaster = newUserName

            with transaction.atomic():
                # 更新旧设备的userID,设备添加时间
                old_deviceInfo_qs.update(userID=newUserID, data_joined=now_time)
                # 更新设备的主用户信息
                Device_Info.objects.filter(UID=uid).update(vodPrimaryUserID=vodPrimaryUserID, vodPrimaryMaster=vodPrimaryMaster)
                VodHlsModel.objects.filter(uid=uid).delete()

                # UIDMainUser.objects.filter(UID=uid).delete()
                # uid_main_dict = {
                #     'UID': uid,
                #     'user_id': newUserID
                # }
                # UIDMainUser.objects.create(**uid_main_dict)

        except Exception as e:
            # print(e)
            return response.json(500, repr(e))
        else:
            return response.json(0)

    def mealTransfer(self, request_dict, response, userID):
        # 云存套餐转移,同一用户下不同设备间的云存套餐转移
        old_uid = request_dict.get("old_uid", None)
        new_uid = request_dict.get("new_uid", None)
        nowTime = int(time.time())

        try:
            # 查询两个UID是否在同一账号下
            old_deviceInfo_qs = Device_Info.objects.filter(userID_id=userID, UID=old_uid).values('isExist','vodPrimaryUserID')
            new_deviceInfo_qs = Device_Info.objects.filter(userID_id=userID, UID=new_uid).values('isExist')
            if not (old_deviceInfo_qs.exists() and new_deviceInfo_qs.exists()):
                return response.json(10010)

            # 不是主用户无法转移
            vodPrimaryUserID = old_deviceInfo_qs[0]['vodPrimaryUserID']
            if vodPrimaryUserID != '' and vodPrimaryUserID != userID:
                return response.json(10038)
            vodPrimaryUserID = userID
            vodPrimaryMaster = ModelService.get_user_name(userID)

            new_isExist = new_deviceInfo_qs[0]['isExist']
            if not new_isExist:
                return response.json(10011)

            # 查询转出设备正在使用的套餐
            old_using_uid_bucket = UID_Bucket.objects.filter(uid=old_uid, endTime__gte=nowTime).values('id', 'bucket_id', 'has_unused').order_by('addTime')
            if not old_using_uid_bucket.exists():
                return response.json(10013)

            # 免费存储桶不可转移
            old_vod_bucket_id = old_using_uid_bucket[0]['bucket_id']
            is_free = VodBucketModel.objects.get(id=old_vod_bucket_id).is_free
            if is_free == 1:
                return response.json(10012)

            # 查询转入设备是否存在正在使用的套餐和未使用的套餐
            new_using_uid_bucket = UID_Bucket.objects.filter(uid=new_uid, endTime__gte=nowTime)
            new_unused_uid_bucket = Unused_Uid_Meal.objects.filter(uid=new_uid)
            if new_using_uid_bucket.exists() or new_unused_uid_bucket.exists():
                return response.json(10014)

            # 如果转出设备有未使用套餐,更改第一个未使用套餐为正在使用
            if old_using_uid_bucket[0]['has_unused'] == 1:
                old_unused_uid_bucket = Unused_Uid_Meal.objects.filter(uid=old_uid).values('id', 'channel', 'bucket_id', 'addTime', 'expire', 'num')
                count = old_unused_uid_bucket.count()
                unused = old_unused_uid_bucket[0]
                has_unused = 1 if count>1 else 0    # 如果存在不止一个未使用套餐,has_unused=1
                endTime = CommonService.calcMonthLater(unused['expire'] * unused['num'])
                data_dict = {
                    'uid': old_uid,
                    'channel': unused['channel'],
                    'bucket_id': unused['bucket_id'],
                    'addTime': unused['addTime'],
                    'endTime': endTime,
                    'updateTime': nowTime,
                    'status': 1,
                    'use_status': 1,
                    'has_unused': has_unused
                }
                UID_Bucket.objects.create(**data_dict)  # 正在使用套餐表添加数据
                Unused_Uid_Meal.objects.filter(uid=old_uid).first().delete()   # 删除未使用套餐表中的数据

            with transaction.atomic():
                # 更新转入设备的主用户信息
                Device_Info.objects.filter(UID=new_uid).update(vodPrimaryUserID=vodPrimaryUserID, vodPrimaryMaster=vodPrimaryMaster)
                # 更新正在使用套餐的uid,重置拥有未使用套餐
                old_using_uid_bucket_id = old_using_uid_bucket[0]['id']
                UID_Bucket.objects.filter(id=old_using_uid_bucket_id).update(uid=new_uid,has_unused=0)
                StsCrdModel.objects.filter(uid=old_uid).delete()    # 删除转出设备stscrd表关联数据

        except Exception as e:
            # print(e)
            return response.json(500, repr(e))
        else:
            return response.json(0)

    def expireMeal(self, request_dict, response):
        UID_Bucket_id = request_dict.get("UID_Bucket_id", None)
        # 修改endTime让当前设备套餐过期
        if UID_Bucket_id:
            try:
                UID_Bucket.objects.filter(id=UID_Bucket_id).update(use_status=2)
            except Exception as e:
                # print(e)
                return response.json(500, repr(e))
            else:
                return response.json(0)
        response.json(404)
