from pickle import decode_long
import requests
import json
import logging
from requests.auth import HTTPBasicAuth
from django.conf import settings
from smartfarming.api.views.forecast.all_dict import insect_dict,get_siminfo,get_simsinfo
from kedong.decoration import kedong_deco, PortError
from smartfarming.models.device import MongoDeviceConfig, MongoDevice
from smartfarming.models.weather import MongoQXZ_Base_Info

logger = logging.getLogger("control")
config_dict = settings.CONFIG


@kedong_deco(login_required=True)
def device_control_info(request):
    # 设备控制信息/ 设备操作当前状态
    post_info = request.POST
    d_id = post_info.get("d_id", '')
    cmd = post_info.get("cmd", '')
    if not cmd:
        raise PortError('cmd',"参数缺失")
    if not d_id:
        raise PortError('d_id', "参数缺失")
    device_config = MongoDeviceConfig.objects.filter(d_id=d_id,cmd=cmd)
    if device_config.exists():
        d_config = device_config.first()
        try:
            config = json.loads(d_config.device_config)
        except:
            config = eval(d_config.device_config)
        if "ext" in config:
            d_config = config["ext"]
        else:
            d_config = config
        return d_config
    else:
        device = MongoDevice.objects.filter(id=d_id, device_type_id__in = [5, 8])
        if device:
            device = device.first()
        raise PortError(d_id, "配置未上传")
    

@kedong_deco(login_required=True)
def device_control(request):
    # 设备下发控制
    #测报灯  下发主题  /yfkj/cbd/sub/+imei
    #杀虫灯  下发主题  /yfkj/scd/sub/+imei
    #性诱设备  下发主题 yfkj/xycb/s2c/+imei
    #孢子仪  下发主题 /yfkj/bzy/s2c/+imei
    post_info = request.POST
    device_type_id = post_info.get("device_type_id", '')
    d_id = post_info.get("d_id", '')
    req = post_info.get("req","")
    work_type = post_info.get("work_type", '')
    device_name = post_info.get("device_name", '')
    if not d_id:
        raise PortError('d_id',"参数缺失")
    devices = MongoDevice.objects.all()
    try:
        device = devices.get(id=int(d_id))
    except:
        raise PortError("d_id","没有此设备")
    if device.device_expire == "1":
        raise PortError("d_id","设备已过期")
    if device_name:
        device.device_name = device_name
        device.save()
    config = post_info.get("config", '')
    cmd = post_info.get("cmd", '')
    payload = {}
    if work_type == "0":
        payload = {"cmd": "workmode", "ext": {"asleep": "1", "common": "0", "power": "0"}}
    elif work_type == "1":
        payload = {"cmd": "workmode", "ext": {"asleep": "0", "common": "1", "power": "0"}}
    elif work_type == "2":
        payload = {"cmd": "workmode", "ext": {"asleep": "0", "common": "0", "power": "1"}}
    if config:
        try:
            config = json.loads(config)
        except:
            raise PortError('',"参数类型错误")
    if not work_type:
        if not config:
            raise PortError('config', "参数缺失")
        payload["cmd"] = "paramconf"
        payload["ext"] = config
    if req == "ctr_clear":
        payload = {"cmd": "ctr_clear"}
    topic = ""
    if not device_type_id:
        raise PortError('device_type_id',"参数缺失")
    if int(device_type_id) == 3:
        topic = "/yfkj/cbd/sub/%s"%device.device_id
    elif int(device_type_id) == 2:
        topic = "/yfkj/scd/sub/%s"%device.device_id
    elif int(device_type_id) == 4:
        topic = "/yfkj/xycb/s2c/%s"%device.device_id
    elif int(device_type_id) in [5, 8]:
        topic = "/yfkj/qxz/sub/%s"%device.device_id
        timeout = config.get("timeout","")
        content = config.get("content","")
        interval = config.get("interval","")
        if content:
            payload["cmd"] = "dotled"
            payload["ext"] = {
                "content":content,
                "timeout":timeout,
            }
            cmds = {"topic": topic, "payload": payload, "qos": 1}
            content = "气象站：%s,下发：%s"
        if interval:
            payload["cmd"] = "config"
            payload["ext"] = {"interval":interval}
            cmds = {"topic": topic, "payload": payload, "qos": 1}
            logger.warning(f"设备下发的指令：{cmds}")
            response = requests.post(
                "%s" % config_dict['mqtt_config']["http"], 
                json=cmds,timeout=(3),
                auth=HTTPBasicAuth(config_dict['mqtt_config']["user"], 
                config_dict['mqtt_config']["secret_key"])
            )
            logger.warning(f"设备的返回值：{response}")
            # response_code = 200
            response_code = response.status_code
            if response_code == 200:
                device_config = MongoDeviceConfig.objects.get(d_id=d_id)
                device_config.device_config = str(payload)
                device_config.save()
                logger.warning(f"修改设备控制文件{d_id} 成功: {str(payload)}")
                return True
            else:
                return False
    elif int(device_type_id) == 7:
        topic = "/yfkj/bzy/s2c/%s"%device.device_id
    
    elif int(device_type_id) == 14:
        payload = config
        topic = "yfkj/color/s2c/%s"%device.device_id
    elif int(device_type_id) == 12:
        topic = "/yfkj/cbd/sub/%s"%device.device_id
    if cmd == "setnet":
        ftp = config["ftp"]
        mqtt = config["mqtt"]
        mqtt["qos"] = 0
        payload = {
            "cmd":cmd,
            "ftp": ftp,
            "mqtt": mqtt,
        }
    payload = json.dumps(payload)
    cmds = {"topic":topic,"payload":payload,"qos":1}
    content = "设备类型：%s,下发：%s"
    # mqtt 协议
    logger.warning(f"设备下发的指令：{cmds}")
    response = requests.post(
        "%s" % config_dict['mqtt_config']["http"], 
        json=cmds,timeout=(3),
        auth=HTTPBasicAuth(config_dict['mqtt_config']["user"], 
        config_dict['mqtt_config']["secret_key"])
    )
    logger.warning(f"设备的返回值：{response}")
    response_code = response.status_code
    logger.warning(f"控制响应码：{response_code}")
    if response_code == 200:
        payload = json.loads(payload)
        ext = payload.get("ext", {})
        if ext:
            dattim = ext.get("dattim", "")
            clt = ext.get("clt", "")
        if int(device_type_id) == 2:
            ext = payload.get("ext")
            if dattim:
                ext.pop("dattim")
                ext["dat_f"] = dattim
            if clt:
                ext.pop("clt")
                ext["clt_t"] = clt 
            payload["ext"] = ext
        device_config = MongoDeviceConfig.objects.get(d_id=d_id)
        device_config.device_config = str(json.dumps(payload))
        device_config.save()
        logger.warning(f"修改设备{d_id} 成功: {str(payload)}")
        return True
    else:
        return False


