import requests
import json
from json import JSONDecodeError

from requests.auth import HTTPBasicAuth
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


@kedong_deco(login_required=True)
def device_control_info(request):
    """
    设备控制信息/ 设备操作当前状态
    参数：
    d_id                   必传                         设备自增id
    cmd                    必传                         netconf/paramconf/config/。。。用来标记获取什么类型的配置信息
    """
    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', "参数缺失")

    if MongoDeviceConfig.objects.filter(d_id=d_id,cmd=cmd).exists():
        d_config = MongoDeviceConfig.objects.get(d_id=d_id,cmd=cmd)
        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:
        raise PortError(d_id, "配置未上传")


def user_device_control(request):
    """
    用户远程控制设备下发（用于对接）
    参数：
    device_type_id              必传                          设备类型  2杀虫灯,3测报灯,4智能性诱,7孢子仪 5气象站, 14色诱测报灯 12吸虫塔
    device_id                   必传                          设备号
    config                      必传                          设备控制参数
    username                    必传                          用户名

    config 说明：
        测报灯：{'ts': 0, 'tpl': 5, 'tt': 6, 'collt': 10, 'datt': 20, 'htim': 10, 'et': 6, 'st': 20, 'hst': 85, 'tph': 70, 'imgres': 0}
        测报灯拍照：takephoto
}

     具体说明太长          对接口问我要
    """
    #测报灯  下发主题  /yfkj/cbd/sub/+imei
    #杀虫灯  下发主题  /yfkj/scd/sub/+imei
    #性诱设备  下发主题 yfkj/xycb/s2c/+imei
    #孢子仪  下发主题 /yfkj/bzy/s2c/+imei
    # myuid = request.myuser.uid
    # user_type = request.user_type
    post_info = request.POST
    username = post_info.get("username")
    ip = request.META.get('REMOTE_ADDR')
    try:
        check_username = DeviceUser.objects.get(real_name=username)
    except:
        raise PortError('username', "用户名不存在")

    if check_username.user_type == 3:
        raise PortError('', "控制异常,请联系上级")

    
    
    device_type_id = post_info.get("device_type_id", '')
    device_id = post_info.get("device_id", '')
    if not device_id:
        raise PortError('device_id',"参数缺失")
    devices = Device.objects.all()
   
    try:
        device = devices.get(device_id=device_id)
    except:
        raise PortError("device_id","没有此设备")

    if not check_username.user_type == 1 and device.device_expire == "1":
        raise PortError("device_id","设备已过期")
    
    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:
        if config == "takephoto":
            payload["cmd"] = "takephoto"
        else:
            try:
                config = json.loads(config)
            except  JSONDecodeError as e:
                config = eval(config)
            except:
                raise PortError('',"参数类型错误")
            payload["cmd"] = "paramconf"
            payload["ext"] = config
    else:
        raise PortError('',"缺少config参数")

    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
    else:
        raise PortError('device_type_id',"参数超出范围")

    payload = json.dumps(payload)
    cmds = {"topic":topic,"payload":payload,"qos":1}

    content = "设备类型：%s,下发：%s"
    operation_log(check_username.uid, content % (device_type_id, payload), device.device_id, 0, ip)
    res = rp(cmds)
    if res.status_code == 200:
        return True


