import time
import json
import asyncio
from pot_libs.aredis_util import aredis_utils
from pot_libs.logger import log
from pot_libs.mysql_util import mysql_util
from unify_api.constants import Product

AUTH_EXP = 300  # redis缓存时间


async def load_product_auth(user_id, product_id):
    product_auth = {}
    sql = "SELECT product, cid_ext, proxy, created_time " \
          "FROM user_product_auth WHERE user_id=%s and product = %s"

    async with mysql_util.MysqlUtil() as conn:
        result = await conn.fetchone(sql, args=(user_id, product_id))
        if result:
            products = {}
            cid_dic = {}
            proxy_dic = {}
            product = str(result.get("product"))
            pro_id = int(product)
            if pro_id == 3:
                pro_id = 2
            if pro_id == Product.ZhidianUManage.value:
                pro_id = Product.ZhiDianU.value
            if pro_id == Product.RecognitionElectricNew.value:
                pro_id = Product.RecognitionElectric.value
            base_sql = "select cid from company where product = %s " \
                       "and is_show = 1"
            # 1. cid_ext工厂权限
            cid_ext = result.get("cid_ext")
            if cid_ext:
                cid_dic = json.loads(cid_ext)
                # 增加cid_dic校验 确保这个cid_ext配置的是这个产品的工厂
                async with mysql_util.MysqlUtil() as conn:
                    cids = await conn.fetchall(base_sql, args=(pro_id,))
                cid_list = [cid.get("cid") for cid in cids]
                cid_real = cid_dic.keys()
                cid_real = list(map(int, cid_real))
                if not set(cid_real) <= set(cid_list):
                    log.error(f"工厂配置错误, {cid_real} 不是 {cid_list}的子集")
                    cid_dic = {}
            # 2. proxy工厂权限, proxy为0则是超级权限
            proxy_id = result.get("proxy")
            if isinstance(proxy_id, str):
                if proxy_id == "0":
                    cid_sql = base_sql
                    args = (pro_id,)
                else:
                    proxy_id = proxy_id.split(',')
                    cid_sql = f"""
                    select c.cid from company c
                    left join company_proxy_map cpm on c.cid =cpm.cid
                    where product = %s and is_show = 1 and proxy in %s
                    """
                    args = (pro_id, proxy_id)
                async with mysql_util.MysqlUtil() as conn:
                    cids = await conn.fetchall(cid_sql, args=args)

                for cid in cids:
                    cid = cid.get("cid")
                    proxy_dic[f"{cid}"] = []
            # 3. 合并工厂dic
            proxy_dic.update(cid_dic)

            products[product] = proxy_dic
            product_auth["product"] = products
    # 4. 保存到redis
    # await aredis_utils.RedisClient().setex(
    #     f"auth:product_auth:{product_id}_{user_id}", AUTH_EXP,
    #     json.dumps(product_auth))

    return product_auth


async def get_product_auth(user_id, product_id):
    # auth_json = await aredis_utils.RedisClient().get(
    #     f"auth:product_auth:{product_id}_{user_id}")
    # if auth_json:
    #     product_auth = json.loads(auth_json)
    # else:
    product_auth = await load_product_auth(user_id, product_id)
    cid_ext = product_auth.get("product", {}).get(str(product_id), {})
    return {"product": cid_ext}


async def check_user_auth(request):
    user_id, product_id = 1, 1
    auth_json = await aredis_utils.RedisUtils().get(
        "auth:product_auth:%s" % user_id)
    if auth_json:
        product_auth = json.loads(auth_json)
    else:
        product_auth = await load_product_auth(user_id, product_id)
    cid_ext = product_auth.get("product", {}).get(product_id, {})
    if cid_ext:
        return True
    return False


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(get_product_auth(80, 2))