@kedong_deco(login_required=True)
def clear_insects_permission(request):
    """
    杀虫灯账户是否具有清虫权限
    """
    uid = request.myuser.uid
    data = [0, 0]
    return data


@kedong_deco(login_required=True)
def get_device_config(request):
    """
    查询设备配置信息/设备监测最新数据  刷新按钮
    参数：
    device_type_id                  必传                         设备类型  2杀虫灯,3测报灯,4智能性诱,5气象站,6监控设备,7孢子仪  14色诱测报  12吸虫塔
    d_id                            必传                         设备自增id
    control_type                    必传                         操作类型  data 读取设备数据信息/serverconf 读取服务器配置信息
    """
    #测报灯  下发主题  /yfkj/cbd/sub/+imei
    #杀虫灯  下发主题  /yfkj/scd/sub/+imei
    #性诱设备  下发主题 yfkj/xycb/s2c/+imei
    #孢子仪  下发主题 /yfkj/bzy/s2c/+imei
    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', "参数缺失")
    devices = MongoDevice.objects.all()
    device = devices.get(id=int(d_id))
    myuser_type = request.user_type
    if not myuser_type == 1 and device.device_expire == "1":
        raise PortError('', "该设备已到期")
    control_type = post_info.get("control_type", '')
    if not control_type:
        raise PortError('control_type',"参数缺失")
    payload = {
        "cmd": "read",
        "ext":control_type
    }
    topic = ""
    if not device_type_id:
        raise PortError('device_type_id', "参数缺失")
    if int(device_type_id) == 3 or int(device_type_id) == 12:
        topic = "/yfkj/cbd/sub/%s" % device.device_id
    elif int(device_type_id) == 2:
        topic = "/yfkj/scd/sub/%s" % device.device_id
    elif int(device_type_id) == 4:
        topic = "/yfkj/xycb/s2c/%s" % device.device_id
    elif int(device_type_id) == 5:
        topic = "/yfkj/qxz/sub/%s" % device.device_id
        payload = {
        "cmd": "read",
        "ext": {"type": control_type}
    }
    elif int(device_type_id) == 7:
        topic = "/yfkj/bzy/s2c/%s" % device.device_id
    elif int(device_type_id) == 9:
        topic = "/yfkj/tccbd/sub/%s" % device.device_id
    elif int(device_type_id) == 14:
        topic = "yfkj/color/s2c/%s" % device.device_id
        payload = {"cmd":"read","ext":"data"}
    elif int(device_type_id) == 8:
        topic = "/yfkj/xyv3/s2c/%s" % device.device_id
    
    cmd = {
        "topic": topic, 
        "payload": json.dumps(payload), 
        "qos": 1
    }   
    # mqtt 协议 
    logger.warning(f"设备下发的指令：{cmd}")
    response = requests.post(
        "%s"%config_dict['mqtt_config']["http"], 
        json=cmd,
        auth=HTTPBasicAuth(
            config_dict['mqtt_config']["user"], 
            config_dict['mqtt_config']["secret_key"]
            )
    )
    logger.warning(f"设备的返回值：{response}")
    response_code = response.status_code
    if response_code == 200:
        return True
    else:
        return False


