from pyramid.view import view_config
from ..models import UserManager
import random

from ..mns.account import Account
from ..mns.topic import *


@view_config(route_name='authority.requestfindsms', request_method='POST', renderer='json')
def requestSingleFinddSms(request):
    session = request.session
    if not 'verifycode' in session:
        mobile = request.POST.get("mobile")
        account = request.POST.get("account")
        mgr = UserManager(request.dbsession)
        if not mgr.checkUserMobile(account,mobile):
            return {"r":1,"msg":"用户名手机号不匹配"}

        code = random.randrange(100000, 1000000)
        session['verifycode'] = str(code)
        session['mobile'] = mobile
        my_account = Account("http://1123295317641689.mns.cn-beijing.aliyuncs.com/", "LTAI4YCzRAOIaA6v", "thUkHSGun0Ant797JsJexcZlSV3X0a")
        my_topic = my_account.get_topic("sms.topic-cn-beijing")
        msg_body = "sms-message"
        direct_sms_attr1 = DirectSMSInfo(free_sign_name="建研数力", template_code="SMS_70350062", single=True)
        direct_sms_attr1.add_receiver(receiver=mobile)
        direct_sms_attr1.set_params({"code":session['verifycode']})
        msg1 = TopicMessage(msg_body, direct_sms=direct_sms_attr1)
        re_msg = my_topic.publish_message(msg1)
        if(re_msg.message_id):
            return {"r":0,"msg":"发送成功"}
        else:
            return {"r":0,"msg":"发送失败，请重试"}

    return {"r":1,"msg":"请求频繁，请稍后再试"}


@view_config(route_name='authority.requestsendsms', request_method='POST', renderer='json')
def requestSingleSendSms(request):
    session = request.session
    if not 'verifycode' in session:
        mobile = request.POST.get("mobile")
        if(len(mobile)==11):
            code = random.randrange(100000, 1000000)
            session['verifycode'] = str(code)
            session['mobile'] = mobile

            my_account = Account("http://1123295317641689.mns.cn-beijing.aliyuncs.com/", "LTAI4YCzRAOIaA6v", "thUkHSGun0Ant797JsJexcZlSV3X0a")
            my_topic = my_account.get_topic("sms.topic-cn-beijing")
            msg_body = "sms-message"
            direct_sms_attr1 = DirectSMSInfo(free_sign_name="建研数力", template_code="SMS_70250119", single=True)
            direct_sms_attr1.add_receiver(receiver=mobile)
            direct_sms_attr1.set_params({"code":session['verifycode']})
            msg1 = TopicMessage(msg_body, direct_sms=direct_sms_attr1)
            re_msg = my_topic.publish_message(msg1)
            if(re_msg.message_id):
                return {"r":0,"msg":"发送成功"}
            else:
                return {"r":0,"msg":"发送失败，请重试"}
        else:
            return {"r":0,"msg":"手机号非法"}

    return {"r":1,"msg":"请求频繁，请稍后再试"}
