from celery import Celery
from django.conf import settings
from django.core.mail import send_mail
import time

import os
import django
from django.template import loader, RequestContext

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TTShengXian.settings')
django.setup()

from apps.goods.models import GoodsType, IndexGoodsBanner, IndexPromotionBanner, IndexTypeGoodsBanner

# 创建celery类的实例对象
task0 = Celery('celery_tasks.tasks', broker='redis://192.168.0.250:6379/0')


# 定义任务函数
@task0.task
def send_register_active_email(to_email, username, token):
    # 发送邮件
    subject = '天天生鲜欢迎信息'
    message = ''
    sender = settings.EMAIL_FROM
    receiver = [to_email]
    html_message = '<h1>%s 欢迎您成为天天生鲜注册会员</h1>请点击<a href="http://127.0.0.1:8000/user/active/%s">激活</a>您的账户<br/>' % (
        username, token)

    send_mail(subject, message, sender, receiver, html_message=html_message)
    time.sleep(7)

@task0.task
def generate_static_index_html():
    # 产生首页静态文件
    # 获取商品种类信息
    types = GoodsType.objects.all()

    # 获取首页轮播商品信息
    goods_banners = IndexGoodsBanner.objects.all().order_by('index')  # 0 1 2 3 4

    # 获取首页促销活动信息
    promotion_banners = IndexPromotionBanner.objects.all().order_by('index')

    # 获取首页商品分类商品展示信息
    for type in types:  # GoodType
        # 获取type种类首页分类商品的图片展示信息
        image_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1).order_by('index')
        # 获取type种类首页分类商品的文字展示信息
        title_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0).order_by('index')

        # 动态给type增加属性，分别保存首页分类的图片和文字展示信息
        type.image_banners = image_banners
        type.title_banners = title_banners

    # 组织模版上下文
    context = {'types': types,
               'goods_banners': goods_banners,
               'promotion_banners': promotion_banners}

    # 使用模版
    # return render(request, 'index.html', context)
    # 1. 加载模版文件
    temp = loader.get_template('static_index.html')
    # 2. 定义模版上下文,可以不加这一步，默认就传数据过来的
    # context = RequestContext(request, context)
    # 3. 模版渲染
    static_index_html = temp.render(context)

    # 生成首页对应静态文件
    save_path = os.path.join(settings.BASE_DIR, 'templates/index.html')
    print(save_path)
    with open(save_path, 'w', encoding='utf-8') as f:
        f.write(static_index_html)
