#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@AUTHOR: ASJRD018
@NAME: AnsjerPush
@software: PyCharm
@DATE: 2020/2/14 13:54
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: ShadowController.py
@Contact: chanjunkai@163.com
"""
# 测试环境
# test.shadow.dvema.com
# 生产环境
# shadow.dvema.com
# 设备影子更新
import logging
import time

import requests
from django.http import JsonResponse
from ratelimit.decorators import ratelimit

from AnsjerPush.config import SERVER_TYPE
from Model.models import Device_Info, UidSetModel, UID_Preview, VoicePromptModel, UID_Bucket, UidChannelSetModel, \
    AiService, CountryModel
from Object.ETkObject import ETkObject
from Object.ResponseObject import ResponseObject
from Service.CommonService import CommonService


def generate_utk(request):
    request.encoding = 'utf-8'
    response = ResponseObject()
    if request.method == 'GET':
        request_dict = request.GET
    elif request.method == 'POST':
        request_dict = request.POST
    else:
        return response.json(444, 'wrong method')
    username = request_dict.get('username', None)
    password = request_dict.get('password', None)
    uid = request_dict.get('uid', None)
    if username and password:
        if username == 'debug_user' and password == 'debug_password':
            # utko = UidTokenObject()
            # # right
            # utko.generate(data={'uid': uid})
            etkObj = ETkObject(etk='')
            etk = etkObj.encrypt(uid)
            return response.json(0, {'etk': etk})
        else:
            return response.json(404)
    else:
        return response.json(444, 'username password')


# 设备影子更新
def update_device_shadow(request):
    request.encoding = 'utf-8'
    if request.method == 'POST':
        request_dict = request.POST
    elif request.method == 'GET':
        request_dict = request.GET
    else:
        return JsonResponse(status=200, data={'code': 0, 'msg': 'success', 'data': {}})
    logger = logging.getLogger('info')
    try:
        etk = request_dict.get('etk', None)
        eto = ETkObject(etk)
        uid = eto.uid
        if not uid:
            return JsonResponse(status=200, data={'code': 0, 'msg': 'success', 'data': {}})
        logger.info('使用配置: {}'.format(SERVER_TYPE))
        logger.info('data: {}'.format(request_dict.dict()))

        if SERVER_TYPE != 'Ansjer.test_settings':
            if SERVER_TYPE != 'Ansjer.cn_formal_settings':  # 同步更新国内数据
                requests.post(url='http://shadow.zositechc.cn/deviceShadow/update', data=request_dict.dict(), timeout=2)

        nowTime = int(time.time())

        # 重置按钮
        is_reset = request_dict.get('is_reset', None)
        # 传1则重置设备信息
        if is_reset == '1':
            logger.info('设备重置: {}'.format(uid))

            # 重置语音提示
            uid_channel_qs = UidChannelSetModel.objects.filter(uid__uid=uid)
            if uid_channel_qs.exists():
                uid_channel_qs.update(voice_prompt_intelligent_mute=0, voice_prompt_status=0, voice_prompt_enter=0,
                                      voice_prompt_leave=0, voice_repeat_day=127, voice_start_time=0, voice_end_time=0,
                                      voice_start_x=0, voice_start_y=18, voice_end_x=44, voice_end_y=18,
                                      voice_direction=0)

            # 购买云存套餐的设备isExist置为2
            uid_bucket = UID_Bucket.objects.filter(uid=uid, endTime__gte=nowTime).values('id', 'has_unused').order_by(
                'addTime')
            if not uid_bucket.exists():
                Device_Info.objects.filter(UID=uid).update(isExist=2)
            # 删除预览图
            uid_pre_qs = UID_Preview.objects.filter(uid=uid)
            if uid_pre_qs.exists():
                uid_pre_qs.delete()

            # 删除语音提示
            voice_qs = VoicePromptModel.objects.filter(uid=uid)
            if voice_qs.exists():
                voice_qs.delete()

            # 关闭移动侦测的消息提醒
            Device_Info.objects.filter(UID=uid).update(NotificationMode=0)

            # 关闭AI
            AiService.objects.filter(uid=uid, use_status=1).update(detect_status=0, detect_group='')

            logger.info('{}重置成功'.format(uid))
        ucode = request_dict.get('ucode', None)
        version = request_dict.get('version', None)
        p2p_region = request_dict.get('p2p_region', None)
        tz = request_dict.get('tz', None)
        video_code = request_dict.get('video_code', None)
        ip = CommonService.get_ip_address(request)
        channel = request_dict.get('channel', None)
        cloud_vod = request_dict.get('cloud_vod', None)
        push_status = request_dict.get('push_status', None)
        pwd = request_dict.get('pwd', None)
        is_alexa = request_dict.get('is_alexa', None)
        is_human = request_dict.get('is_human', None)
        is_custom_voice = request_dict.get('is_custom', None)
        double_wifi = request_dict.get('double_wifi', None)
        mobile_4g = request_dict.get('mobile4G', None)
        is_ptz = request_dict.get('is_ptz', None)
        is_ai = request_dict.get('is_ai', None)
        isSupportFourPoint = request_dict.get('isSupportFourPoint', None)

        # 更新
        qs_dict = {
            'updTime': nowTime,
            'ip': ip
        }
        if channel:
            qs_dict['channel'] = channel
        if p2p_region:
            qs_dict['p2p_region'] = p2p_region
        if ucode:
            qs_dict['ucode'] = ucode
        if version:
            qs_dict['version'] = version
        if tz:
            qs_dict['tz'] = tz
        if video_code:
            qs_dict['video_code'] = video_code
        if cloud_vod:
            qs_dict['cloud_vod'] = cloud_vod
        if push_status:
            # 复位重置推送消息提醒
            qs_dict['detect_status'] = 0 if is_reset == '1' else push_status
        if pwd:
            qs_dict['pwd'] = pwd
        if is_human:
            qs_dict['is_human'] = is_human
        if is_custom_voice:
            qs_dict['is_custom_voice'] = is_custom_voice
        if double_wifi:
            qs_dict['double_wifi'] = double_wifi
        if mobile_4g:
            qs_dict['mobile_4g'] = int(mobile_4g)
        if is_ptz:
            qs_dict['is_ptz'] = is_ptz
        if is_ai:
            qs_dict['is_ai'] = is_ai
        if isSupportFourPoint:
            qs_dict['isSupportFourPoint'] = isSupportFourPoint
        ipInfo = CommonService.getIpIpInfo(ip, 'CN')
        country_qs = CountryModel.objects.filter(country_code=ipInfo['country_code']).values('id')
        if country_qs.exists():
            country = country_qs[0]['id']
            qs_dict['tb_country'] = country
        logger.info('{} qs_dict: {}'.format(uid, qs_dict))

        us_qs = UidSetModel.objects.filter(uid=uid)
        if us_qs.exists():
            if is_alexa and us_qs[0].is_alexa == 0:
                qs_dict['is_alexa'] = is_alexa
            us_qs.update(**qs_dict)
        # 新增
        else:
            if is_alexa:
                qs_dict['is_alexa'] = is_alexa
            qs_dict['uid'] = uid
            qs_dict['addTime'] = nowTime
            UidSetModel.objects.create(**qs_dict)
        logger.info('***设备影子保存成功{}'.format(uid))
        return JsonResponse(status=200, data={'code': 0, 'msg': 'success', 'data': {}})
    except Exception as e:
        print('异步保存设备影子信息报错,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
        logger.info('更新设备影子异常: {}'.format(repr(e)))
        return JsonResponse(status=200, data={'code': 0, 'update_shadow_error': repr(e)})
