# -*- coding:utf-8 -*-
# @Time    : 2020/5/22 2:22 下午
# @Author  : Creat by Han
import json

import copy
import datetime
import time
import os
import requests
from django.forms.models import model_to_dict
from django.db.models import Q
from django.conf import settings
from kedong.decoration import kedong_deco, PortError
from smartfarming.models.device import MongoDevice
from smartfarming.models.weather import MongoQXZ_Base_Info, QXZdata_New, MongoQXZ_Conf, QXZstatus_New
from smartfarming.api.views.weather.all_dict import qxz_dict

config_dict = settings.CONFIG


@kedong_deco(login_required=True)
def qxz_page(request):
    """
    气象设备列表接口 :
    参数:
    page                    非必传(num)                     页码,默认为1
    device_id               非必传(str)                     设备号
    device_status           非必传(str)                     在线状态 1在线 0离线
    device_name             非必传(str)                     设备名称
    device_type             非必传(str)                      5气象站 8墒情站
    返回值:
    {
        "data": {                       
        "ids": [
            {
                "d_id":"",                              设备数据库ID
                "equip_name":"",                        设备名称
                "equip_id":12313456,                    设备ID
                "is_online":1,                          在线状态   1在线 0离线
                "rssi":10,                              信号强度
                "volt":22,                              电压
                "lng":113,                              经度
                "lat":113,                              纬度
                "off_time":""                           离线时间
                "address":""                            设备地址
                "device_expire_time": 1234444     设备到期时间
                "device_expire": # 设备状态 0未到期,1已到期,2即将到期
                "device_expire_days": 到期天数
                }
            ],                  
        "nums": 0                                       设备总数
        },
        "formError": {},
        "errorCode": 0,
        
        "message": "",
        "params": {}
    }

    """
    device_id = request.POST.get("device_id")
    device_status = request.POST.get("device_status")
    device_name = request.POST.get("device_name")
    page = request.POST.get("page","")
    page_size = request.POST.get("page_size","")
    device_type = request.POST.get("device_type","5")
    if not page and not page_size:
        page = 1 
        page_size = 8
    else:
        if not page.isdigit() and  not page_size.isdigit():
            raise PortError("","字段类型有误")
        else:
            page = int(page)
            page_size = int(page_size)
    
    if device_type not in ("5","8"):
        raise PortError("","参数超出范围")


    devices = MongoDevice.objects.filter(device_type_id=device_type).order_by('-device_status', '-uptime')
    #设备状态查询
    if device_status:
        devices = devices.filter(device_status=int(device_status))
    #设备号查询
    if device_id:
        devices = devices.filter(Q(device_id__icontains=device_id) | Q(device_name__icontains=device_id))
    #设备名称查询
    if device_name:
        devices = devices.filter(device_name__icontains=device_name)

    date = []
    nums = devices.count()

    result = devices[(page_size*(page-1)):(page*page_size)]
    result_device_id_list = [item.device_id for item in result]
    qxz_base_dict = {item.device_id: item for item in MongoQXZ_Base_Info.objects.filter(device_id__in=result_device_id_list)}
    for i in result:
        try:
            qxz_base = qxz_base_dict[i.device_id]
            rssi = qxz_base.rssi
            volt = qxz_base.volt
        except:
            rssi = ""
            volt = ""
            
        lng = i.lng
        lat = i.lat
        address = i.province+i.city+i.district
        is_online = i.device_status
        uptime = i.uptime

        date.append({
            "d_id":i.id,
            "equip_name":i.device_name,
            "equip_id":i.device_id,
            "volt":volt,
            "rssi":rssi,
            "lng":lng,
            "lat":lat,
            "address":address,
            "is_online":is_online,
            "uptime":uptime,
        })
    
    data = {'ids':date, 'nums': nums}
    return data


