from pot_libs.common.components.responses import success_res
from unify_api.utils.response_code import RET
from unify_api.modules.qk_website.dao.apply_trial_dao import \
    get_apply_trial_by_data, save_apply_trial_by_data
from pot_libs.aredis_util.aredis_utils import RedisUtils
from pot_libs.aiokafka_util.kafka_util import KafkaUtils
from pot_libs.logger import log
from unify_api.constants import PRODUCT_INFOS


async def apply_trial_service(name, email, company, phone, product, ip):
    # 防止多次提交
    redis_client = RedisUtils()
    ip_count = await redis_client.get(ip) or b'0'
    ip_count = int(ip_count.decode())
    log.info(f"apply_trial ip: {ip}, ip_count:{ip_count}")
    if ip_count >= 5:
        return success_res(code=RET.already_submit, msg="提交次数过多，请5分钟后尝试")
    await redis_client.setex(ip, 300, ip_count + 1)

    is_having = await get_apply_trial_by_data(name, email, company,
                                              phone, product)
    if is_having:
        return success_res(code=RET.already_submit, msg="您已提交，请勿再次提交")
    await save_apply_trial_by_data(name, email, company, phone, product)
    # 微信通知
    dic_data = {
        "name": name,
        "email": email,
        "company": company,
        "phone": phone,
        "product": PRODUCT_INFOS.get(product).get("name"),
        "user_list": [10086, 111]
    }
    await KafkaUtils.send_msg(topic="power_iot.push.wechat_apply_trial_msg",
                              dic_data=dic_data)
    return success_res(code=RET.ok, msg="成功")