def user_get_device_config(request):
    """
    查询设备配置信息/设备监测最新数据  （用于对接)
    参数：
    device_type_id                  必传                         设备类型  3测报灯
    device_id                       必传                         设备号
    control_type                    必传                         操作类型  data 读取设备数据信息
    username                        必传                         用户名
    """
    #测报灯  下发主题  /yfkj/cbd/sub/+imei
    #杀虫灯  下发主题  /yfkj/scd/sub/+imei
    #性诱设备  下发主题 yfkj/xycb/s2c/+imei
    #孢子仪  下发主题 /yfkj/bzy/s2c/+imei
    # uid = request.myuser.uid
    # user_type = request.user_type
    # if user_type == 3:
    #     raise PortError('', "控制异常,请联系上级")
    
    post_info = request.POST
    device_type_id = post_info.get("device_type_id", '')
    device_id = post_info.get("device_id", '')
    if not device_id:
        raise PortError('device_id', "参数缺失")
    username = post_info.get("username")
    ip = request.META.get('REMOTE_ADDR')
    try:
        check_username = DeviceUser.objects.get(real_name=username)
    except:
        raise PortError('username', "用户名不存在")
    devices = Device.objects.all()
    device = devices.get(device_id=device_id)

    # myuser_type = request.user_type
    if not check_username.user_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:
        topic = "/yfkj/cbd/sub/%s" % device.device_id
    else:
        raise PortError('device_type_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}    
    res = requests.post("%s"%config_dict['mqtt_config']["http"], json=cmd,
                        auth=HTTPBasicAuth(config_dict['mqtt_config']["user"], config_dict['mqtt_config']["secret_key"]))

    if res.status_code == 200:
        return True
    else:
        return False


@kedong_deco(login_required=True)
def device_control(request):
    """
    设备下发控制
    参数：
    device_type_id              必传                         设备类型  2杀虫灯,3测报灯,4智能性诱,7孢子仪 5气象站, 14色诱测报灯 12吸虫塔
    d_id                        必传                         设备自增id
    config                      非必传                        设备控制参数
    work_type                   非必传                        工作模式时 必传 0节能 1常规  2加强
    cmd                         非必传                        下发服务器配置使用 setnet
    device_name                 必传                          设备名称

    config 说明：
        测报灯：{'ts': 0, 'tpl': 5, 'tt': 6, 'collt': 10, 'datt': 20, 'htim': 10, 'et': 6, 'st': 20, 'hst': 85, 'tph': 70, 'imgres': 0}
        孢子仪：{'datt': 0, 'drop_time': 0, 'imgres': 0, 'set_temp': 25, 'coll_time': ['7-9', '10-11', Ellipsis], 'cul_time': 24, 'wind_sw': 0}
        杀虫灯：{'timctrl': 1, 'et': 22, 'st': 20}
        色诱测报灯: {'cmd': 'photoconf','ext': {'start': '18','end': '22','freq': '20'}   下发设置工作时间
}

                具体说明太长          对接口问我要
    """
    #测报灯  下发主题  /yfkj/cbd/sub/+imei
    #杀虫灯  下发主题  /yfkj/scd/sub/+imei
    #性诱设备  下发主题 yfkj/xycb/s2c/+imei
    #孢子仪  下发主题 /yfkj/bzy/s2c/+imei
    myuid = request.myuser.uid
    user_type = request.user_type
    if user_type == 3:
        raise PortError('', "控制异常,请联系上级")
    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 not user_type == 1 and 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"
            rp(cmds)
        if interval:
            payload["cmd"] = "config"
            payload["ext"] = {"interval":interval}
            cmds = {"topic": topic, "payload": payload, "qos": 1}
            rp(cmds)
        return True
    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"
    # TODO 大数据平台转发
    print(cmds)
    response_code = 200
    if response_code == 200:
        return True


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



def clear_insects(request):
    """
    杀虫灯批量一键自清虫
    """
    uid = request.myuser.uid
    myuser = request.myuser
    device_query =  Device.devices(uid=uid,myuser=myuser)
    scd_query = device_query.filter(device_type_id=2)
    scd_imei_list = [i.device_id for i in scd_query]
    for i in scd_imei_list:
        topic = "/yfkj/scd/sub/%s" % i
        payload = json.dumps({"cmd": "ctr_clear"})
        cmds = {"topic":topic,"payload":payload,"qos":1}
        try:
            res = rp(cmds)
            if res.status_code != 200:
                return False
        except:
            return False
    return True



def scd_device_control(request):
    """
    杀虫灯批量下发控制接口
    参数：
    imei_list                   必传                         设备imei号 为选中的设备下发
    config                      必传                       设备控制参数
      
    config 说明：
        杀虫灯：{"st":"20","et":"2","ds":"0","ts":"0","tt":"4","dattim":"30","clt":"120"}

    下发成功后返回值：
    "data": [],
    下发未成功返回值：
     "data": [
        "863488050761140"                                   下发未成功设备号
    ],
}
    """
    #测报灯  下发主题  /yfkj/cbd/sub/+imei
    #杀虫灯  下发主题  /yfkj/scd/sub/+imei
    #性诱设备  下发主题 yfkj/xycb/s2c/+imei
    #孢子仪  下发主题 /yfkj/bzy/s2c/+imei
    imei_list = request.POST.get("imei_list")

    config = request.POST.get("config", '')
    uid = request.myuser.uid
    myuser = request.myuser

    if not config:
        raise PortError("config","配置信息未传")
    if not imei_list:
        raise PortError("imei_list","设备列表未传")
    
    try:
        config = json.loads(config)
    except:
        raise PortError('',"参数类型错误")
    data = []
    payload = {}
    payload["cmd"] = "paramconf"
    payload["ext"] = config
    payload = json.dumps(payload)

    device_ids = json.loads(imei_list)
    device_query =  Device.devices(uid=uid,myuser=myuser)
    scd_query = device_query.filter(device_type_id=2)
    scd_list = [i.device_id for i in scd_query]
    
    for i in device_ids:
        if i in scd_list:
            topic = "/yfkj/scd/sub/%s" % i
            cmds = {"topic":topic,"payload":payload,"qos":1}
            try:
                res = rp(cmds)
                if res.status_code == 200:
                    pass
                else:
                    data.append(i)
            except:
                data.append(i)
        else:
            raise PortError('permission error',"%s设备非用户账户下"%i)
    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
    # uid = request.myuser.uid
    # user_type = request.user_type
    # if user_type == 3:
    #     raise PortError('', "控制异常,请联系上级")
    imei_list = ["866950041980524","866950041980458","866950041975045","866950041941286","866950041941203","866950041980425","866950041941377"]
    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
    if device.device_id in imei_list:
        topic = "yfkj/xycb/s2c/%s" % device.device_id
        cmd = {"topic": topic, "payload": json.dumps(payload), "qos": 1}
    #     res = requests.post("http://www.yfzhwlw.com:8080/api/v2/mqtt/publish",
    #                     data=json.dumps(cmd, indent=1), auth=HTTPBasicAuth("admin", "yfkj_6019"))
    # else:
    #     cmd = {"topic": topic, "payload": json.dumps(payload), "qos": 1}    
    #     res = requests.post("%s"%config_dict['mqtt_config']["http"], json=cmd,
    #                         auth=HTTPBasicAuth(config_dict['mqtt_config']["user"], config_dict['mqtt_config']["secret_key"]))
    # TODO 暂时处理调用http接口
    code = 200
    if code == 200:
        return True
    else:
        return False


@kedong_deco(login_required=True)
def admin_device_control(request):
    """
    单个按钮管理员操作  设备控制
    参数：
    device_type_id              必传                         设备类型  2杀虫灯,3测报灯,4智能性诱,5气象站,6监控设备,7孢子仪, 9糖醋测报灯 14色诱测报灯 8性诱3.0 12吸虫塔
    d_id                        必传                         设备自增id
    cmd                         必传                         设备控制参数  poweroff关机
                                                                        poweron开机
                                                                        reboot重启
                                                                        update升级
                                                                        coldoff制冷关闭
                                                                        coldon制冷开启
                                                                        takephoto拍照
                                                                        autotakephoto 对焦拍照
                                                                        boot1 屏幕禁用
                                                                        boot0 屏幕取消禁用
                                                                        turnset 设置定时卷粘虫板时间
                                                                        turn 卷粘虫带/转仓
                                                                        photoset 拍照时刻
                                                                        repower 重新上电
                                                                        data    数据上传
                                                                        mqttconf  mqtt网络配置
                                                                        close_shake 关闭震动
                                                                        open_shake  开启震动
                                                                        clearworm   清网
                                                                        dtu_reboot  重启
                                                                        dtu_update  升级
                                                                        test        杀虫灯一键测试
                                                                        big_data    平台转换到大数据平台
                                                                        yfwlw       平台转发到四情平台
                                                                        location 手动定位,传lat、lng 参数
                                                                        imei 修改设备号, 传 imei 参数设备号
                                                                        photo_num  拍照数量 传num 参数 拍照数
    parm                        非必传                     当某些控制操作需要参数限制的时候 必传  （比如设置定时时间10分钟  传 10）


    """
    #测报灯  下发主题  /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}
    # TODO 调用大数据平台接口
    response_code = 200
    if response_code == 200:
        return True
    else:
        return False



def tccbd_device_control(request):
    """
    糖醋测报单个按钮操作/设备设置
    参数：
    device_type_id              必传                         设备类型   9 糖醋测报灯
    d_id                        必传                         设备自增id
    cmd                         必传                         设备控制参数  reboot重启
                                                                        update升级
                                                                        takephoto拍照
                                                                        boot1 屏幕禁用
                                                                        status 查询最新状态
                                                                        paramconf 查询配置信息
                                                                        

                                                                        set 下发设置所需参数
                                                                        st 定时开始时间
                                                                        et 定时结束时间
                                                                        collt 收集时间
                                                                        htim 糖醋液发挥时间
                                                                        datt 数据上传时间间隔
                                                                        pump_sec 水泵打开时间
                                                                        shake_sec 电磁阀打开时间
                                                                        jp 加液排水时间


    """
    
    post_info = request.POST
    device_type_id = post_info.get("device_type_id", '')
    d_id = post_info.get("d_id", '')
    cmd = post_info.get("cmd", '')
    devices = Device.objects.all()
    device_id = devices.get(id=int(d_id)).device_id
    if not cmd:
        raise PortError('cmd', "参数缺失")
    if  int(device_type_id) == 9:
        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 cmd == "set":
            st = post_info.get('st') #定时开始时间
            et = post_info.get('et')#定时结束时间
            collt = post_info.get('collt') #收集时间
            htim = post_info.get('htim') #糖醋液发挥时间
            datt = post_info.get('datt') #数据上传时间间隔
            pump_sec = post_info.get('pump_sec')    #pump_sec水泵打开时间
            shake_sec = post_info.get('shake_sec') #电磁阀打开时间
            jp = post_info.get("jp")  # 加液排水时间
            payload = {"cmd": "paramconf","ext": {"st": int(st),"et": int(et),"collt": int(collt),"htim": int(htim),"datt": int(datt),"pump_sec": int(pump_sec),"shake_sec": int(shake_sec),"jp":int(jp),"boot": 0}}

        topic = "/yfkj/tccbd/sub/%s" % device_id
        payload = json.dumps(payload)
        data = {"topic":topic,"payload":payload,"qos":1}
        res = requests.post("%s" % config_dict['mqtt_config']["http"], json=data,
                            auth=HTTPBasicAuth(config_dict['mqtt_config']["user"], config_dict['mqtt_config']["secret_key"]))
        if res.status_code == 200:
            return True
    else:
        raise PortError('cmd', "设备类型错误")




def device_sim(request):
    """
    设备查询sim卡接口
    d_id                        必传                         设备自增id
    iccid                       非必传                       用户填写的iccid
    type                        必传                         sim卡类型 sim  hksim 海康sim  change修改 iccid
    
    """
    post_info = request.POST
    _device_id = post_info.get("d_id")
    iccid = post_info.get("iccid")

    types = post_info.get("type")

    if not _device_id:
        raise PortError('d_id', "未传设备id")

    if iccid and not iccid.isalnum():
        # if not iccid.isalnum():
        raise PortError('iccid', "不能输入特殊字符")

    data = []
    try:
        device = Device.objects.get(id=_device_id)
    except:
        raise PortError('d_id', "没有该设备")
    if types == "hksim":
        data.append({"iccid":device.simid})
    elif types == "sim":
        if device.device_type_id == 7:
            models = BZYData
        elif device.device_type_id == 4:
            models = XYCBData
        elif device.device_type_id == 2:
            models = SCDData
        elif device.device_type_id == 3:
            models = CBDData
        elif device.device_type_id == 8:
            models = XYThreeData
        elif device.device_type_id == 14:
            models = SYCBData
        elif device.device_type_id == 12:
            models = XCTData
        else:
            raise PortError('d_id', "暂无该设备类型")
        
        # if device.device_type_id == 12:
        #     models = XCTData

        decic = models.objects.filter(device_id=_device_id).order_by('-id')[:1]
        # decic = DeviceData.objects.filter(device_id=_device_id).order_by('-addtime')[:1]
        for  i in decic:
            try:
                iccid = eval(i.device_data)["iccid"]
            except:
                iccid = ""
            data.append({"iccid":iccid})
    elif types == "change":
        device.simid = iccid
        device.save()
        data.append({"iccid":iccid})
    else:
        raise PortError('d_id', "参数有误")
    return data


