import json
import time

from django.http import JsonResponse

from Ansjer.config import SERVER_TYPE, LOGGER, CONFIG_INFO, CONFIG_CN
from Model.models import Device_Info, UidSetModel, UID_Preview, VoicePromptModel, UidChannelSetModel, \
    AiService, CountryModel, CityInformation, IPAddr, LogModel
from Object.ETkObject import ETkObject
from Object.RedisObject import RedisObject
from Service.CommonService import CommonService
from Object.IPWeatherObject import IPQuery, GeoIP2


# 更新设备影子
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.info('---更新设备影子---,使用配置:{}, 参数:{}'.format(SERVER_TYPE,
                                                     json.dumps(request_dict.dict())))
    # redis加锁
    redis_obj = RedisObject()
    redis_key = None

    try:
        etk = request_dict.get('etk', None)
        eto = ETkObject(etk)
        uid = eto.uid
        if not uid:
            return JsonResponse(status=200, data={'code': 400001, 'msg': 'The UID length or format is incorrect.',
                                                  'data': {}})

        nowTime = int(time.time())
        ip = CommonService.get_ip_address(request)
        # 重置按钮
        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)

            # 删除预览图
            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()

            # 关闭移动侦测推送
            UidSetModel.objects.filter(uid=uid).update(detect_status=0)
            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('{}v2重置成功'.format(uid))

            # 更新ip信息
            update_ip_info(ip, uid)
        else:
            redis_key = f"DEVICE:UPDATE:SHADOW:{uid}"
            is_lock = redis_obj.CONN.set(redis_key, value=1, nx=True, ex=60)
            if not is_lock:
                return JsonResponse(status=200, data={'code': 5, 'msg': 'Please try again one minute later!',
                                                      'data': {}})
        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)
        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)
        ai_type = request_dict.get('AiType', 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
        if ai_type:
            qs_dict['ai_type'] = ai_type
        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))

        save_ip_info(ip, 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)

        # 记录操作日志
        content = json.loads(json.dumps(request_dict))
        log = {
            'ip': ip,
            'user_id': 1,
            'status': 200,
            'time': nowTime,
            'content': json.dumps(content),
            'url': 'deviceShadow/updateV2',
            'operation': f'{uid}更新设备影子',
        }
        LogModel.objects.create(**log)

        if redis_key:
            redis_obj.del_data(redis_key)
        return JsonResponse(status=200, data={'code': 0, 'msg': 'success', 'data': {}})
    except Exception as e:
        if redis_key:
            redis_obj.del_data(redis_key)
        LOGGER.info('更新设备影子异常: errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
        return JsonResponse(status=200, data={'code': 1000001, 'update_shadow_error': repr(e)})


def save_ip_info(ip, qs_dict):
    """
    保存ip信息
    根据服务器配置使用不同的服务, 国内:阿里云, 测试,国外:geoip2
    @param ip:
    @param qs_dict:
    @return:
    """
    if CONFIG_INFO == CONFIG_CN:
        # 查询ip区级信息
        district = get_district(ip)

        city_information_qs = CityInformation.objects.filter(district=district).values('city_id')
        if city_information_qs.exists():
            city_id = city_information_qs[0]['city_id']
            qs_dict['tb_city_information_id'] = city_id
    else:
        ip_addr_qs = IPAddr.objects.filter(ip=ip, is_geoip2=True)
        if not ip_addr_qs.exists():
            GeoIP2(ip)


def update_ip_info(ip, uid):
    """
    更新ip信息
    根据服务器配置使用不同的服务, 国内:阿里云, 测试,国外:geoip2
    @param ip:
    @param uid:
    @return:
    """
    if CONFIG_INFO == CONFIG_CN:
        # 和新ip的city_id不一致,更新tb_city_information_id
        uid_set_qs = UidSetModel.objects.filter(uid=uid).values('ip', 'tb_city_information_id')
        if uid_set_qs.exists():
            # 查询ip区级信息
            district = get_district(ip)

            city_information_qs = CityInformation.objects.filter(district=district).values('city_id')
            if city_information_qs.exists():
                city_id = city_information_qs[0]['city_id']
                if uid_set_qs[0]['tb_city_information_id'] != city_id:
                    uid_set_qs.update(tb_city_information_id=city_id)
    else:
        ip_addr_qs = IPAddr.objects.filter(ip=ip, is_geoip2=True)
        if not ip_addr_qs.exists():
            GeoIP2(ip)


def get_district(ip):
    ip_addr_qs = IPAddr.objects.filter(ip=ip, is_geoip2=False).values('district', 'city')
    if ip_addr_qs.exists():
        district = ip_addr_qs[0]['district']
        city = ip_addr_qs[0]['city']
        # 区级信息为空或city_information表查询不到区级信息,使用城市数据
        if district == '':
            district = city
        else:
            city_information_qs = CityInformation.objects.filter(district=district)
            if not city_information_qs.exists():
                city_qs = CityInformation.objects.filter(district=city)
                if city_qs.exists():
                    district = city
    else:
        ip_qs = IPQuery(ip)
        district = ip_qs.district
    return district
