import datetime
import time
from smartfarming.models.device import MongoDevice, MongoSCDData, MongoDeviceType, MongoXYCBData
from kedong.decoration import kedong_deco, PortError
from smartfarming.utils import get_address_by_lntlat, get_weather_info
from smartfarming.models.user import MongoOperateLogs


def operation_log(uid,content,target_id,operation_type,ip):
    """
    uid                     必传              操作者id
    content                 必传              操作内容
    target_id               必传              被操作者id
    operation_type          必传              对设备操作0 对用户操作传1

    """
    if not (uid or content or target_id or operation_type or ip):
        raise PortError('log',"日志记录参数缺失")
    try:
        MongoOperateLogs(addtime=int(time.time()), uid=uid, content=content, target_id=target_id,operation_type=operation_type,ip=ip).save()
    except Exception as e:
        print("操作日志存储失败", e)


@kedong_deco(login_required=False)
def weathers(request):
    """
    天气接口
    参数
    lat             必传(str)               纬度
    lng             必传(str)               经度

    返回值：
     "data": [
        {
        "id": 1201,
        "province": "新疆维吾尔自治区",             省
        "city": "克孜勒苏柯尔克孜自治州",           市
        "district": "阿克陶县",                     县
        "lng": "75.945159",                         经度
        "lat": "39.147079",                         纬度
        "at": "31",                                 温度
        "ah": "14",                                 湿度
        "upl_time": "2021-10-25 14:39:48",          时间
        "win": "东风",                              风向
        "win_speed": "1级",                         风速
        "win_meter": "5km/h",                       风力
        "wea": "多云",                              天气
        "visibility": "30km",                       能见度
        "pressure": "863",                          压力
        "air": "40",                                空气
        "air_pm25": "19",                           空气PM2.5
        "air_level": "优",                          空气等级
        "air_tips": "空气很好,可以外出活动,呼吸新鲜空气,拥抱大自然！"   空气说明
        }
    ],
    "params": {
    "lat": "039.1850853",
    "lng": "075.8749465"
    }
    }


    """

    lat = request.POST.get('lat', '')
    lng = request.POST.get('lng', '')
    device_id = request.POST.get('device_id')

    if not lat and not lng:
        raise PortError('', '未传经纬度')

    province, city, district = "", "", ""
    if device_id:
        try:
            instance = MongoDevice.objects.get(device_id=device_id)
            province, city, district = instance.province, instance.city, instance.district
            if (not city) and district:
                city = district
        except Exception as e:
            pass

    if not (province and city):
        province, city, district = get_address_by_lntlat(lng, lat)

    result = []
    weather_info = get_weather_info(lng, lat)
    try:
        upl_time = weather_info.get('upl_time')
        upl_time = datetime.datetime.fromtimestamp(int(upl_time)).strftime("%Y-%m-%d %H:%M:%S")
    except Exception as e:
        upl_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    result.append({
        "province": province,
        "city": city,
        "district": district,
        "lng": lng,
        "lat": lat,
        "at": weather_info.get('tem', ''),
        "ah": weather_info.get('humidity', '%'),
        "upl_time": upl_time,
        "win": weather_info.get('win', ''),
        "win_speed": weather_info.get('win_speed', ''),
        "win_meter": weather_info.get('win_meter', ''),
        "wea": weather_info.get('wea', ''),
        "visibility": weather_info.get('visibility', ''),
        "pressure": weather_info.get('pressure', ''),
        "air": weather_info.get('air', ''),
        "air_pm25": weather_info.get('air_pm25', ''),
        "air_level": weather_info.get('air_level', ''),
        "air_tips": weather_info.get('air_tips', ''),
    })
    return result


@kedong_deco(login_required=True)
def scd_gis_info(request):
    """
        杀虫灯GIS展示信息
        参数
        device_id             必传(str)               设备ID

        返回值：
         "data": {
            "address": "河南省新乡市原阳县",         设备地址
            "uptime": "2022-01-02 12:12:12",      最新上传时间
            "device_name": "xxxxxx",              设备名称
            "device_id":"xxxxxxxxxxx",             设备ID
            'device_status': "在线",                设备状态
            "at": "30",                             温度
            "ah": "50",                             湿度
            "ws_status": "待机",                   工作状态
            "rps_status": "正常",                  雨控状态
            "tt": "4",                              定时时长
            "ct": "0",                              电击次数
            "csq": "0"                              信号强度
            }

        """
    device_id = request.POST.get('device_id')
    try:
        device_info = MongoDevice.objects.get(device_id=device_id)
    except Exception as e:
        raise PortError("device_id", "设备id参数异常")

    device_name = device_info.device_name
    if not device_name:
        device_name = MongoDeviceType.objects.get(id=4).type_name

    up_date = datetime.datetime.utcfromtimestamp(device_info.uptime)

    try:
        queryset = MongoSCDData.objects.filter(device_id=device_info.id).order_by('-id')[0]
        data_info = eval(queryset.device_data)
    except Exception as e:
        data_info = {}

    ws = data_info.get('ws', '0')
    ws_status = "待机"
    if ws == "1":
        ws_status = "工作"
    elif ws == "2":
        ws_status = "充电"

    tt = data_info.get('tt', '0')
    if tt == '0':
        tt = '常亮'

    rps_status = "正常" if data_info.get("rps", "0") == "0" else "保护"

    data = {
        "address": f"{device_info.province}{device_info.city}{device_info.district}",
        "uptime": up_date.strftime("%Y-%m-%d %H:%M:%S"),
        "device_name": device_name,
        "device_id": device_info.device_id,
        'device_status': "在线" if device_info.device_status == 1 else "离线",
        "ws_status": ws_status,
        "rps_status": rps_status,
        "tt": tt,
        "at": data_info.get('at', ''),
        "ah": data_info.get('ah', ''),
        "ct": data_info.get('ct', '0'),
        "csq": data_info.get('csq', '0')
    }
    return data



