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

import oss2
from django.db import transaction
from django.db.models import Q

from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from django.views.generic.base import View
from Service.ModelService import ModelService
from Service.CommonService import CommonService
from Model.models import Device_Info, UidSetModel, LogModel, UID_Bucket, Unused_Uid_Meal, Order_Model, StsCrdModel, \
    VodHlsModel, ExperienceContextModel, DeviceTypeModel, Equipment_Info, UidUserModel


class DeviceManagement(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):
        language = request_dict.get('language', 'en')
        response = ResponseObject(language, 'pc')
        if operation == 'addDeviceType':
            return self.addDeviceType(request, request_dict, response)
        elif operation == 'delDeviceData':
            return self.delDeviceData(request_dict, response)
        else:
            tko = TokenObject(
                request.META.get('HTTP_AUTHORIZATION'),
                returntpye='pc')
            if tko.code != 0:
                return response.json(tko.code)
            response.lang = tko.lang
            userID = tko.userID
            if not userID:
                return response.json(444, 'userID')
            if operation == 'getDeviceInfoList':
                return self.getDeviceInfoList(request_dict, response)
            elif operation == 'deleteDevice':
                return self.deleteDevice(request_dict, response)
            elif operation == 'resetVod':
                return self.resetVod(request, request_dict, response)
            elif operation == 'resetPrimaryUser':
                return self.resetPrimaryUser(request, request_dict, response)
            elif operation == 'getDeviceTypeList':
                return self.getDeviceTypeList(request_dict, response)
            elif operation == 'deleteDeviceType':
                return self.deleteDeviceType(request_dict, response)
            else:
                return response.json(444, 'operation')

    # 获取设备信息数据
    def getDeviceInfoList(self, request_dict, response):
        pageNo = request_dict.get('pageNo', None)
        pageSize = request_dict.get('pageSize', None)
        UID = request_dict.get('UID', None)
        serialNumber = request_dict.get('serialNumber', None)
        NickName = request_dict.get('NickName', None)
        username = request_dict.get('username', None)

        if not all([pageNo, pageSize]):
            return response.json(444)

        page = int(pageNo)
        line = int(pageSize)

        try:
            if UID or serialNumber or NickName or username:    # 条件查询
                if UID:
                    device_info_qs = Device_Info.objects.filter(UID__contains=UID)
                if serialNumber:
                    device_info_qs = Device_Info.objects.filter(serial_number__contains=serialNumber)
                if NickName:
                    device_info_qs = Device_Info.objects.filter(NickName__contains=NickName)
                if username:
                    device_info_qs = Device_Info.objects.filter(Q(userID__username__contains=username) |
                                                                Q(userID__userEmail__contains=username) |
                                                                Q(userID__phone__contains=username))
                total = len(device_info_qs)
                if not total:
                    return response.json(0, {'list': {}, 'total': 0})
                device_info_qs = device_info_qs[(page - 1) * line:page * line]
            else:   # 查询全部
                total = Device_Info.objects.filter().count()
                device_info_qs = Device_Info.objects.filter()[(page - 1) * line:page * line]
                if not device_info_qs.exists():
                    return response.json(0, {'list': {}, 'total': 0})

            device_info_list = CommonService.qs_to_dict(device_info_qs)
            for k, v in enumerate(device_info_list["datas"]):
                for device_info in device_info_qs:
                    if v['pk'] == device_info.id:
                        # 设备的用户名和主用户
                        username = ModelService.get_user_name(device_info_list["datas"][k]['fields']['userID'])
                        device_info_list["datas"][k]['fields']['username'] = username
                        device_info_list["datas"][k]['fields']['vodPrimaryMaster'] = device_info_list["datas"][k]['fields']['vodPrimaryMaster']
                        # 设备类型,是否支持Alexa和ip
                        type = device_info_list["datas"][k]['fields']['Type']
                        device_type_qs = DeviceTypeModel.objects.filter(type=type).values('name')
                        if device_type_qs.exists():
                            device_info_list["datas"][k]['fields']['Type'] = device_type_qs[0]['name']
                        uid_set_qs = UidSetModel.objects.filter(uid=device_info_list["datas"][k]['fields']['UID']).values('is_alexa', 'ip')
                        if uid_set_qs.exists():
                            isAlexa = '是' if uid_set_qs[0]['is_alexa'] else '否'
                            device_info_list["datas"][k]['fields']['isAlexa'] = isAlexa
                            device_info_list["datas"][k]['fields']['ip'] = uid_set_qs[0]['ip']
            return response.json(0, {'list': device_info_list, 'total': total})
        except Exception as e:
            print(e)
            return response.json(500, repr(e))

    # 根据id删除设备
    def deleteDevice(self, request_dict, response):
        deviceID = request_dict.get('deviceID', None)
        userID = request_dict.get('userID', None)
        uid = request_dict.get('uid', None)
        if not all([deviceID, userID, uid]):
            return response.json(444)

        try:
            with transaction.atomic():
                Device_Info.objects.filter(id=deviceID).delete()
                Equipment_Info.objects.filter(userID_id=userID, devUid=uid).delete()    # 删除推送消息
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, repr(e))

    # 重置设备主用户
    def resetPrimaryUser(self, request, request_dict, response):
        uid = request_dict.get('uid', None)
        if not uid:
            return response.json(404)
        try:
            # 记录操作日志
            ip = CommonService.get_ip_address(request)
            content = json.loads(json.dumps(request_dict))
            log = {
                'ip': ip,
                'user_id': 2,
                'status': 200,
                'time': int(time.time()),
                'url': 'deviceManagement/resetPrimaryUser',
                'content': json.dumps(content),
                'operation': '{}重置设备主用户'.format(uid),
            }
            LogModel.objects.create(**log)
            Device_Info.objects.filter(UID=uid).update(vodPrimaryUserID='', vodPrimaryMaster='')
            return response.json(0)
        except Exception as e:
            return response.json(500, repr(e))

    # 重置设备云存
    def resetVod(self, request, request_dict, response):
        uid = request_dict.get('uid', None)
        if not uid:
            return response.json(444)
        try:
            # 记录操作日志
            ip = CommonService.get_ip_address(request)
            content = json.loads(json.dumps(request_dict))
            log = {
                'ip': ip,
                'user_id': 2,
                'status': 200,
                'time': int(time.time()),
                'url': 'deviceManagement/resetVod',
                'content': json.dumps(content),
                'operation': '{}重置设备云存'.format(uid),
            }
            with transaction.atomic():
                LogModel.objects.create(**log)
                # 删除和更新设备云存相关数据
                UID_Bucket.objects.filter(uid=uid).delete()
                Unused_Uid_Meal.objects.filter(uid=uid).delete()
                Order_Model.objects.filter(UID=uid).delete()
                StsCrdModel.objects.filter(uid=uid).delete()
                VodHlsModel.objects.filter(uid=uid).delete()
                ExperienceContextModel.objects.filter(uid=uid).delete()
                Device_Info.objects.filter(UID=uid).update(vodPrimaryUserID='', vodPrimaryMaster='')
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, repr(e))

    # 获取设备类型数据
    def getDeviceTypeList(self, request_dict, response):
        name = request_dict.get('name', None)
        pageNo = request_dict.get('pageNo', None)
        pageSize = request_dict.get('pageSize', None)

        if not all([pageNo, pageSize]):
            return response.json(444)

        page = int(pageNo)
        line = int(pageSize)
        try:
            if name:
                device_type_qs = DeviceTypeModel.objects.filter(name__contains=name).values()
                total = len(device_type_qs)
            else:
                device_type_qs = DeviceTypeModel.objects.filter().values()[(page - 1) * line:page * line]
                total = DeviceTypeModel.objects.filter().count()
            if not device_type_qs.exists():
                return response.json(173)
            device_type_list = []
            for device_type in device_type_qs:
                auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
                bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'ansjer-static-resources')

                icon = device_type['icon']
                url = 'device_type/' + icon
                device_type['icon'] = bucket.sign_url('GET', url, 3600)
                device_type_list.append(device_type)
            return response.json(0, {'list': device_type_list, 'total': total})
        except Exception as e:
            print(e)
            return response.json(500, repr(e))

    # 删除设备类型
    def deleteDeviceType(self, request_dict, response):
        deviceTypeID = request_dict.get('deviceTypeID', None)
        if not deviceTypeID:
            return response.json(444)
        try:
            DeviceTypeModel.objects.filter(id=deviceTypeID).delete()
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, repr(e))

    # 添加设备类型
    def addDeviceType(self, request, request_dict, response):
        iconFile = request.FILES.get('iconFile', None)
        name = request_dict.get('name', None)
        model = request_dict.get('model', None)
        type = request_dict.get('type', None)
        ptz_type = request_dict.get('ptz_type', None)

        if not all([iconFile, name, model, type, ptz_type]):
            return response.json(444)
        try:
            model = int(model)
            ptz_type = int(ptz_type)
            icon = iconFile.name
            now_time = int(time.time())
            # 上传文件到阿里云OSS
            auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
            bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'ansjer-static-resources')
            key = 'device_type/' + icon     # 图片文件存放于 device_type 目录下
            # https://oss.console.aliyun.com/bucket/oss-cn-shenzhen/ansjer-static-resources/object?path=device_type%2F
            bucket.put_object(key=key, data=iconFile)
            DeviceTypeModel.objects.create(name=name, model=model, type=type, ptz_type=ptz_type, icon=icon,
                                           add_time=now_time, update_time=now_time)
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, repr(e))

    # 删除设备数据
    def delDeviceData(self, request_dict, response):
        uidList = request_dict.get('uidList', None)
        delDataOptions = request_dict.get('delDataOptions', None)

        if not all([uidList, delDataOptions]):
            return response.json(444)
        try:
            with transaction.atomic():
                uidList = uidList.splitlines()      # 按行('\r', '\r\n', \n')切割字符串返回列表
                # 根据删除项删除相关数据
                if '设备信息数据' in delDataOptions:
                    Device_Info.objects.filter(UID__in=uidList).delete()
                if '设备配置数据' in delDataOptions:
                    UidSetModel.objects.filter(uid__in=uidList).delete()
                if '设备推送数据' in delDataOptions:
                    Equipment_Info.objects.filter(devUid__in=uidList).delete()
                if '设备AP信息数据' in delDataOptions:
                    UidUserModel.objects.filter(UID__in=uidList).delete()
                if '设备云存数据' in delDataOptions:
                    UID_Bucket.objects.filter(uid__in=uidList).delete()
                    Unused_Uid_Meal.objects.filter(uid__in=uidList).delete()
                    Order_Model.objects.filter(UID__in=uidList).delete()
                    StsCrdModel.objects.filter(uid__in=uidList).delete()
                    VodHlsModel.objects.filter(uid__in=uidList).delete()
                    ExperienceContextModel.objects.filter(uid__in=uidList).delete()
                    Device_Info.objects.filter(UID__in=uidList).update(vodPrimaryUserID='', vodPrimaryMaster='')
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, repr(e))