@kedong_deco(login_required=True)
def qxz_detail(request):
    """
    气象历史数据接口 ：
    参数：
    device_id               必传(string)
    page                    非必传(num)                     页码，默认为1
    start_time              非必传(string 时间戳)           开始时间    (用于时间搜索)
    end_time                非必传(string 时间戳)           结束时间    (用于时间搜索)

    返回值：
    {
        "data": {
            "conf": {
            "e1":x.e1,"e2":x.e2,"e3":x.e3,"e4":x.e4,"e5":x.e5,
            "e6":x.e6,"e7":x.e7,"e8":x.e8,"e9":x.e9,"e10":x.e10,
            "e11":x.e11,"e12":x.e12,"e13":x.e13,"e14":x.e14,
            "e15":x.e15,"e16":x.e16,"e17":x.e17,"e18":x.e18,
            "e19":x.e19,"e20":x.e20,"e21":x.e21,"e22":x.e22,
            "e23":x.e23,"e24":x.e24,"e25":x.e25,"e26":x.e26,
            "e27":x.e27,"e28":x.e28,"e29":x.e29,"e30":x.e30
            },
            "nums": 0,
            "rainFall": 1              气象设备是否具有日雨量累计因子,有返回1,无返回0
            "data": [
                {
                "e1":qxz_list.e1,"e2":qxz_list.e2,"e3":qxz_list.e3,"e4":qxz_list.e4,"e5":qxz_list.e5,
                "e6":qxz_list.e6,"e7":qxz_list.e7,"e8":qxz_list.e8,"e9":qxz_list.e9,"e10":qxz_list.e10,
                "e11":qxz_list.e11,"e12":qxz_list.e12,"e13":qxz_list.e13,"e14":qxz_list.e14,
                "e15":qxz_list.e15,"e16":qxz_list.e16,"e17":qxz_list.e17,"e18":qxz_list.e18,
                "e19":qxz_list.e19,"e20":qxz_list.e20,"e21":qxz_list.e21,"e22":qxz_list.e22,
                "e23":qxz_list.e23,"e24":qxz_list.e24,"e25":qxz_list.e25,"e26":qxz_list.e26,
                "e27":qxz_list.e27,"e28":qxz_list.e28,"e29":qxz_list.e29,"e30":qxz_list.e30, 
                "upl_time":qxz_list.upl_time.strftime('%Y-%m-%d %H:%M:%S')
                },
                {
                "e1":qxz_list.e1,"e2":qxz_list.e2,"e3":qxz_list.e3,"e4":qxz_list.e4,"e5":qxz_list.e5,
                "e6":qxz_list.e6,"e7":qxz_list.e7,"e8":qxz_list.e8,"e9":qxz_list.e9,"e10":qxz_list.e10,
                "e11":qxz_list.e11,"e12":qxz_list.e12,"e13":qxz_list.e13,"e14":qxz_list.e14,
                "e15":qxz_list.e15,"e16":qxz_list.e16,"e17":qxz_list.e17,"e18":qxz_list.e18,
                "e19":qxz_list.e19,"e20":qxz_list.e20,"e21":qxz_list.e21,"e22":qxz_list.e22,
                "e23":qxz_list.e23,"e24":qxz_list.e24,"e25":qxz_list.e25,"e26":qxz_list.e26,
                "e27":qxz_list.e27,"e28":qxz_list.e28,"e29":qxz_list.e29,"e30":qxz_list.e30, 
                "upl_time":qxz_list.upl_time.strftime('%Y-%m-%d %H:%M:%S')
                },...
            ]
            }
        "params": {},
        "formError": {},
        "errorCode": 0,
        "message": "",
    
    }

    """
    f_tbegin = request.POST.get('start_time')
    f_tend = request.POST.get('end_time')
    device_id = request.POST.get("device_id")
    
    try:
        device = MongoDevice.objects.get(device_id=device_id)
        device_expire = device.device_expire
        device_expire_time = device.device_expire_time
    except:
        raise PortError('device_id',"暂无此设备")
    
    qxz_list = QXZdata_New.objects.filter(device_id=device_id)
    
    myuser_type = request.user_type
    if not myuser_type == 1 and not myuser_type == 5:
        if f_tbegin and int(f_tend) > int(device_expire_time):
            f_tend = device_expire_time
    if f_tbegin and f_tend:
        qxz_list =qxz_list.filter(uptime__range=(int(f_tbegin),int(f_tend))).order_by('-id')
    page = int(request.POST.get('page',1))
    data = []
    nums = qxz_list.count()
    conf = {}
    if nums:
        for i in qxz_list[(10*(page-1)):(page*10)]:
            dat = {}
            for e in range(1, 31):
                k = f'e{e}'
                v = getattr(i, k)
                dat[k] = v or ""
            data.append({"dat": dat, "time": i.uptime})

        try:
            x = MongoQXZ_Conf.objects.get(device_id=device_id)
            conf = {}
            for e in range(1, 31):
                k = f'e{e}'
                v = getattr(x, k)
                conf[k] = v or ""
        except Exception as e:
            conf = {}
    rainFall = 0
    for factor in conf.values():
        if factor == "降雨量累计#mm":
            rainFall = 1
            break
    data1 = {"data":data,"nums":nums,"conf":conf,"rainFall":rainFall}
    return data1


