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


async def user_auth_asy():
    """fcl同步用户信息到新表"""
    # 1. 查询user_fcl表所有记录
    sql = "SELECT * from user_fcl where is_active = 1"
    async with MysqlUtil() as conn:
        demo_info = await conn.fetchall(sql=sql)
    for info in demo_info:
        user_id = info.get("user_id")
        type = info.get("type")
        proxy_id = info.get("proxy_id")
        # 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
        else:
            dt = pendulum.now()
            timestamp = dt.int_timestamp
            created_time = timestamp
        # 2. 迁移逻辑
        # 2.1 type = 1 and proxy_id = 5, 迁移到“知电U” 和 “知电U管理版”，配proxy字段
        if type == 1 and proxy_id == 5:
            # 迁移到“知电U”
            insert_sql = "INSERT INTO user_product_auth (user_id, product, " \
                         "proxy, created_time) VALUES (%s, %s, %s, %s)"
            args1 = (user_id, 1, 5, created_time)
            # 迁移到“知电U管理版
            args2 = (user_id, 5, 5, created_time)
            try:
                async with MysqlUtil() as conn:
                    await conn.execute(insert_sql, args=args1)
                    await conn.execute(insert_sql, args=args2)
            except Exception as e:
                print(e)
                print(f"{user_id} insert mysql failed")
                continue
        # 2.2 type = 1 and proxy_id = 10, 迁移到“知电U”，配到cid_ext字段
        elif type == 1 and proxy_id == 10:
            # 迁移到“知电U”
            cid_ext = {}
            sql_cid = "SELECT cid from company where proxy = 10 and " \
                      "product = 1"
            async with MysqlUtil() as conn:
                cid_res = await conn.fetchall(sql=sql_cid)
            for cid in cid_res:
                cid_ext[str(cid["cid"])] = []
            cid_ext = json.dumps(cid_ext)
            insert_sql = "INSERT INTO user_product_auth (user_id, product, " \
                         "cid_ext, created_time) VALUES (%s, %s, %s, %s)"
            args = (user_id, 1, cid_ext, created_time)
            try:
                async with MysqlUtil() as conn:
                    await conn.execute(insert_sql, args=args)
            except Exception as e:
                print(e)
                print(f"{user_id} insert mysql failed")
                continue
        # 2.3 type = 2的记录全部迁移到“知电U”，配置cid_ext字段
        elif type == 2:
            cid = info.get("cid")
            cid_ext = {str(cid): []}
            cid_ext = json.dumps(cid_ext)
            insert_sql = "INSERT INTO user_product_auth (user_id, product, " \
                         "cid_ext, created_time) VALUES (%s, %s, %s, %s)"
            args = (user_id, 1, cid_ext, created_time)
            try:
                async with MysqlUtil() as conn:
                    await conn.execute(insert_sql, args=args)
            except Exception as e:
                print(e)
                print(f"{user_id} insert mysql failed")
                continue


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