# coding:utf-8
__author__ = 'Tone'
__date__ = '2018/8/3 '
from random import Random
from users.models import EmailVerifyRecord
from django.core.mail import send_mail
from Djangtest.settings import EMAIL_FROM
from datetime import datetime,timedelta


# 生产随机字符串
def random_str(randomlength = 8):
    str=''
    chars='AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(randomlength):
        str += chars[random.randint(0,length)]
    return str

# 发送邮件验证码
def send_register_email(email,send_type='register'):
    email_record = EmailVerifyRecord()
    if send_type == 'update':
        code = random_str(4)
    else:
        code = random_str(16)
    email_record.code = code
    email_record.email = email
    email_record.send_type = send_type
    email_record.ex_time = datetime.now()+timedelta(days=1)
    email_record.save()

    if send_type == 'register':
        email_title = '清客在线激活链接'
        email_body = ' 点击下方链接自动激活:http://127.0.0.1:8000/active/{0}'.format(code)
        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        if send_status:
            pass
    elif send_type == 'forget':
        email_title = '清客在线密码重置'
        email_body = ' 点击下方链接进入重置页面:http://127.0.0.1:8000/reset/{0}'.format(code)
        send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        if send_status:
            pass
    elif send_type == 'update':
        email_title = '清客在线修改邮箱'
        email_body = '你的验证码为{0}'.format(code)
        # send_status = send_mail(email_title, email_body, EMAIL_FROM, [email])
        # if send_status:
        #     pass