#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@AUTHOR: ASJRD018
@NAME: AnsjerFormal
@software: PyCharm
@DATE: 2019/1/14 15:57
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: DetectController.py
@Contact: chanjunkai@163.com
"""
import logging
import os
import time

import apns2
import jpush as jpush
import oss2
from django.http import JsonResponse
from django.views.generic.base import View
from pyfcm import FCMNotification

from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, DETECT_PUSH_DOMAIN, \
    JPUSH_CONFIG, FCM_CONFIG, APNS_CONFIG, \
    BASE_DIR, APNS_MODE, SERVER_TYPE, LOGGER, PUSH_REDIS_ADDRESS
from Model.models import Device_Info, Equipment_Info, UidSetModel, UidPushModel, SysMsgModel, \
    VodBucketModel
from Object.ETkObject import ETkObject
from Object.RedisObject import RedisObject
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Object.UidTokenObject import UidTokenObject
from Object.utils import LocalDateTimeUtil
from Service.CommonService import CommonService
from Service.EquipmentInfoService import EquipmentInfoService
from Service.VodHlsService import SplitVodHlsObject


class DetectControllerView(View):

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        # self.ip = CommonService.get_ip_address(request)
        return self.validation(request.GET, operation)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        # self.ip = CommonService.get_ip_address(request)
        return self.validation(request.POST, operation)

    def validation(self, request_dict, operation):
        response = ResponseObject()
        if operation is None:
            return response.json(444, 'error path')
        token = request_dict.get('token', None)
        tko = TokenObject(token)
        if tko.code == 0:
            userID = tko.userID
            # 修改推送设置
            if operation == 'changeStatus':
                print("进入changeStatus")
                return self.do_change_status(userID, request_dict, response)
            # 查询推送信息
            elif operation == 'queryInfo':
                return self.do_query(request_dict, response, userID)
            # 更新推送延迟
            elif operation == 'updateInterval':
                return self.do_update_interval(userID, request_dict, response)
            else:
                return response.json(414)
        else:
            return response.json(tko.code)

    def do_query(self, request_dict, response, userID):
        logger = logging.getLogger('info')
        logger.info("-----旧APP调用移动侦测查询")
        page = int(request_dict.get('page', None))
        line = int(request_dict.get('line', None))
        if not page or not line:
            return response.json(444, 'page,line')
        startTime = request_dict.get('startTime', None)
        endTime = request_dict.get('endTime', None)
        eventType = request_dict.get('eventType', None)
        uids = request_dict.get('uids', None)
        try:
            uid_list = []
            if uids:
                uid_list = uids.split(',')

            if not startTime and not endTime:
                # 默认查询近七天内数据
                endTime = int(time.time())
                startTime = LocalDateTimeUtil.get_before_days_timestamp(endTime, 7)

            qs, count = EquipmentInfoService. \
                union_equipment_info(userID, uid_list, eventType, startTime, endTime, page, line)
            logger.info('<<<|||分表查询结果count:{}'.format(count))
            uids = request_dict.get('uids', None)
            if uids:
                uid_list = uids.split(',')
                # qs = qs.filter(devUid__in=uid_list)
                dvqs = Device_Info.objects.filter(UID__in=uid_list, userID_id=userID).values('UID', 'Type', 'NickName')
                uid_type_dict = {}
                for dv in dvqs:
                    uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
            else:
                dvqs = Device_Info.objects.filter(userID_id=userID).values('UID', 'Type', 'NickName')
                uid_type_dict = {}
                for dv in dvqs:
                    uid_type_dict[dv['UID']] = {'type': dv['Type'], 'NickName': dv['NickName']}
            # print(uid_type_dict)
            if not qs or count == 0 or not qs.exists():
                return response.json(0, {'datas': [], 'count': 0})
            # if not qs.exists():
            #     return response.json(0, {'datas': [], 'count': 0})
            # qs = qs.values('id', 'devUid', 'devNickName', 'Channel', 'eventType', 'status', 'alarm', 'eventTime',
            #                'receiveTime', 'is_st', 'addTime')

            # count = qs.count()
            # qr = qs[(page - 1) * line:page * line]
            qr = qs
            res = []
            auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
            img_bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
            # vod_time_list = []
            for p in qr:
                devUid = p['devUid']
                eventTime = p['eventTime']
                channel = p['Channel']
                if p['is_st'] == 1:
                    p['img'] = img_bucket.sign_url('GET', '{uid}/{channel}/{time}.jpeg'.
                                                   format(uid=devUid, channel=p['Channel'], time=eventTime), 300)
                    p['img_list'] = [img_bucket.sign_url('GET', '{uid}/{channel}/{time}.jpeg'.
                                                         format(uid=devUid, channel=channel, time=eventTime), 300)]
                elif p['is_st'] == 2:
                    # 列表装载回放时间戳标记
                    split_vod_hls_obj = SplitVodHlsObject()
                    vodqs = split_vod_hls_obj.get_vod_hls_data(uid=devUid, channel=channel, start_time=int(eventTime)).values(
                        "bucket_id")
                    if not vodqs.exists():
                        return response.json(173)
                    vod_bucket_qs = VodBucketModel.objects.filter(id=vodqs[0]['bucket_id']).values('bucket', 'endpoint')
                    if not vod_bucket_qs.exists():
                        return response.json(173)
                    bucket_name = vod_bucket_qs[0]['bucket']
                    endpoint = vod_bucket_qs[0]['endpoint']
                    bucket = oss2.Bucket(auth, endpoint, bucket_name)
                    ts = '{uid}/vod{channel}/{etime}/ts0.ts'.format(uid=devUid, channel=p['Channel'],
                                                                    etime=eventTime)
                    thumb0 = bucket.sign_url('GET', ts, 3600,
                                             params={'x-oss-process': 'video/snapshot,t_0000,w_700'})
                    thumb1 = bucket.sign_url('GET', ts, 3600,
                                             params={'x-oss-process': 'video/snapshot,t_1000,w_700'})
                    thumb2 = bucket.sign_url('GET', ts, 3600,
                                             params={'x-oss-process': 'video/snapshot,t_2000,w_700'})
                    # thumb3 = bucket.sign_url('GET', ts, 3600, params={'x-oss-process': 'video/snapshot,t_3000,w_700'})
                    p['img_list'] = [thumb0, thumb1, thumb2]
                elif p['is_st'] == 3:
                    # 列表装载回放时间戳标记
                    p['img_list'] = []
                    for i in range(p['is_st']):
                        img = img_bucket.sign_url('GET', '{uid}/{channel}/{time}_{st}.jpeg'.
                                                  format(uid=devUid, channel=p['Channel'], time=eventTime, st=i), 300)
                        p['img_list'].append(img)
                if devUid in uid_type_dict.keys():
                    p['uid_type'] = uid_type_dict[devUid]['type']
                    p['devNickName'] = uid_type_dict[devUid]['NickName']
                else:
                    p['uid_type'] = ''
                res.append(p)
            return response.json(0, {'datas': res, 'count': count})
        except Exception as e:
            return response.json(474)

    def do_change_status(self, userID, request_dict, response):
        token_val = request_dict.get('token_val', None)
        jg_token_val = request_dict.get('jg_token_val', '')
        appBundleId = request_dict.get('appBundleId', None)
        app_type = request_dict.get('app_type', None)
        push_type = request_dict.get('push_type', None)
        status = request_dict.get('status', None)
        m_code = request_dict.get('m_code', None)
        uid = request_dict.get('uid', None)
        # 设备语言
        lang = request_dict.get('lang', 'en')
        tz = request_dict.get('tz', '0')
        domain_name = request_dict.get('domain_name', None)
        # 消息提醒功能新增

        # 如果传空上来，就默认为0
        if tz == '':
            tz = 0
        else:
            tz = tz.replace("GMT", "")
        detect_group = request_dict.get('detect_group', None)
        interval = request_dict.get('interval', None)
        if not status:
            return response.json(444, 'status')
        # 关闭推送
        if not all([appBundleId, app_type, token_val, uid, m_code]):
            return response.json(444, 'appBundleId,app_type,token_val,uid,m_code')
        # 判断推送类型对应key是否存在
        print('push_type:', push_type)

        dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
        status = int(status)
        # 获取用户区域
        # ip = self.ip
        # ipInfo = CommonService.getIpIpInfo(ip=ip, lang='EN')
        # area = ipInfo['country_name']
        # if area == 'China':
        #     DETECT_PUSH_DOMAIN = 'cn.push.dvema.com'
        # else:
        #     DETECT_PUSH_DOMAIN = 'en.push.dvema.com'

        nowTime = int(time.time())
        if dvqs.exists():
            # 修改状态
            device_type = dvqs[0].Type
            dvqs.update(NotificationMode=status)
            uid_set_qs = UidSetModel.objects.filter(uid=uid)
            # uid配置信息是否存在

            if uid_set_qs.exists():
                uid_set_id = uid_set_qs[0].id
                qs_data = {
                    'detect_status': status,
                    'updTime': nowTime,
                }
                if interval:
                    qs_data['detect_interval'] = int(interval)
                if detect_group:
                    qs_data['detect_group'] = detect_group
                if status == 0:
                    qs_data['detect_interval'] = 60
                    qs_data['new_detect_interval'] = 60
                uid_set_qs.update(**qs_data)

            else:
                qs_data = {
                    'uid': uid,
                    'addTime': nowTime,
                    'updTime': nowTime,
                    'detect_status': status,
                    'device_type': device_type
                }
                if interval:
                    qs_data['detect_interval'] = int(interval)
                if detect_group:
                    qs_data['detect_group'] = detect_group
                # 添加设备配置
                uid_set_qs = UidSetModel.objects.create(**qs_data)

                uid_set_id = uid_set_qs.id

            if status == 0:
                UidPushModel.objects.filter(uid_set__uid=uid).delete()
                # 状态为0的时候删除redis缓存数据
                self.do_delete_redis(uid)
                return response.json(0)
            elif status == 1:
                uid_push_qs = UidPushModel.objects.filter(userID_id=userID, m_code=m_code, uid_set__uid=uid)

                if uid_push_qs.exists():
                    uid_push_update_dict = {
                        'appBundleId': appBundleId,
                        'app_type': app_type,
                        'push_type': push_type,
                        'token_val': token_val,
                        'jg_token_val': jg_token_val,
                        'updTime': nowTime,
                        'lang': lang,
                        'tz': tz
                    }
                    uid_push_qs.update(**uid_push_update_dict)
                else:
                    # uid_set_id = uid_set_qs[0].id
                    uid_push_create_dict = {
                        'uid_set_id': uid_set_id,
                        'userID_id': userID,
                        'appBundleId': appBundleId,
                        'app_type': app_type,
                        'push_type': push_type,
                        'token_val': token_val,
                        'jg_token_val': jg_token_val,
                        'm_code': m_code,
                        'addTime': nowTime,
                        'updTime': nowTime,
                        'lang': lang,
                        'tz': tz
                    }
                    # 绑定设备推送
                    UidPushModel.objects.create(**uid_push_create_dict)
                if interval:
                    self.do_delete_redis(uid, int(interval))
                else:
                    self.do_delete_redis(uid)
                # utko = UidTokenObject()
                # # right
                # utko.generate(data={'uid': uid})
                etkObj = ETkObject(etk='')
                etk = etkObj.encrypt(uid)
                if domain_name in ['api.zositeche.com', 'api.loocam3.com', 'common.neutral3.com']:
                    detectUrl = 'http://push.zositeche.com/notify/push?etk={etk}'.format(etk=etk)
                else:
                    detectUrl = "{DETECT_PUSH_DOMAIN}notify/push?etk={etk}". \
                        format(etk=etk, DETECT_PUSH_DOMAIN=DETECT_PUSH_DOMAIN)
                return response.json(0, {'detectUrl': detectUrl})
        else:
            return response.json(14)

    def do_delete_redis(self, uid, detect_interval=0):
        keyPattern = '{uid}*'.format(uid=uid)
        redisObj = RedisObject(host=PUSH_REDIS_ADDRESS)
        keys = redisObj.get_keys(keyPattern)
        if keys:
            for key in keys:
                key = key.decode()
                if detect_interval == 0:
                    redisObj.del_data(key=key)
                elif key.find('plt') != -1:
                    continue
                elif key.find('flag') != -1:
                    redisObj.set_data(key=key, val=1, expire=detect_interval)
                else:
                    redisObj.del_data(key=key)

    def do_update_interval(self, userID, request_dict, response):
        uid = request_dict.get('uid', None)
        interval = request_dict.get('interval', None)
        dvqs = Device_Info.objects.filter(userID_id=userID, UID=uid)
        if dvqs.exists():
            uid_set_qs = UidSetModel.objects. \
                filter(uid=uid, uidpushmodel__userID_id=userID)
            if uid_set_qs.exists():
                uid_set_qs.update(detect_interval=int(interval))
            else:
                return response.json(173)
        else:
            return response.json(0)