@kedong_deco(login_required=True)
def xycb_gis_info(request):
    """
        性诱测报GIS展示信息
        参数
        device_id             必传(str)               设备ID

        返回值：
         "data": {
            "address": "河南省新乡市原阳县",         设备地址
            "uptime": "2022-01-02 12:12:12",      最新上传时间
            "device_name": "xxxxxx",              设备名称
            "device_id":"xxxxxxxxxxx",             设备ID
            'device_status': "在线",                设备状态
            "at": "30",                             温度
            "ah": "50",                             湿度
            "ws_status": "待机",                   工作状态
            "cs_status": "非充电",                        充电状态
            "bs_status": "正常",                    电池状态
            "infr_ct": "0",                         击虫次数
            "csq": "0"                              信号强度
            }

        """
    device_id = request.POST.get('device_id')
    try:
        device_info = MongoDevice.objects.get(device_id=device_id)
    except Exception as e:
        raise PortError("device_id", "设备id参数异常")

    device_name = device_info.device_name
    if not device_name:
        device_name = MongoDeviceType.objects.get(id=4).type_name

    up_date = datetime.datetime.utcfromtimestamp(device_info.uptime)

    try:
        queryset = MongoXYCBData.objects.filter(device_id=device_info.id).order_by('-id')[0]
        data_info = eval(queryset.device_data)
    except Exception as e:
        data_info = {}

    ws = data_info.get('ws', '0')
    ws_status = "待机"
    if ws == "1":
        ws_status = "工作"
    elif ws == "2":
        ws_status = "充电"

    bs = data_info.get('bs', '0')
    bs_status = '正常'
    if bs == '1':
        bs_status = '欠压'
    elif bs == '2':
        bs_status = '过压'

    cs_status = '非充电' if data_info.get('cs', '0') == '0' else '充电'

    data = {
        "address": f"{device_info.province}{device_info.city}{device_info.district}",
        "uptime": up_date.strftime("%Y-%m-%d %H:%M:%S"),
        "device_name": device_name,
        "device_id": device_info.device_id,
        'device_status': "在线" if device_info.device_status == 1 else "离线",
        "at": data_info.get('at', ''),
        "ah": data_info.get('ah', ''),
        "ws_status": ws_status,
        "cs_status": cs_status,
        "bs_status": bs_status,
        "infr_ct": data_info.get('infr_ct', '0'),
        "csq": data_info.get('csq')
    }
    return data


@kedong_deco(login_required=True)
def get_spore_time(request):
    """
    获取孢子仪载玻片/培养夜时间
    获取性诱设备优芯
    参数：
    device_type_id                  必传                         设备类型  7孢子仪 4性诱设备
    d_id                            必传                         设备自增id

    返回：
    glass_slide_time 载玻片更换时间
    cultivate_time 培养液更换时间
    """
    post_info = request.POST
    device_type_id = post_info.get("device_type_id", '')
    d_id = post_info.get("d_id", '')
    if not d_id:
        raise PortError('d_id', "参数缺失")
    if not device_type_id:
        raise PortError('device_type_id',"参数缺失")
    devices = MongoDevice.objects.get(id=d_id, device_type_id=device_type_id)
    if int(device_type_id) == 7:
        glass_slide_time = devices.glass_slide_time
        cultivate_time = devices.cultivate_time
        if glass_slide_time == 0 or cultivate_time == 0:
            glass_slide_time = ""
            cultivate_time = ""
        return {
            "glass_slide_time":glass_slide_time,
            "cultivate_time":cultivate_time,
                }
    elif int(device_type_id) == 4:
        decoy = devices.decoy
        return {
            "decoy":decoy
        }
    


@kedong_deco(login_required=True)
def updata_spore_time(request):
    """
    更新孢子仪载玻片/培养夜时间
    更新性诱设备诱芯
    参数：
    device_type_id                              必传                         设备类型  7孢子仪  4性诱设备
    d_id                                        必传                         设备自增id
    glass_slide_time                            必传                         载玻片更换时间
    cultivate_time                              必传                         培养液更换时间
    decoy                                       必传                         性诱设备诱芯

    """
    myuid = request.myuser.uid
    user_type = request.user_type
    post_info = request.POST
    device_type_id = post_info.get("device_type_id", '')
    d_id = post_info.get("d_id", '')
    glass_slide_time = post_info.get("glass_slide_time", '')
    cultivate_time = post_info.get("cultivate_time", '')
    decoy = post_info.get("decoy", '')
    if not d_id:
        raise PortError('d_id', "参数缺失")
    if not device_type_id:
        raise PortError('device_type_id',"参数缺失")
    try:
        devices = MongoDevice.objects.get(id=d_id)
    except:
        raise PortError('',"未找到此设备")
    if int(device_type_id) == 7:
        devices.glass_slide_time = glass_slide_time
        devices.cultivate_time = cultivate_time
        devices.save()
        content = "更新孢子仪,载玻片时间：%s，培养夜时间：%s"
        operation_log(myuid, content % (glass_slide_time, cultivate_time), devices.device_id, 0, request.ip)
    elif int(device_type_id) == 4:
        if not decoy:
            raise PortError('decoy',"参数缺失")
        devices.decoy = decoy
        devices.save()
        content = "更新性诱设备诱芯：%s"
        operation_log(myuid, content % decoy, devices.device_id, 0, request.ip)
    return True