import asyncio
import json
import sys
import os
import pendulum

base_path = os.path.abspath('../../../')
sys.path.append(base_path)
sys.path.append(f'{base_path}/pot_libs')
from pot_libs.mysql_util.mysql_util import MysqlUtil
from pot_libs.utils.pendulum_wrapper import my_pendulum

"""
××运行前确认PRO_INF是否正确××
  sql条件product = 1
"""

PRO_INF = {
    "table": "user_portrait",
    "product": 1
}

DEMO_CID = "[42]"

hn_filter_proxy = [11, 13, 14, 15, 16, 17]  # 生产
# hn_filter_proxy = [8, 7]  # 测试


async def user_auth_asy():
    """同步用户信息到新表"""
    # 1. 通过华能proxy_id反查华能cid
    hn_sql = "SELECT c.cid from company c left join " \
              "company_proxy_map cpm on cpm.cid=c.cid " \
              "where cpm.proxy in %s and c.product = 1"
    async with MysqlUtil() as conn:
        hn_cid_info = await conn.fetchall(sql=hn_sql,
                                          args=(tuple(hn_filter_proxy),))
    hn_filter_cid = [c.get("cid") for c in hn_cid_info]
    # 2. 查询user_elecsafe表所有记录
    table = PRO_INF["table"]
    sql = f"SELECT * from {table}"
    async with MysqlUtil() as conn:
        demo_info = await conn.fetchall(sql=sql)
    # 2.构造新表数据
    for info in demo_info:
        cid = info.get("cid")
        proxy = info.get("proxy_id")
        inner = None
        proxy_list = []
        if proxy:
            proxy_id_list = proxy.split(",")
            proxy_list = [int(i) for i in proxy_id_list]
        # 2.1过滤掉华能
        # 过滤proxy
            inner = [i for i in proxy_list if i in hn_filter_proxy]
        if inner:
            continue
        # 过滤cid
        if cid in hn_filter_cid:
            continue
        # 2.2新表字段数据
        user_id = info.get("user_id")
        product = PRO_INF["product"]
        type = info.get("type")
        # uassistant_auth = info.get("super_auth")
        created_time = info.get("created_at")
        # demo_cid = None
        # 创建时间转换为时间戳
        if created_time:
            dt = my_pendulum.from_format(str(created_time),
                                         'YYYY-MM-DD HH:mm:ss')
            created_time = dt.int_timestamp
        if type == 0:  # 超级用户，所有工厂的权限
            proxy_id = 0
            cid_ext = None
        elif type == 1:
            proxy_id = None
            cid_ext = None
            # 只配了一个代理
            if len(proxy_list) == 1:
                proxy_id = proxy_list[0]
            # 如果proxy_id=13,则有华能代理权限
            elif 13 in proxy_list:
                proxy_id = 13
            # 作为工厂用户迁移
            else:
                sql_cid = "SELECT c.cid from company c left join " \
                         "company_proxy_map cpm on cpm.cid=c.cid " \
                         "where cpm.proxy in %s and c.product = 1"
                async with MysqlUtil() as conn:
                    cid_res = await conn.fetchall(sql=sql_cid,
                                                  args=(tuple(proxy_list),))
                cid_ext = {}
                for cid in cid_res:
                    cid_ext[str(cid["cid"])] = []
                cid_ext = json.dumps(cid_ext)
        elif type == 2:
            cid = info.get("cid")
            cid_ext = {str(cid): []}
            cid_ext = json.dumps(cid_ext)
            proxy_id = None
        else:  # type3 demo用户
            continue
        # 3.插入数据到user_product_auth
        if not created_time:
            dt = pendulum.now()
            timestamp = dt.int_timestamp
            created_time = timestamp
        print(user_id, product, cid_ext, proxy_id, 0, created_time)
        sql_ins = "INSERT INTO user_product_auth " \
                  "(user_id, product, cid_ext, proxy, " \
                  "uassistant_auth, created_time) " \
                  "VALUES (%s, %s, %s, %s, %s, %s)"
        try:
            async with MysqlUtil() as conn:
                cid_res = await conn.execute(sql_ins, args=(
                    user_id, product, cid_ext, proxy_id, 0,
                    created_time))
        except Exception as e:
            continue


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(user_auth_asy())