@kedong_deco(login_required=True)
def qxz_status(request):
    """
    气象详情接口 :
    参数:
    device_id               必传(string)
    返回值:
    {
    "data": {
        'dat':{
                "e1":qxz_list.e1,"e2":qxz_list.e2,"e3":qxz_list.e3,"e4":qxz_list.e4,"e5":qxz_list.e5,
                "e6":qxz_list.e6,"e7":qxz_list.e7,"e8":qxz_list.e8,"e9":qxz_list.e9,"e10":qxz_list.e10,
                "e11":qxz_list.e11,"e12":qxz_list.e12,"e13":qxz_list.e13,"e14":qxz_list.e14,
                "e15":qxz_list.e15,"e16":qxz_list.e16,"e17":qxz_list.e17,"e18":qxz_list.e18,
                "e19":qxz_list.e19,"e20":qxz_list.e20,"e21":qxz_list.e21,"e22":qxz_list.e22,
                "e23":qxz_list.e23,"e24":qxz_list.e24,"e25":qxz_list.e25,"e26":qxz_list.e26,
                "e27":qxz_list.e27,"e28":qxz_list.e28,"e29":qxz_list.e29,"e30":qxz_list.e30, 
                "upl_time":qxz_list.upl_time.strftime('%Y-%m-%d %H:%M:%S')
                },
        'conf':{
            "e1":x.e1,"e2":x.e2,"e3":x.e3,"e4":x.e4,"e5":x.e5,
            "e6":x.e6,"e7":x.e7,"e8":x.e8,"e9":x.e9,"e10":x.e10,
            "e11":x.e11,"e12":x.e12,"e13":x.e13,"e14":x.e14,
            "e15":x.e15,"e16":x.e16,"e17":x.e17,"e18":x.e18,
            "e19":x.e19,"e20":x.e20,"e21":x.e21,"e22":x.e22,
            "e23":x.e23,"e24":x.e24,"e25":x.e25,"e26":x.e26,
            "e27":x.e27,"e28":x.e28,"e29":x.e29,"e30":x.e30
            },
            "led":0,           0 无led点阵屏功能  1 有led点阵屏功能                                    
            "ledinfo":"点阵屏内容"
            },
    "errorCode": 0,
    "message": "",
    "formError": {}
    }

    """
    e_id = request.POST.get("device_id")
    if not e_id:
        raise PortError("","参数缺失")
    qxz_list = QXZstatus_New.objects.filter(device_id=e_id).first()
    if not qxz_list:
        raise PortError("","未找到此设备")
    data = []
    dat = {"e1":qxz_list.e1,"e2":qxz_list.e2,"e3":qxz_list.e3,"e4":qxz_list.e4,"e5":qxz_list.e5,
            "e6":qxz_list.e6,"e7":qxz_list.e7,"e8":qxz_list.e8,"e9":qxz_list.e9,"e10":qxz_list.e10,
            "e11":qxz_list.e11,"e12":qxz_list.e12,"e13":qxz_list.e13,"e14":qxz_list.e14,
            "e15":qxz_list.e15,"e16":qxz_list.e16,"e17":qxz_list.e17,"e18":qxz_list.e18,
            "e19":qxz_list.e19,"e20":qxz_list.e20,"e21":qxz_list.e21,"e22":qxz_list.e22,
            "e23":qxz_list.e23,"e24":qxz_list.e24,"e25":qxz_list.e25,"e26":qxz_list.e26,
            "e27":qxz_list.e27,"e28":qxz_list.e28,"e29":qxz_list.e29,"e30":qxz_list.e30, "uptime":qxz_list.uptime}
    try:
        x = MongoQXZ_Conf.objects.get(device_id=e_id)
        conf = {"e1":x.e1,"e2":x.e2,"e3":x.e3,"e4":x.e4,"e5":x.e5,
                "e6":x.e6,"e7":x.e7,"e8":x.e8,"e9":x.e9,"e10":x.e10,
                "e11":x.e11,"e12":x.e12,"e13":x.e13,"e14":x.e14,
                "e15":x.e15,"e16":x.e16,"e17":x.e17,"e18":x.e18,
                "e19":x.e19,"e20":x.e20,"e21":x.e21,"e22":x.e22,
                "e23":x.e23,"e24":x.e24,"e25":x.e25,"e26":x.e26,
                "e27":x.e27,"e28":x.e28,"e29":x.e29,"e30":x.e30}
    except:
        conf = {}
    try:
        led = MongoQXZ_Base_Info.objects.get(device_id=e_id).led
    except:
        led = "0"
    try:
        ledinfo = MongoQXZ_Base_Info.objects.get(device_id=e_id).ledinfo
    except:
        ledinfo = ""
    data = {'dat':dat,'conf':conf, "led":led,"ledinfo":ledinfo}
    return data


