# coding:utf-8
import os
import sys
import time
local_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
if local_path not in sys.path:
    sys.path.append(local_path)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kedong.settings")
from django.conf import settings
from kedong.tools import RedisPool
from scripts.tools.utils import dashuju_pub_mqtt


cbd_redis_pool = RedisPool().get_redis_pool(settings.redis_db["cbd"])


def re_cbd_publish(payload):
    if settings.DEBUG:
        return None

    imei_id = payload['imei_id']
    at, ah = payload['at'], payload['ah']
    try:
        at = str(round(float(at)))
    except ValueError as e:
        at = "25"
    try:
        ah = str(round(float(ah)))
    except ValueError as e:
        print('at_error', e, payload)
        ah = "30"

    publics = "/yfkj/cbd/sub/#"

    TASK_TOPIC = publics.replace("#", imei_id)
    payload_1 = {"cmd": "sensor", "ext": {"new_hum": ah, "new_tem": at}}
    dashuju_pub_mqtt(TASK_TOPIC, payload_1)


def re_pub_cbd_publish(data):
    if settings.DEBUG:
        return None

    imei_id = data['imei_id']
    payload = data['payload']
    TASK_TOPIC = ""
    if TASK_TOPIC:
        dashuju_pub_mqtt(TASK_TOPIC, payload)


class CbdDeviceController(DeviceController):

    def cbd_device(self, data):
        table_name = "sa_device_cbd_data"
        DEVICE_NAME = "测报灯"
        DTYPE = 3
        serverconf = ''
        payload = data['payload']
        imei_id = data['imei_id']

        re_cbd_publish(data)
        re_pub_cbd_publish(data)

        ext = payload["ext"]
        dver_num = ext.get("dver", "")
        # 0-手动,1-GPS,2-基站
        gps = ext["gps"]  
        lng, lat = data['lng'], data['lat']

        device_code = 0
        try:
            device_code = int(ext.get("vtype", 0))
        except Exception as e:
            pass

        now_time = int(time.time())
        device_config = {
            "cmd": "paramconf",
            "ext": {
                "hst": ext.get("hst", "0"),
                "collt": ext.get("collt", ""),
                "et": ext.get("et", ""),
                "datt": ext.get("dat_f", 30),
                "shake_sec": ext.get("shake_sec", 1),
                "tpl": ext.get("tpl", 5),
                "shake": ext.get("shake", 0),
                "tph": ext.get("tph", 0),
                "ts": ext.get("ts", 0),
                "st": ext.get("st", 0),
                "htim": ext.get("htim", 0),
                "tt": ext.get("tt", 0),
                "ds": ext.get("ds", 0),
                "ws": ext.get("ws", 0),
            }
        }

        temp_dict = {
            'device_id': imei_id, 
            'device_type_id': DTYPE, 
            'dver_num': dver_num,
            'addtime': now_time, 
            'uptime': now_time, 
            'device_name': DEVICE_NAME,
            'lng': lng, 
            'lat': lat, 
            'gps': gps, 
            'serverconf': serverconf, 
            'device_status': 1,
            'device_code': device_code
        }
        return temp_dict, device_config, table_name

    def xct_device(self, data):
        """吸虫塔设备"""
        table_name = "sa_device_xct_data"
        DEVICE_NAME = "吸虫塔"
        # 设备类型id
        DTYPE = 12

        serverconf = ''
        payload = data['payload']
        imei_id = data['imei_id']

        re_cbd_publish(data)

        ext = payload["ext"]
        dver_num = ext["dver"]
         # 0-手动,1-GPS,2-基站
        gps = ext["gps"] 
        lng, lat = data["lng"], data["lat"]
        now_time = int(time.time())
        device_config = {
            "cmd": "paramconf",
            "ext": {
                "dat_f": ext.get("dat_f", 30),  # 数据上传时间
                "shake_sec": ext["shake_sec"],  # 震动时间
                "shake": ext["shake"],  # 震动开关， 1开启 0关闭
                "ds": ext["ds"],  # 设备开关机，1开机，0关机
                "dver": ext["dver"],  # 版本号
                "st": ext["st"],
                "et": ext["et"],
            }
        }
        temp_dict = {
            'device_id': imei_id, 'device_type_id': DTYPE, 'dver_num': dver_num,
            'addtime': now_time, 'uptime': now_time, 'device_name': DEVICE_NAME,
            'lng': lng, 'lat': lat, 'gps': gps, 'serverconf': serverconf, 'device_status': 1,
            'device_code': DTYPE
        }

        return temp_dict, device_config, table_name

    def make_device_config(self, data):
        payload = data['payload']
        ext = payload["ext"]
        try:
            vtype = int(ext["vtype"])
            if vtype == 6:
                return self.xct_device(data)
        except Exception as e:
            pass
        return self.cbd_device(data)


if __name__ == "__main__":
    # 正常消息订阅
    PUBLICS = "/yfkj/cbd/pub/#"
    # 离线消息订阅
    OFFLINE = "/yfkj/cbd/offline/#"
    cbd = CbdDeviceController()
    key = "/yfkj/cbd"
    while True:
        try:
            data = cbd_redis_pool.bpop(key)
            now_time = int(time.time())
            create_time = data['create_time']
            if now_time - create_time > 3600:
                continue
            cbd.device_controller(data)
        except Exception as e:
            print(e)
