import pendulum

from pot_libs.logger import log
from unify_api.modules.common.dao.common_dao import mid_by_pid, meter_by_mid, \
    meter_param_by_mid, change_sensor_by_location, get_point_monitor_dao, \
    get_location_monitor_dao
from uuid import uuid4


async def get_point_soe_config(event_data, with_params=False):
    """
    with_params: 用于同步配置参数信息，保证adio事件可以得到正确的数值
    """
    point_id = event_data.get('point_id')
    event_settings = {k: v for k, v in event_data.items() if k in [
        'threshold', 'duration', 'enable'
    ]}
    # 根据pid获取mid
    mid_dic = await mid_by_pid(point_id)
    mid = mid_dic.get("mid")
    if mid is None:
        log.info(f'=======no mid of point id: {point_id}')
        return None, None

    meter_dic = await meter_by_mid(mid)
    sid = meter_dic.get("sid")
    meter_sn = meter_dic.get("meter_no")

    config = {
        'soe': {
            "electric": {
                meter_sn: {event_data['event_type']: event_settings}}}
    }
    if with_params:
        params = await meter_param_by_mid(mid)
        params = {k: v for k, v in params.items() if v is not None}
        params['point_id'] = point_id
        config['params'] = {'electric': {meter_sn: params}}
    return sid, config


async def get_point_soe_config_new15(event_data, with_params=False):
    point_id = event_data.get('point_id')
    event_settings = {k: v for k, v in event_data.items() if k in [
        'threshold', 'duration', 'enable'
    ]}
    datas = await get_point_monitor_dao(point_id)
    sid = datas.get("sid")
    meter_sn = datas.get("meter_no")
    config = {
        'soe': {
            "electric": {
                meter_sn: {event_data['event_type']: event_settings}}}
    }
    if with_params:
        keys_li = ["ctr", "ptr", "ctnum", "vc", "tc", "imax"]
        params = {k: v for k, v in datas.items() if k in keys_li
                  and (v is not None)}
        params['point_id'] = point_id
        config['params'] = {'electric': {meter_sn: params}}
    return sid, config


async def get_location_soe_config(event, with_params):
    location_id = event.get('location_id')
    event_settings = {k: v for k, v in event.items() if k in [
        'threshold', 'duration', 'enable'
    ]}
    try:
        sensor_dic = await change_sensor_by_location(location_id)
        sid = sensor_dic.get("sid")
        field = sensor_dic.get("field")
    except:
        log.info(f'=======no sid of location: {location_id}')
        return None, None

    if field == "residual_current":
        config = {'soe': {"adio": {event['event_type']: event_settings}}}
    else:
        config = {
            'soe': {"adio": {field: {event['event_type']: event_settings}}}}
    if with_params:
        config['params'] = {'adio': {field: {'location_id': location_id}}}
    return sid, config


async def get_location_soe_config_new15(event, with_params):
    location_id = event.get('location_id')
    event_settings = {k: v for k, v in event.items() if k in [
        'threshold', 'duration', 'enable'
    ]}
    datas = await get_location_monitor_dao(location_id)
    sid = datas.get("sid")
    field = datas.get("ad_field")
    if field == "residual_current":
        config = {'soe': {"adio": {event['event_type']: event_settings}}}
    else:
        config = {
            'soe': {"adio": {field: {event['event_type']: event_settings}}}}
    if with_params:
        config['params'] = {'adio': {field: {'location_id': location_id}}}
    return sid, config


async def change_param_to_config(req_json, method):
    """
    web参数, 转换为与装置通信的报文
    soe method: config
    """
    sid, config = None, None
    point_id = req_json.get("point_id")
    if point_id is not None:
        # sid, config = await get_point_soe_config(req_json, with_params=True)
        sid, config = await get_point_soe_config_new15(req_json,
                                                       with_params=True)

    location_id = req_json.get('location_id')
    if location_id is not None:
        # sid, config = await get_location_soe_config(req_json,
        # with_params=True)
        sid, config = await get_location_soe_config_new15(req_json,
                                                          with_params=True)
    request_data = {}
    if sid:
        request_id = str(uuid4())
        request_data = dict(
            request_id=request_id,
            time=pendulum.now().to_datetime_string(),
            method=method,
            sid=sid, data=config)
    return request_data


async def switch_control_param_to_config(sid, field, switch,
                                         command="switch_control",
                                         method="command"):
    """
    联动控制, 转换为与装置通信的报文
    soe method: command
    """
    # 展龙反馈, 装置不识别00
    if switch == "00":
        switch = "10"
    request_id = str(uuid4())
    request_data = dict(
        request_id=request_id,
        time=pendulum.now().to_datetime_string(),
        method=method,
        sid=sid,
        data={'command': command,
              'params': {'field': field, 'value': switch}}
    )
    return request_data
