from json import JSONDecodeError
import json
import datetime
from django.conf import settings
from kedong.decoration import kedong_deco, PortError
from smartfarming.models.device import MongoDevice, MongoCBDData, DevicePestWarning
from smartfarming.models.worm_forecast import MongoCBDphoto
from smartfarming.models.pest_count import MongoCBDPestWarning
from smartfarming.models.weather import QXZThresholdWarning, QXZstatus_New, MongoQXZ_Conf


@kedong_deco(login_required=True)
def get_cbd_info(request):
    """
     获取基地绑定设备列表
        参数：
            device_id       必须      设备编码

        返回值：
        {
            "data": {
                'device_id': "1111111111111",           设备id
                'device_name': "abc",                   设备名称
                'address': "dizhi",                      设备地址
                'uptime': "2022-01-01 12:12",           上报时间
                "upds": 1,              上仓门状态 1打开,0关闭
                "tpl": 5,               低温保护阈值温度
                "dver": "1.0.0",        设备固件版本
                "gs": 0,                通道状态 1落虫,0排水
                "hs": 0,                加热状态 1加热,0正常
                "dnds": 0,              下仓门状态 1打开,0关闭
                "is_online": 0,         在线状态
                "csq": 29,              信号强度
                "tph": 70,              高温保护阈值温度
                "ts": 0                 定时模式 0光控,1时控
                "tps": 1                温控状态 1 温控,0 正常
                "lps": 0                光控状态 1 光控,0 正常
                "hrt": 22               加热仓实时温度
                'img_list': img_list,                   图片列表
                'warning_info': {                       警报信息
                    "warning_status": 1,                预警类型, 1目标种类预警 2、指定害虫数量预警  3 害虫数量总和预警 4综合预警
                    "warning_content": 'xxxxxx"         预警内容
                }
            },
            "errorCode": 0,
            "message": ,
            "formError": {}
        }

    """
    config_dict = settings.CONFIG
    device_id = request.POST.get('device_id', '').strip()
    device_info = MongoDevice.objects.get(device_id=device_id)
    d_id = device_info.id
    device_data = MongoCBDData.objects.filter(device_id=device_id).order_by('-id').first()
    if device_data:
        try:
            device_data = json.loads(device_data.device_data)
        except JSONDecodeError as e:
            device_data = eval(device_data.device_data)
        except:
            raise PortError("device_id", "暂无数据")
    else:
        raise PortError("device_id", "暂无数据")

    device_addr = f'{device_info.province}{device_info.city}{device_info.district}'
    photo_list = MongoCBDphoto.objects.filter(device_id=d_id, photo_status=1).order_by("-id")
    up_date = datetime.datetime.utcfromtimestamp(device_info.uptime)

    http_img_url = config_dict["image_url"]["image"]
    img_list = []
    for p in photo_list[:3]:
        img_url = p.indentify_photo
        if not img_url:
            img_url = p.addr
        if not img_url.startswith('http'):
            img_url = http_img_url + img_url

        img_list.append(img_url)
    warning_content = MongoCBDPestWarning.objects.filter(device_id=device_id).order_by("-id").values_list("warning_content", flat=True)
    warning_info = {}
    warning_info['warning_content'] = [i for i in warning_content]
    

    tmp_device_id = device_info.device_id
    device_name = device_info.device_name

    result = {
        'device_id': tmp_device_id,
        'device_name': device_name or tmp_device_id,
        'uptime': up_date.strftime("%Y-%m-%d %H:%M:%S"),
        'img_list': img_list,
        'warning_info': warning_info,
        "is_online": device_info.device_status,
        "ts": device_data.get("ts", 1),
        "hs": device_data.get("hs", ""),
        "upds": device_data.get("upds", ""),
        "dnds": device_data.get("dnds", ""),
        "csq": device_data.get("csq", ""),
        "dver": device_data.get("dver", ""),
        "tph": device_data.get("tph", ""),
        "tpl": device_data.get("tpl", ""),
        "tps": device_data.get("tps", ""),
        "lps": device_data.get("lps", ""),
        "hrt": device_data.get("hrt", ""),
        "rps": device_data.get("rps", ""),
        "ds": device_data.get("ds", 1),
        "address": device_addr,
    }
    return result



@kedong_deco(login_required=True)
def get_qxz_or_sq_info(request):
    """
    气象站或者墒情站数据详情接口
    """
    device_id = request.POST.get('device_id', '').strip()
    device_info = MongoDevice.objects.get(device_id=device_id)
    device_addr = f'{device_info.province}{device_info.city}{device_info.district}'
    up_date = datetime.datetime.utcfromtimestamp(device_info.uptime)

    warning_queryset = QXZThresholdWarning.objects.filter(device_id=device_id, status=0).order_by("-id")
    warning_info = {}
    try:
        warn = warning_queryset[0]
        warning_info['set_value'] = warn.set_value
        warning_info['current_value'] = warn.current_value
        warning_info['ekey'] = warn.ekey
        warning_info['warning_content'] = warn.warning_content
    except Exception as e:
        pass

    conf, dat = {}, {}
    try:
        qxz_status = QXZstatus_New.objects.filter(device_id=device_id).order_by('-id')[0]
        qxz_conf = MongoQXZ_Conf.objects.get(device_id=device_id)
        for i in range(1, 31):
            k = f'e{i}'
            conf[k] = getattr(qxz_conf, k)
            dat[k] = getattr(qxz_status, k)
    except Exception as e:
        pass

    temp_device_id = device_info.device_id
    device_name = device_info.device_name
    result = {
        'device_id': temp_device_id,
        'device_name': device_name or temp_device_id,
        'address': device_addr,
        'uptime': up_date.strftime("%Y-%m-%d %H:%M:%S"),
        'device_status': "在线" if device_info.device_status == 1 else "离线",
        'warning_info': warning_info,
        'conf': conf,
        'dat': dat,
    }
    return result
