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():
    """hn同步用户信息到新表"""
    # 1. 查询user_portrait表所有记录
    sql = "SELECT * from user_portrait 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")
        cid = info.get("cid")
        # 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 proxy_id = "11,13,14,15,16,17,19", 迁移到“知电U” 和 “知电U管理版”，配proxy=13字段
        if type == 1 and proxy_id == "11,13,14,15,16,17,19":
            # 迁移到“知电U”管理版
            insert_sql = "INSERT INTO user_product_auth (user_id, product, " \
                         "proxy, created_time) VALUES (%s, %s, %s, %s)"
            args1 = (user_id, 1, 13, created_time)
            # 迁移到“知电U管理版
            args2 = (user_id, 5, 13, 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 迁移到“知电U”，配到cid_ext字段
        elif type == 1 and proxy_id in (
                                    "11", "13", "14", "15", "16", "17", "19"):
            # 迁移到“知电U”
            cid_ext = {}
            sql_cid = "SELECT c.cid from company c left join " \
                      "company_proxy_map cpm on cpm.cid=c.cid " \
                      "where cpm.proxy = %s and c.product = 1"
            async with MysqlUtil() as conn:
                cid_res = await conn.fetchall(sql=sql_cid, args=(proxy_id,))
            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 工厂用户迁移到“知电U”，配置cid_ext字段
        elif type == 2 and cid in (82, 87, 88, 84, 85, 89, 90, 92, 93, 96,
                                   97, 98, 99, 100, 102, 107, 108, 101, 103,
                                   91, 95, 104, 105, 106, 86, 109, 142, 143):
            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())
