#!/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/7 9:27
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: EquipmentStat.py
@Contact: chanjunkai@163.com
"""
import base64
import json
import threading
import urllib.parse
import time
import oss2
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET
from Model.models import Device_Info
from Object.ETkObject import ETkObject
from Object.RedisObject import RedisObject
from Object.ResponseObject import ResponseObject
from Service.ModelService import ModelService
from Service.CommonService import CommonService

'''
http://192.168.136.45:8077/device/online?UID=C2887N9EBS87ZAT1111A
http://192.168.136.45:8077/device/offline?UID=C2887N9EBS87ZAT1111A
http://192.168.136.45:8077/device/updateIP?UID=C2887N9EBS87ZAT1111A?ip=190.9.194.216
'''


@csrf_exempt
def EquipmentOnline(request):
    response = ResponseObject()
    if request.method == 'GET':
        request.encoding = 'utf-8'
        UID = request.GET.get('UID', None)
    if request.method == 'POST':
        request.encoding = 'utf-8'
        UID = request.POST.get('UID', None)
    qs = Device_Info.objects.filter(UID=UID)
    if not qs.exists():
        return response.json(173)


@csrf_exempt
def EquipmentOffline(request):
    response = ResponseObject()
    if request.method == 'GET':
        request.encoding = 'utf-8'
        UID = request.GET.get('UID', None)
    if request.method == 'POST':
        request.encoding = 'utf-8'
        UID = request.POST.get('UID', None)
    qs = Device_Info.objects.filter(UID=UID)
    if not qs.exists():
        return response.json(173)
    try:
        qs.update(Online=False)
    except Exception as e:
        print(repr(e))
    return response.json(0)


@csrf_exempt
def updateIP(request):
    response = ResponseObject()
    if request.method == 'GET':
        request.encoding = 'utf-8'
        request_dict = request.GET
    if request.method == 'POST':
        request.encoding = 'utf-8'
        request_dict = request.POST
    UID = request_dict.get('UID', None)
    ip = request_dict.get('ip', None)
    qs = Device_Info.objects.filter(UID=UID)
    if not qs.exists():
        return response.json(173)
    area = ''
    try:
        area = CommonService.getAddr(ip=ip)
        qs.update(ip=ip, area=area)
    except Exception as e:
        print(repr(e))
    return response.json(0, {'area': area})


def getTZ(request):
    request.encoding = 'utf-8'
    if request.method == 'GET':
        request_dict = request.GET
    elif request.method == 'POST':
        request_dict = request.POST
    else:
        return JsonResponse(status=200, data={'code': 403, 'msg': '接口请求方法错误'})
    c = request_dict.get('etk', None)
    ip = request_dict.get('ip', None)
    lang = request_dict.get('lang', None)
    update = request_dict.get('update',None)
    if not ip:
        ip = CommonService.get_ip_address(request)
    if c:
        c = base64.b64decode(c)
        c = c[2:-2]
        c = urllib.parse.unquote(c.decode('utf-8'))
        c = base64.b64decode(c)
        uid = c.decode('utf-8')
        if len(uid) == 20:
            print(uid)
            redisObject = RedisObject(db=7)
            data = redisObject.get_data(key=ip)

            if data:
                info = json.loads(data)
                return JsonResponse(status=200, data={'code': 0, 'msg': 'success', 'data': info})
            elif update:
                info = CommonService.getIpIpInfo(ip=ip, lang=lang,update=True)
            else:
                info = CommonService.getIpIpInfo(ip=ip, lang=lang,update=False)
            try:
                tz = info['utc_offset']
                # 增加GMT,且补:00
                if len(tz) == 5:
                    gmtz = tz.replace('UTC-', 'GMT-0').replace('UTC+', 'GMT+0')
                    if ':' not in gmtz:
                        gmtz = gmtz + ':00'
                    info['gmt_offset'] = gmtz
                elif len(tz) == 8:
                    gmtz = tz.replace('UTC-', 'GMT-0').replace('UTC+', 'GMT+0')
                    info['gmt_offset'] = gmtz
                redisObject.set_data(key=ip, val=json.dumps(info), expire=3600)
            except Exception as e:
                pass
            return JsonResponse(status=200, data={'code': 0, 'msg': 'success', 'data': info})
        else:
            return JsonResponse(status=200, data={'code': 404, 'msg': '令牌错误'})
    else:
        return JsonResponse(status=200, data={'code': 444, 'msg': '接口参数错误 etk'})


# 设备日志上传
def getUploadLogUrl(request):
    request.encoding = 'utf-8'
    if request.method == 'GET':
        request_dict = request.GET
    elif request.method == 'POST':
        request_dict = request.POST
    else:
        return JsonResponse(status=200, data={'code': 403, 'msg': 'wrong post method!'})
    etk = request_dict.get('etk', None)
    eto = ETkObject(etk)
    uid = eto.uid
    if len(uid) == 20:
        auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
        bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
        nowTime = int(time.time())
        obj = 'log/{uid}/'.format(uid=uid) + str(nowTime) + '.log'
        url = bucket.sign_url('PUT', obj, 7200)
        return JsonResponse(status=200, data={'code': 0, 'msg': 'success', 'url': url})
    else:
        return JsonResponse(status=200, data={'code': 404, 'msg': 'wrong etk'})
