# -*- coding:utf-8 -*-
# @Time    : 2020/5/22 2:22 下午
# @Author  : Creat by Han
import json
import ast
import copy
import datetime
import time
import os
import pymysql
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, MongoCBDData
from smartfarming.models.weather import MongoQXZ_Base_Info, QXZdata_New, MongoQXZ_Conf, QXZstatus_New, MongoQXZ_Alarm
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 = QXZdata_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


@kedong_deco(login_required=True)
def qxz_early_warning(request):
    """
    气象站查看短信预警信息接口\配置预警信息接口
    参数：
    device_id          必传(str)                设备号
    status             必传(str)                当status等于see查看， 当status等于save保存
    alarm              非必传(json)             配置信息，例如：{"dat":{"e1":"1#12","e2":"0#","e3":"0#","e4":"0#","e5":"0#","e6":"0#","e7":"0#","e8":"0#","e9":"0#"},"tel":"18258845915","equip_id":"865553058440811"}
    
    返回值：
    {
        "data" 0  0 保存成功 1失败
    }
    """
    status = request.POST.get("status")
    device_id = request.POST.get("device_id")

    if status == "see":
        try:
            qxz_alarm = MongoQXZ_Alarm.objects.get(device_id=device_id)
            alarm = ast.literal_eval(qxz_alarm.conf)
            phone = qxz_alarm.phone 
        except Exception as e:
            print(e)
            alarm = ""
            phone = ""
        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}
        for k in list(conf.keys()): 
            if not conf[k]:
                del conf[k]
        data = {"conf":conf,"alarm":alarm,"phone":phone}

    elif status == "save":
        alarm = ast.literal_eval(request.POST.get('alarm'))
        conf = alarm["dat"]
        try:
            MongoQXZ_Alarm.objects.update_or_create(
                device_id=device_id,
                defaults={
                    "conf": {"dat": conf},
                    "upl_time": int(time.time())
                }
            )
            return {"code":0}
        except Exception as e:
            raise PortError("","更新失败") 
    else:
        raise PortError("","参数超出范围")
    return data


def qxz_configs(conf,e_data,es):
    """气象站要素配置"""
    e3s = conf.get(es,"")
    code = e_data.split('#')[1]
    if e3s:
        config = e3s.split("#")
        config.insert(0,code)
    else:
        config = qxz_dict_1[e_data.split('#')[1]]
    return config


