import re
import requests
import time
from django.conf import settings
from django.db.models import Count
from django.core.paginator import Paginator

from smartfarming.api.views.forecast.all_dict import insect_dict, attract_discern
from smartfarming.models.sim_card import MongoMsg_Conf
from smartfarming.models.device import MongoDevice
from smartfarming.models.camera import MongoCameraPhoto, MongoCameraData, MongoCameraAccount
from smartfarming.serializers.device_serializers import DeviceSerializers
from smartfarming.utils import controlMove

from kedong.decoration import kedong_deco, PortError
config_dict = settings.CONFIG


@kedong_deco(login_required=True)
def list_camera(request):
    """
    获取监控设备列表 ：
    参数：
    
    page                    非必传(num)                     页码，默认为1
    device_id               非必传                          设备ID, 不传为监控列表， 传设备号为搜索
    page_size               非必传                          一页条数，默认为10

    返回值：
    {
    "data": {
        data : {
            "device_name":"",                            设备名称
            "device_id":"",                              设备ID
            "photo_num":"",                              是否拍过照片 0未拍过  1拍过
            "status":"",                                 设备状态  0离线  1在线
            "camera_playback":""                         用来判断是否有录像功能 0不支持 1支持
            "sim":""                                     监控SIM 卡
        }            
        counts : 99                                总数
            } 
    "errorCode": 0,
    "message": "",
    "formError": {}
    }

    """
    _list = []
    myuser = request.myuser
    post_info = request.POST
    device_id = post_info.get('device_id')
    page = int(post_info.get('page', 1))
    page_size = int(post_info.get('page_size', 10))

    search_dict = {
        "device_type_id": 6
    }
    if device_id:
        search_dict["device_id"] = re.compile(fr"^.*{device_id}.*$")

    # total_num, data_list = MongoDevice.get_device_list(myuser, match=search_dict, page_num=page, page_size=page_size)

    queryset = MongoDevice.objects.filter(device_type_id=6)
    total_num = queryset.count()
    paginator = Paginator(queryset, page_size)
    page_obj = paginator.get_page(page)
    serializers = DeviceSerializers(page_obj, many=True)
    data_list = serializers.data
    _list = []
    device_id_list = []
    for x in data_list:
        device_id = x.get("device_id")
        device_id_list.append(device_id)

        _list.append({
            "device_name": x.get("device_name"),
            "device_id": device_id,
            "photo_num": "",
            "status": x.get("device_status"),
            "camera_playback": "",
            "sim": x.get("simid")
        })

    photo_queryset = MongoCameraPhoto.objects.filter(device_id__in=device_id_list, photo_status=1).values('device_id').annotate(count=Count('device_id'))
    phote_dict = {p['device_id']: "1" for p in photo_queryset}
    playback_dict = {y['device_id']: y["camera_playback"] for y in MongoCameraData.objects.filter(device_id__in=device_id_list).values('device_id','camera_playback')}

    for item in _list:
        item["photo_num"] = phote_dict.get(device_id, "0")
        item["camera_playback"] = playback_dict.get(device_id,"0")
    datas = {"data": _list, "counts": total_num}
    return datas


