import json
import re

from pot_libs.logger import log
from pot_libs.aiohttp_util.aiohttp_utils import AioHttpUtils
# from bromake.modules.shidianu.service.open_data_service import get_token
from pot_libs.settings import SETTING
import base64
from pot_libs.mysql_util.mysql_util import MysqlUtil


async def get_td_engine_data(url, sql):
    if "?" not in url:
        url += "?tz=Asia/Shanghai"
    token = get_token()
    log.info(f"token:{token},sql:{sql}")
    resp_str, status = await AioHttpUtils().post_data(
        url, data=sql, timeout=50,
        headers={"Authorization": f"Basic {token}"}
    )
    results = json.loads(resp_str)
    log.info(f"resp_str:{resp_str},status:{status}")
    if results["code"] != 0:
        return False, None
    return True, results


def get_token():
    user_password = f"{SETTING.td_user}:{SETTING.td_pwd}"
    token = base64.b64encode(user_password.encode()).decode()
    return token


async def insert_into_tidb(schema, tables, value):
    sql = (
        f'''
         INSERT INTO {schema}.{tables} VALUES({value});
        '''
    )
    async with MysqlUtil() as conn:
        datas = await conn.fetchone(sql)
    return datas if datas else {}


def test_td_engine():
    """
    td_eignne insert into TiDB
    """
    from pot_libs.settings import SETTING
    import requests
    token = get_token()
    url = f"{SETTING.stb_url}db_water?tz=Asia/Shanghai"
    print(token)
    h = {"Authorization": f"Basic {token}"}
    sql = f"select * from db_water.water_stb limit 10 "
    r = requests.post(url, data=sql, headers=h)
    print(r.status_code)
    print(r.content)
    a_list, a_dict = [], {}
    for data in json.loads(r.content)['data']:
        index = 0
        for head in json.loads(r.content)['head']:
            a_dict.update({head: data[index]})
            index += 1
        a_list.append(a_dict)
    print(a_list)


async def elec_current_data_new16(mtids):
    res_map = {}
    url = f"{SETTING.stb_url}db_electric?tz=Asia/Shanghai"
    table_names = [get_td_table_name("electric", mtid) for mtid in mtids]
    if len(table_names) > 1:
        for table_name in table_names:
            sql = f"select last_row(*) from {table_name} group by tbname "
            is_succ, results = await get_td_engine_data(url, sql)
            if is_succ:
                head = parse_td_columns(results)
                for res in results["data"]:
                    data = dict(zip(head, res))
                    res_map[data["mtid"]] = data
            res_map.update(res_map)
            return res_map, {}
    else:
        sql = f"select last_row(*) from " + "".join(
            table_names) + "group by tbname "
        is_succ, results = await get_td_engine_data(url, sql)
        if is_succ:
            head = parse_td_columns(results)
            for res in results["data"]:
                data = dict(zip(head, res))
                res_map[data["mtid"]] = data
        return res_map, {}


def get_td_table_name(topic, id):
    """
    :param topic: 需要查询的主题
    :param id: 表命名使用的id
    :return:
    """
    topic_map = {
        "electric": "mt%s_ele",
        "pv_ele": "pv_ele%s",
        "pv_sts": "pv_sts%s",
        "ws": "ws%s"
    }
    table_name = topic_map.get(topic)
    return table_name % id


# td 3.0
def td3_tbl_compate(td_tables):
    if len(td_tables) > 1:
        return tuple(td_tables)

    return f"('{td_tables[0]}')"


def parse_td_columns(rsp_data):
    head = []
    if not rsp_data.get("column_meta"):
        return []
    for col in rsp_data["column_meta"]:
        r = re.findall(r'last_row\((.*)\)', col[0])
        tbl_field = r[0] if r else col[0]
        head.append(tbl_field)
    return head


def get_td_table_name(topic, id):
    """
    :param topic: 需要查询的主题
    :param id: 表命名使用的id
    :return:
    """
    topic_map = {
        "water": "water_ele_electric_ops%s",
        "electric": "mt%s_ele_electric_ops",
        "pv_ele": "pv_ele%s",
        "pv_sts": "pv_sts%s",
        "ws": "ws%s",
        "adi": "mt%s_adi_electric_ops",
        "pt_temp": "pt_temp%s_electric_ops",  # 电容
        "ent_guard_sts_stb": "ent_guard_sts%s",  # 门控
        "ent_guard_soe_stb": "ent_guard_soe%s",  # 门控报警
        "indoor_temp_stb": "indoor_temp%s",  # 室内温度
        "indoor_temp_soe_stb": "indoor_temp_soe%s",  # 室内温度报警
        "indoor_hum_stb": "indoor_hum%s",  # 室内湿度
        "indoor_hum_soe_stb": "indoor_hum_soe%s",  # 室内湿度报警
        "water_fld_sts_stb": "water_fld_sts%s",  # 水浸
        "water_fld_soe_stb": "water_fld_soe%s",  # 水浸报警
        "smoke_sts_stb": "smoke_sts_stb%s",  # 烟感
        "smoke_soe_stb": "smoke_soe_stb%s",  # 烟感报警
        "old_adio_stb": "s_%s_a",  # 安电--旧 这里是%s是sid
        "new_adio_stb": "mt%s_adi",  # 安电——新
        "old_electric_stb": "s_%s_a",
        "new_electric_stb": "mt%s_ele",

    }
    table_name = topic_map.get(topic)
    return table_name % id