@kedong_deco(login_required=True)
def qxz_data_chart(request):
    """
    气象折线图接口 ：
    参数：
    device_id               必传(string)

    begin              必传(string 时间戳)             开始时间    (用于时间搜索)     默认近一个月
    end                非必传(string 时间戳)           结束时间    (用于时间搜索)
    返回值：
    {
        "data": {
            "conf": {
            "e1":x.e1,"e2":x.e2,"e3":x.e3,"e4":x.e4,"e5":x.e5,
            "e6":x.e6,"e7":x.e7,"e8":x.e8,"e9":x.e9,"e10":x.e10,
            "e11":x.e11,"e12":x.e12,"e13":x.e13,"e14":x.e14,
            "e15":x.e15,"e16":x.e16,"e17":x.e17,"e18":x.e18,
            "e19":x.e19,"e20":x.e20,"e21":x.e21,"e22":x.e22,
            "e23":x.e23,"e24":x.e24,"e25":x.e25,"e26":x.e26,
            "e27":x.e27,"e28":x.e28,"e29":x.e29,"e30":x.e30
            },
            "nums": 0,
            "data": [
                {
                "e1":qxz_list.e1,"e2":qxz_list.e2,"e3":qxz_list.e3,"e4":qxz_list.e4,"e5":qxz_list.e5,
                "e6":qxz_list.e6,"e7":qxz_list.e7,"e8":qxz_list.e8,"e9":qxz_list.e9,"e10":qxz_list.e10,
                "e11":qxz_list.e11,"e12":qxz_list.e12,"e13":qxz_list.e13,"e14":qxz_list.e14,
                "e15":qxz_list.e15,"e16":qxz_list.e16,"e17":qxz_list.e17,"e18":qxz_list.e18,
                "e19":qxz_list.e19,"e20":qxz_list.e20,"e21":qxz_list.e21,"e22":qxz_list.e22,
                "e23":qxz_list.e23,"e24":qxz_list.e24,"e25":qxz_list.e25,"e26":qxz_list.e26,
                "e27":qxz_list.e27,"e28":qxz_list.e28,"e29":qxz_list.e29,"e30":qxz_list.e30, 
                "upl_time":qxz_list.upl_time.strftime('%Y-%m-%d %H:%M:%S')
                },
                {
                "e1":qxz_list.e1,"e2":qxz_list.e2,"e3":qxz_list.e3,"e4":qxz_list.e4,"e5":qxz_list.e5,
                "e6":qxz_list.e6,"e7":qxz_list.e7,"e8":qxz_list.e8,"e9":qxz_list.e9,"e10":qxz_list.e10,
                "e11":qxz_list.e11,"e12":qxz_list.e12,"e13":qxz_list.e13,"e14":qxz_list.e14,
                "e15":qxz_list.e15,"e16":qxz_list.e16,"e17":qxz_list.e17,"e18":qxz_list.e18,
                "e19":qxz_list.e19,"e20":qxz_list.e20,"e21":qxz_list.e21,"e22":qxz_list.e22,
                "e23":qxz_list.e23,"e24":qxz_list.e24,"e25":qxz_list.e25,"e26":qxz_list.e26,
                "e27":qxz_list.e27,"e28":qxz_list.e28,"e29":qxz_list.e29,"e30":qxz_list.e30, 
                "upl_time":qxz_list.upl_time.strftime('%Y-%m-%d %H:%M:%S')
                },...
            ]
            }
        "params": {},
        "formError": {},
        "errorCode": 0,
        "message": "",
    
    }

    """
    
    device_id = request.POST.get("device_id")
    data = []
    f_tbegin = request.POST.get('begin')
    f_tend = request.POST.get('end')

    try:
        device = MongoDevice.objects.get(device_id=device_id)
        device_expire = device.device_expire
        device_expire_time = device.device_expire_time
    except:
        raise PortError('device_id',"暂无此设备")
    
    qxz_list = QXZdata_New.objects.filter(device_id=device_id)
    
    myuser_type = request.user_type
    if not myuser_type == 1 and not myuser_type == 5:
        if f_tbegin and int(f_tend) > int(device_expire_time):
            f_tend = device_expire_time
    if f_tbegin and f_tend:
        qxz_list =qxz_list.filter(uptime__range=(int(f_tbegin),int(f_tend))).order_by('-id')

    conf = {}
    for i in qxz_list:
        data.append({"dat":{"e1":i.e1,"e2":i.e2,"e3":i.e3,"e4":i.e4,"e5":i.e5,
                "e6":i.e6,"e7":i.e7,"e8":i.e8,"e9":i.e9,"e10":i.e10,
                "e11":i.e11,"e12":i.e12,"e13":i.e13,"e14":i.e14,
                "e15":i.e15,"e16":i.e16,"e17":i.e17,"e18":i.e18,
                "e19":i.e19,"e20":i.e20,"e21":i.e21,"e22":i.e22,
                "e23":i.e23,"e24":i.e24,"e25":i.e25,"e26":i.e26,
                "e27":i.e27,"e28":i.e28,"e29":i.e29,"e30":i.e30},
                "time":i.uptime})

    try:
        x = MongoQXZ_Conf.objects.get(device_id=device_id)
        conf = {"e1":x.e1,"e2":x.e2,"e3":x.e3,"e4":x.e4,"e5":x.e5,
                "e6":x.e6,"e7":x.e7,"e8":x.e8,"e9":x.e9,"e10":x.e10,
                "e11":x.e11,"e12":x.e12,"e13":x.e13,"e14":x.e14,
                "e15":x.e15,"e16":x.e16,"e17":x.e17,"e18":x.e18,
                "e19":x.e19,"e20":x.e20,"e21":x.e21,"e22":x.e22,
                "e23":x.e23,"e24":x.e24,"e25":x.e25,"e26":x.e26,
                "e27":x.e27,"e28":x.e28,"e29":x.e29,"e30":x.e30}
    except:
        conf = {}

    data1 = {"data":data,"conf":conf}
    return data1