@kedong_deco(login_required=True)
def addr_camera_list(request):
    """
    获取监控设备播放地址 
    参数:
    device_id           必传  (string)                  监控设备的序列号

    返回值:
    {
    "data": {
            "hls": "http://test.ys7.com:66/openlive/b475942b03544a5aa35b651670d8712c.m3u8",                  HLS流畅直播地址
            "hlsHd": "http://test.ys7.com:66/openlive/b475942b03544a5aa35b651670d8712c.hd.m3u8",             HLS高清直播地址
            "rtmp": "rtmp://10.82.0.190:1935/openlive/b475942b03544a5aa35b651670d8712c",                     RTMP流畅直播地址
            "rtmpHd": "rtmp://10.82.0.190:1935/openlive/b475942b03544a5aa35b651670d8712c.hd"                 RTMP高清直播地址
            }
    "errorCode": 0,
    "message": "",
    "formError": {}
    }

    """

    try:
        if 'HTTP_X_FORWARDED_FOR' in request.META:
            ip = request.META['HTTP_X_FORWARDED_FOR']
        else:
            ip = request.META['HTTP_X_REAL_IP']
    except Exception as KeyError:
        ip = request.META['REMOTE_ADDR']



    device_id = request.POST.get('device_id')
    # try:
    #     ic = InterfaceCallLog()
    #     ic.ip = ip
    #     ic.device_id = device_id
    #     ic.interface = "addr_camera_list"
    #     ic.meta = str(request.META)
    #     ic.save()
    # except Exception as e:
    #     pass

    # if device_id in jk_list.keys():
    #     if redis_pool.get(device_id):
    #         url_path = redis_pool.get(device_id)
    #     else:
    #         cameraIndexCode = jk_list.get(device_id,"")
    #         url = "http://223.151.55.58:8082/zhcg-serve/hkVideo/api/getPreviewURLsByHls?cameraIndexCode={}&streamType=0".format(cameraIndexCode)
    #         try:
    #            url_path = (requests.get(url,timeout=5).json())["data"]["url"]
    #         except:
    #             url_path = "" 
    #         # 设置播放地址到期时间5分钟
    #         redis_pool.set(device_id,url_path,300)
    #     # 因为其他设备返回的数值是字符串的,所以进行拼接
    #     data =  "{'hls':'%s','hlsHd':'%s','rtmp':'%s','rtmpHd':'%s'}"%(url_path,url_path,url_path,url_path)
    #     return data

    try:
        addr = MongoCameraData.objects.get(device_id=device_id).device_info
    except:
        addr = {}
    return addr


@kedong_deco(login_required=True)
def ctrl_camera(request):
    """
    控制监控设备转动 :
    参数:
    device_id          必传  (string)                  监控设备的序列号
    ctrl               必传  (string)                  操作指令  move 控制球机转动   stop 停止球机转动
    movenum            ctrl=move时必传(string)         0-上,1-下,2-左,3-右,8-放大,9-缩小

    返回值:
    {
    "data": success,     success成功   default失败
    "errorCode": 0,
    "message": "",
    "formError": {}
    }

    """
    device_id = request.POST.get('device_id')
    ctrl = request.POST.get('ctrl')
    account_id = MongoCameraData.objects.filter(device_id=device_id).first()
    if not account_id:
        raise PortError("","未找到此设备")
    camera_query = MongoCameraAccount.objects.filter(id=int(account_id.account_id)).first()
    if not camera_query:
        raise PortError("","未找到此账号")
    channelNo = "1"
    if device_id.find("-") != -1:
        channelNo = device_id.split("-")[1]
        device_id = device_id.split("-")[0]
    # 操作命令:0-上,1-下,2-左,3-右,4-左上,5-左下,6-右上,7-右下,8-放大,9-缩小,10-近焦距,11-远焦距
    if ctrl == "move":
        dire = request.POST.get('movenum')
        # 增加大华相机操作功能
        if camera_query.account_type == 1:
            if dire not in ("0","1","2","3","8","9"):
                raise PortError("movenum","暂不支持其它指令")
            appId = camera_query.app_key
            appSecret = camera_query.app_secret
            controlMove(appId,appSecret,device_id,dire,channelNo)
        else:
            accessToken = camera_query.token
            ctrl_url = 'https://open.ys7.com/api/lapp/device/ptz/start'
            speed = '1'
            data = {'accessToken':accessToken, 'deviceSerial':device_id, 'channelNo':channelNo, 'speed':speed, 'direction':dire}
            res1 = requests.post(ctrl_url,data=data)
    elif ctrl == "stop":
        time.sleep(0.4)
        # 增加大华相机操作功能
        if camera_query.account_type == 1:
            dire = "10"
            appId = camera_query.app_key
            appSecret = camera_query.app_secret
            controlMove(appId,appSecret,device_id,dire,channelNo)
        else:
            accessToken = camera_query.token
            ctrl_url = 'https://open.ys7.com/api/lapp/device/ptz/stop'
            data = {'accessToken':accessToken, 'deviceSerial':device_id, 'channelNo':channelNo}
            res2 = requests.post(ctrl_url,data=data)
    return True