@kedong_deco(login_required=True)
def admin_device_control(request):
    """
    单个按钮管理员操作  设备控制
    """
    #测报灯  下发主题  /yfkj/cbd/sub/+imei
    #杀虫灯  下发主题  /yfkj/scd/sub/+imei
    #性诱设备  下发主题 yfkj/xycb/s2c/+imei
    #孢子仪  下发主题 /yfkj/bzy/s2c/+imei
    #气象站  下发主题 /yfkj/qxz/sub/+imei
    #性诱测报  下发主题 yfkj/color/s2c
    post_info = request.POST
    cmd = post_info.get("cmd", '')
    if not cmd:
        raise PortError('cmd', "参数缺失")
    device_type_id = post_info.get("device_type_id", '')
    parm = post_info.get('parm', "")
    d_id = post_info.get("d_id", '')
    if not d_id:
        raise PortError('d_id',"参数缺失")
    devices = MongoDevice.objects.all()
    device_id = devices.get(id=int(d_id)).device_id
    payload = ""
    topic = ""
    if not device_type_id:
        raise PortError('device_type_id',"参数缺失")
    if int(device_type_id) == 3 or int(device_type_id) == 12:
        topic = "/yfkj/cbd/sub/%s"%device_id
        payload = {"cmd": cmd}
        if cmd == "boot1":
            payload = {"cmd":"switch","ext":{"boot":1}}
        elif cmd == "boot0":
            payload = {"cmd":"switch","ext":{"boot":0}}
        elif cmd == "close_shake":
            payload = {"cmd": "shake", "ext":{"ws":0}}   
        elif cmd == "open_shake":
            payload = {"cmd": "shake", "ext":{"ws":1}}
        elif cmd == "yfwlw":
            payload ={"cmd": "platform", "ext": {"type": "120.27.222.26"}}
        elif cmd =="imei":
            # 修改imei
            imei = post_info.get("imei", '')
            payload = {"cmd":"setimei","ext":{"imei":imei}}
    elif int(device_type_id) == 2:
        topic = "/yfkj/scd/sub/%s" % device_id
        if cmd == "clear":
            if not parm:
                raise PortError('parm',"参数缺失")
            payload = {"cmd":"clear","ext":{ "clt":int(parm)}}
        elif cmd == "test":
            payload = {"cmd":"test"}
        elif cmd == "yfwlw": # 平台切换
            payload ={"cmd":"paramconf","ext":{"type": "120.27.222.26"}}
        elif cmd == "paramconf1": # 标配物联网
            payload = {"cmd":"paramconf","ext":{"vt": "uart"}}
        elif cmd == "paramconf2": # 物联网自清虫
            payload = {"cmd":"paramconf","ext":{"vt": "uart-ZQC"}}
        elif cmd == "paramconf3":   # 物联网光控
            payload = {"cmd":"paramconf","ext":{"vt": "uart-light"}}
        elif cmd == "paramconf4":   # 物联网光控自清虫
            payload = {"cmd":"paramconf","ext":{"vt": "uart-light-ZQC"}}
        else:
            payload = {"cmd": cmd}
    elif int(device_type_id) == 4:
        topic = "/yfkj/xycb/s2c/%s" % device_id
        payload = {"cmd": cmd}
        if cmd == "turnset":
            if not parm:
                raise PortError('parm',"参数缺失")
            payload = {"cmd": "set", "ext": {"type": "turn", "turn_t": parm}}
        elif cmd == "turn":
            payload = {"cmd": "ctrl", "ext": {"turn": "1"}}
        elif cmd == "photoset":
            if not parm:
                raise PortError('parm', "参数缺失")
            pic_t,pic_f = str(parm).split('|')  #  pic_t定时拍照时刻   "pic_f"定时拍照时间间隔
            payload = {"cmd": "set", "ext": {"type": "photo", "pic_t": pic_t, "pic_f": pic_f}}
        elif cmd == "repower":
            payload = {"cmd": "repower","ext":""}
        elif cmd == "yfwlw":
            payload ={"cmd": "platform", "ext": {"type": "120.27.222.26"}}
 
    elif int(device_type_id) == 8:
        topic = "/yfkj/xyv3/s2c/%s" % device_id
        payload = {"cmd": cmd}

        if cmd == "turnset":
            if not parm:
                raise PortError('parm',"参数缺失")
            payload = {"cmd": "set", "ext": {"type": "turn", "turn_t": parm}}
        elif cmd == "turn":
            payload = {"cmd": "ctrl", "ext": {"turn": "1"}}
        elif cmd == "photoset":
            if not parm:
                raise PortError('parm', "参数缺失")
            pic_t,pic_f = str(parm).split('|')  #  pic_t定时拍照时刻   "pic_f"定时拍照时间间隔
            payload = {"cmd": "set", "ext": {"type": "photo", "pic_t": pic_t, "pic_f": pic_f}}
        elif cmd == "repower":
            payload = {"cmd": "repower","ext":""}
       
    elif int(device_type_id) == 5:
        topic = "/yfkj/qxz/sub/%s" % device_id
        payload = {
            "cmd": cmd
        }
    elif int(device_type_id) == 7:
        lists = ["update","reboot","poweroff","poweron","coldoff","coldon","dtu_update","dtu_reboot"]
        payload = {"cmd": cmd}
        if cmd == "takephoto":
            payload = {"cmd": "ctrl", "ext": {"type": "takephoto"}}
        elif cmd in lists:
            payload = {"cmd":cmd}
        elif cmd == "autotakephoto":
            payload = {"ext":{"type":"auto_takephoto"},"cmd":"ctrl"}
        elif cmd == "turn":
            payload = {"ext":{"type":"turn"},"cmd":"ctrl"}
        elif cmd == "big_data":
            # 大数据平台：
            payload ={"cmd": "platform", "ext": {"type": "8.136.98.49"}}
        elif cmd == "yfwlw":
            payload ={"cmd": "platform", "ext": {"type": "120.27.222.26"}}

        elif cmd == "location":
            #设置手动定位
            lat = post_info.get("lat", '')
            lng = post_info.get("lng", '')
            payload ={"cmd":"location", "ext":{"lat":lat,"lng":lng,"type":0}}
        elif cmd == "imei":
            # 修改设备ID:
            imei = post_info.get("imei", '')
            payload = {"cmd":"setimei","ext":{"imei":imei}}
        elif cmd == "photo_num":
            num = int(post_info.get("num", ''))
            payload = {"cmd":"warn","ext":{"status":num,"type":"get_photo_step"}}
        topic = "/yfkj/bzy/s2c/%s" % device_id
    elif int(device_type_id) == 9:
        topic = "/yfkj/tccbd/sub/%s" % device_id
        if cmd == "takephoto":
            payload = {"ext": {"type": "takephoto"}, "cmd": "ctrl"}
        elif cmd == "reboot":
            payload = {"cmd":"reboot","ext":""}
        elif cmd == "update":
            payload = {"cmd":"update","ext":""}
        elif cmd == "status":
           payload = {"cmd": "read", "ext": {"type": "status"}}
        elif cmd == "paramconf":
            payload = {"cmd": "read", "ext": {"type": "paramconf"}}
        elif cmd == "boot1":
            payload = {"cmd": "paramconf","ext": {"st": 20,"et": 5,"collt": 10,"htim": 0,"datt": 20,"pump_sec": 20,"shake_sec": 20,"boot": 1}}

    elif int(device_type_id) == 14:
        topic = "yfkj/color/s2c/%s" % device_id
        if cmd == "update":
            payload = {"cmd": "dtu_update"}
        elif cmd == "reboot":
            payload = {"cmd": "dtu_reboot"}
        elif cmd =="takephoto":
            payload = {"cmd":"rtu_takephoto"}
    payload = json.dumps(payload)
    data = {"topic":topic,"payload":payload,"qos":1}
    logger.warning(f"设备下发的指令：{data}")
    response = requests.post(
        "%s" % config_dict['mqtt_config']["http"], 
        json=data,
        auth=HTTPBasicAuth(
                config_dict['mqtt_config']["user"], 
                config_dict['mqtt_config']["secret_key"]
            )
        )
    logger.warning(f"设备的返回值：{response}")
    response_code = response.status_code
    if response_code == 200:
        if cmd not in ["takephoto"]:
            device_config = MongoDeviceConfig.objects.get(d_id=d_id)
            device_config.device_config = str(payload)
            device_config.save()
            logger.warning(f"修改设备{d_id} 成功: {str(payload)}")
        return True
    else:
        return False