@kedong_deco(login_required=True)
def qxz_day_data(request):
    """
    气象24H数据接口 :
    参数:
    device_id               必传(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")
    qxz_dict_1 = copy.deepcopy(qxz_dict)    # 如果不拷贝 后面折线图修改字典会导致字典内容变化   从而造成数据错误
    
    times = ""

    try:
        MongoDevice.objects.get(device_id=device_id)
    except:
        raise PortError('device_id',"暂无此设备")

    qxz_list = QXZstatus_New.objects.filter(device_id=device_id).order_by("-uptime").first()
    if qxz_list:
        times = qxz_list.uptime


    # 获取最新一条数据的时间然后进行时间格式转换,再获取前一天时间
    if times:
        otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(times))
        times_type = datetime.datetime.strptime(str(otherStyleTime), "%Y-%m-%d %H:%M:%S")
        now = times_type - datetime.timedelta(days=1)
    else:
        # 获取前一天的时间点从0点到24点时间
        now = datetime.datetime.now()- datetime.timedelta(days=1)

    zero_today = now - datetime.timedelta(hours=now.hour, minutes=now.minute, seconds=now.second,microseconds=now.microsecond)
    last_today = zero_today + datetime.timedelta(hours=23, minutes=59, seconds=59)
 
    start_time = int(time.mktime(time.strptime(str(zero_today), "%Y-%m-%d %H:%M:%S")))
    end_time = int(time.mktime(time.strptime(str(last_today), "%Y-%m-%d %H:%M:%S")))
    
    
    sta1 = QXZdata_New.objects.filter(device_id=device_id).filter(uptime__range=(start_time,end_time)).values()
    data = []
    e1 = []
    e1_time = []
    e2 = []
    e2_time = []
    e3 = []
    e3_time = []
    e4 = []
    e4_time = []
    e5 = []
    e5_time = []
    e6 = []
    e6_time = []
    e7 = []
    e7_time = []
    e8 = []
    e8_time = []
    e9 = []
    e9_time = []
    e10 = []
    e10_time = []
    e11 = []
    e11_time = []
    e12 = []
    e12_time = []
    e13 = []
    e13_time = []
    e14 = []
    e14_time = []
    e15 = []
    e15_time = []
    e16 = []
    e16_time = []
    e17 = []
    e17_time = []
    e18 = []
    e18_time = []
    e19 = []
    e19_time = []
    e20 = []
    e20_time = []
    e21 = []
    e21_time = []
    e22 = []
    e22_time = []
    e23 = []
    e23_time = []
    e24 = []
    e24_time = []
    e25 = []
    e25_time = []
    e26 = []
    e26_time = []
    e27 = []
    e27_time = []
    e28 = []
    e28_time = []
    e29 = []
    e29_time = []
    e30 = []
    e30_time = []
    for i in sta1[:200]:
        if i['e1']:
            e1.append(float(i['e1'].split('#')[0]))
            e1_time.append(i['uptime'])
        if i['e2']:
            e2.append(float(i['e2'].split('#')[0]))
            e2_time.append(i['uptime'])
        if i['e3']:
            e3.append(float(i['e3'].split('#')[0]))
            e3_time.append(i['uptime'])
        if i['e4']:
            e4.append(float(i['e4'].split('#')[0]))
            e4_time.append(i['uptime'])
        if i['e5']:
            e5.append(float(i['e5'].split('#')[0]))
            e5_time.append(i['uptime'])
        if i['e6']:
            e6.append(float(i['e6'].split('#')[0]))
            e6_time.append(i['uptime'])
        if i['e7']:
            e7.append(float(i['e7'].split('#')[0]))
            e7_time.append(i['uptime'])
        if i['e8']:
            e8.append(float(i['e8'].split('#')[0]))
            e8_time.append(i['uptime'])
        if i['e9']:
            e9.append(float(i['e9'].split('#')[0]))
            e9_time.append(i['uptime'])
        if i['e10']:
            e10.append(float(i['e10'].split('#')[0]))
            e10_time.append(i['uptime'])
        if i['e11']:
            e11.append(float(i['e11'].split('#')[0]))
            e11_time.append(i['uptime'])
        if i['e12']:
            e12.append(float(i['e12'].split('#')[0]))
            e12_time.append(i['uptime'])
        if i['e13']:
            e13.append(float(i['e13'].split('#')[0]))
            e13_time.append(i['uptime'])
        if i['e14']:
            e14.append(float(i['e14'].split('#')[0]))
            e14_time.append(i['uptime'])
        if i['e15']:
            e15.append(float(i['e15'].split('#')[0]))
            e15_time.append(i['uptime'])
        if i['e16']:
            e16.append(float(i['e16'].split('#')[0]))
            e16_time.append(i['uptime'])
        if i['e17']:
            e17.append(float(i['e17'].split('#')[0]))
            e17_time.append(i['uptime'])
        if i['e18']:
            e18.append(float(i['e18'].split('#')[0]))
            e18_time.append(i['uptime'])
        if i['e19']:
            e19.append(float(i['e19'].split('#')[0]))
            e19_time.append(i['uptime'])
        if i['e20']:
            e20.append(float(i['e20'].split('#')[0]))
            e20_time.append(i['uptime'])
        if i['e21']:
            e21.append(float(i['e21'].split('#')[0]))
            e21_time.append(i['uptime'])
        if i['e22']:
            e22.append(float(i['e22'].split('#')[0]))
            e22_time.append(i['uptime'])
        if i['e23']:
            e23.append(float(i['e23'].split('#')[0]))
            e23_time.append(i['uptime'])
        if i['e24']:
            e24.append(float(i['e24'].split('#')[0]))
            e24_time.append(i['uptime'])
        if i['e25']:
            e25.append(float(i['e25'].split('#')[0]))
            e25_time.append(i['uptime'])
        if i['e26']:
            e26.append(float(i['e26'].split('#')[0]))
            e26_time.append(i['uptime'])
        if i['e27']:
            e27.append(float(i['e27'].split('#')[0]))
            e27_time.append(i['uptime'])
        if i['e28']:
            e28.append(float(i['e28'].split('#')[0]))
            e28_time.append(i['uptime'])
        if i['e29']:
            e29.append(float(i['e29'].split('#')[0]))
            e29_time.append(i['uptime'])
        if i['e30']:
            e30.append(float(i['e30'].split('#')[0]))
            e30_time.append(i['uptime'])
    
    
    conf = {}
    x = MongoQXZ_Conf.objects.filter(device_id=device_id).first()
    if x:
        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}
    data = []
    try:
        if e1 != []:
            config = qxz_configs(conf,i['e1'],"e1")
            data.append({"max":max(e1),"maxtime":e1_time[e1.index(max(e1))],"min":min(e1),"mintime":e1_time[e1.index(min(e1))],"enum":config,"ekey":i['e1'].split('#')[2]})
        if e2 != []:
            config = qxz_configs(conf,i['e2'],"e2")
            data.append({"max":max(e2),"maxtime":e2_time[e2.index(max(e2))],"min":min(e2),"mintime":e2_time[e2.index(min(e2))],"enum":config,"ekey":i['e2'].split('#')[2]})
        if e3 != []:
            config = qxz_configs(conf,i['e3'],"e3")
            data.append({"max":max(e3),"maxtime":e3_time[e3.index(max(e3))],"min":min(e3),"mintime":e3_time[e3.index(min(e3))],"enum":config,"ekey":i['e3'].split('#')[2]})
        if e4 != []:
            config = qxz_configs(conf,i['e4'],"e4")
            data.append({"max":max(e4),"maxtime":e4_time[e4.index(max(e4))],"min":min(e4),"mintime":e4_time[e4.index(min(e4))],"enum":config,"ekey":i['e4'].split('#')[2]})
        if e5 != []:
            config = qxz_configs(conf,i['e5'],"e5")
            data.append({"max":max(e5),"maxtime":e5_time[e5.index(max(e5))],"min":min(e5),"mintime":e5_time[e5.index(min(e5))],"enum":config,"ekey":i['e5'].split('#')[2]})
        if e6 != []:
            config = qxz_configs(conf,i['e6'],"e6")
            data.append({"max":max(e6),"maxtime":e6_time[e6.index(max(e6))],"min":min(e6),"mintime":e6_time[e6.index(min(e6))],"enum":config,"ekey":i['e6'].split('#')[2]})
        if e7 != []:
            config = qxz_configs(conf,i['e7'],"e7")
            data.append({"max":max(e7),"maxtime":e7_time[e7.index(max(e7))],"min":min(e7),"mintime":e7_time[e7.index(min(e7))],"enum":config,"ekey":i['e7'].split('#')[2]})
        if e8 != []:
            config = qxz_configs(conf,i['e8'],"e8")
            data.append({"max":max(e8),"maxtime":e8_time[e8.index(max(e8))],"min":min(e8),"mintime":e8_time[e8.index(min(e8))],"enum":config,"ekey":i['e8'].split('#')[2]})
        if e9 != []:
            config = qxz_configs(conf,i['e9'],"e9")
            data.append({"max":max(e9),"maxtime":e9_time[e9.index(max(e9))],"min":min(e9),"mintime":e9_time[e9.index(min(e9))],"enum":config,"ekey":i['e9'].split('#')[2]})
        if e10 != []:
            config = qxz_configs(conf,i['e10'],"e10")
            data.append({"max":max(e10),"maxtime":e10_time[e10.index(max(e10))],"min":min(e10),"mintime":e10_time[e10.index(min(e10))],"enum":config,"ekey":i['e10'].split('#')[2]})
        if e11 != []:
            config = qxz_configs(conf,i['e11'],"e11")
            data.append({"max":max(e11),"maxtime":e11_time[e11.index(max(e11))],"min":min(e11),"mintime":e11_time[e11.index(min(e11))],"enum":config,"ekey":i['e11'].split('#')[2]})
        if e12 != []:
            config = qxz_configs(conf,i['e12'],"e12")
            data.append({"max":max(e12),"maxtime":e12_time[e12.index(max(e12))],"min":min(e12),"mintime":e12_time[e12.index(min(e12))],"enum":config,"ekey":i['e12'].split('#')[2]})
        if e13 != []:
            config = qxz_configs(conf,i['e13'],"e13")
            data.append({"max":max(e13),"maxtime":e13_time[e13.index(max(e13))],"min":min(e13),"mintime":e13_time[e13.index(min(e13))],"enum":config,"ekey":i['e13'].split('#')[2]})
        if e14 != []:
            config = qxz_configs(conf,i['e14'],"e14")
            data.append({"max":max(e14),"maxtime":e14_time[e14.index(max(e14))],"min":min(e14),"mintime":e14_time[e14.index(min(e14))],"enum":config,"ekey":i['e14'].split('#')[2]})
        if e15 != []:
            config = qxz_configs(conf,i['e15'],"e15")
            data.append({"max":max(e15),"maxtime":e15_time[e15.index(max(e15))],"min":min(e15),"mintime":e15_time[e15.index(min(e15))],"enum":config,"ekey":i['e15'].split('#')[2]})
        if e16 != []:
            config = qxz_configs(conf,i['e16'],"e16")
            data.append({"max":max(e16),"maxtime":e16_time[e16.index(max(e16))],"min":min(e16),"mintime":e16_time[e16.index(min(e16))],"enum":config,"ekey":i['e16'].split('#')[2]})
        if e17 != []:
            config = qxz_configs(conf,i['e17'],"e17")
            data.append({"max":max(e17),"maxtime":e17_time[e17.index(max(e17))],"min":min(e17),"mintime":e17_time[e17.index(min(e17))],"enum":config,"ekey":i['e17'].split('#')[2]})
        if e18 != []:
            config = qxz_configs(conf,i['e18'],"e18")
            data.append({"max":max(e18),"maxtime":e18_time[e18.index(max(e18))],"min":min(e18),"mintime":e18_time[e18.index(min(e18))],"enum":config,"ekey":i['e18'].split('#')[2]})
        if e19 != []:
            config = qxz_configs(conf,i['e19'],"e19")
            data.append({"max":max(e19),"maxtime":e19_time[e19.index(max(e19))],"min":min(e19),"mintime":e19_time[e19.index(min(e19))],"enum":config,"ekey":i['e19'].split('#')[2]})
        if e20 != []:
            config = qxz_configs(conf,i['e20'],"e20")
            data.append({"max":max(e20),"maxtime":e20_time[e20.index(max(e20))],"min":min(e20),"mintime":e20_time[e20.index(min(e20))],"enum":config,"ekey":i['e20'].split('#')[2]})
        if e21 != []:
            config = qxz_configs(conf,i['e21'],"e21")
            data.append({"max":max(e21),"maxtime":e21_time[e21.index(max(e21))],"min":min(e21),"mintime":e21_time[e21.index(min(e21))],"enum":config,"ekey":i['e21'].split('#')[2]})
        if e22 != []:
            config = qxz_configs(conf,i['e22'],"e22")
            data.append({"max":max(e22),"maxtime":e22_time[e22.index(max(e22))],"min":min(e22),"mintime":e22_time[e22.index(min(e22))],"enum":config,"ekey":i['e22'].split('#')[2]})
        if e23 != []:
            config = qxz_configs(conf,i['e23'],"e23")
            data.append({"max":max(e23),"maxtime":e23_time[e23.index(max(e23))],"min":min(e23),"mintime":e23_time[e23.index(min(e23))],"enum":config,"ekey":i['e23'].split('#')[2]})
        if e24 != []:
            config = qxz_configs(conf,i['e24'],"e24")
            data.append({"max":max(e24),"maxtime":e24_time[e24.index(max(e24))],"min":min(e24),"mintime":e24_time[e24.index(min(e24))],"enum":config,"ekey":i['e24'].split('#')[2]})
        if e25 != []:
            config = qxz_configs(conf,i['e25'],"e25")
            data.append({"max":max(e25),"maxtime":e25_time[e25.index(max(e25))],"min":min(e25),"mintime":e25_time[e25.index(min(e25))],"enum":config,"ekey":i['e25'].split('#')[2]})
        if e26 != []:
            config = qxz_configs(conf,i['e26'],"e26")
            data.append({"max":max(e26),"maxtime":e26_time[e26.index(max(e26))],"min":min(e26),"mintime":e26_time[e26.index(min(e26))],"enum":config,"ekey":i['e26'].split('#')[2]})
        if e27 != []:
            config = qxz_configs(conf,i['e27'],"e27")
            data.append({"max":max(e27),"maxtime":e27_time[e27.index(max(e27))],"min":min(e27),"mintime":e27_time[e27.index(min(e27))],"enum":config,"ekey":i['e27'].split('#')[2]})
        if e28 != []:
            config = qxz_configs(conf,i['e28'],"e28")
            data.append({"max":max(e28),"maxtime":e28_time[e28.index(max(e28))],"min":min(e28),"mintime":e28_time[e28.index(min(e28))],"enum":config,"ekey":i['e28'].split('#')[2]})
        if e29 != []:
            config = qxz_configs(conf,i['e29'],"e29")
            data.append({"max":max(e29),"maxtime":e29_time[e29.index(max(e29))],"min":min(e29),"mintime":e29_time[e29.index(min(e29))],"enum":config,"ekey":i['e29'].split('#')[2]})
        if e30 != []:
            config = qxz_configs(conf,i['e30'],"e30")
            data.append({"max":max(e30),"maxtime":e30_time[e30.index(max(e30))],"min":min(e30),"mintime":e30_time[e30.index(min(e30))],"enum":config,"ekey":i['e30'].split('#')[2]})
    except Exception as e:

        raise PortError(" ", "计算数据失败,稍后重试")
    dat = {"data":data,"conf":conf}
    return dat


@kedong_deco(login_required=False)
def device_status_data(request):
    """
    虫情测报灯/数据详情
    设备实时状态接口
        参数:
        device_id               必传                            设备id
        返回值:
        "data": {
        "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               加热仓实时温度
        "device_name":"这里是设备名称",
        "address": "这里是设备位置",
        "iccid": 1234444  SIM卡号
    }
    """
    post_info = request.POST
    _device_id = post_info.get("device_id")
    if not _device_id:
        raise PortError('device_id', "该设备不存在")
    try:
        device = MongoDevice.objects.get(device_id=_device_id)
    except:
        raise PortError('device_id','暂无此设备')
    d_id = device.id
    device_name = device.device_name
    province = device.province
    city = device.city
    district = device.district
    device_status = device.device_status  # 在线状态
    myuser_type = request.user_type
    device_datas = MongoCBDData.objects.filter(device_id=d_id).order_by('-id')
    try:
        device_data = json.loads(device_datas[0].device_data)
    except json.JSONDecodeError as e:
        device_data = eval(device_datas[0].device_data)
    except:
        raise PortError("device_id","暂无数据")
    
    ds = device_data.get("ds",1 )
    ts = device_data.get("ts",1)
    up_st = {
        "is_online": device_status,
        "ts":ts,
        "hs":device_data["hs"],
        "upds":device_data["upds"],
        "dnds":device_data["dnds"],
        "csq":device_data["csq"],
        "dver":device_data["dver"],
        "tph":device_data["tph"],
        "tpl":device_data["tpl"],
        "tps":device_data["tps"],
        "lps":device_data["lps"],
        "hrt":device_data["hrt"],
        "iccid":device_data["iccid"],
        "rps":device_data["rps"],
        "ah":device_data["ah"],
        "at":device_data["at"],
        "ds":ds,
        "device_name":device_name,
        "address": province + city + district,
    }
    return up_st

# config = {
#         'host': config_dict['bigdata']['django_mysql_host'],
#         'port': int(config_dict['bigdata']['django_mysql_port']),
#         'user': config_dict['bigdata']['django_mysql_user'],
#         'password': config_dict['bigdata']['django_mysql_password'],
#         'db': config_dict['bigdata']['django_mysql_db'],
#         'charset': 'utf8mb4',
#         'cursorclass': pymysql.cursors.DictCursor,
#     }