from datetime import datetime

from pyramid.view import view_config
from pyramid.response import Response
from sqlalchemy.exc import DBAPIError
from ..models.UserRegInfo import UserRegInfo
from ..models.User import User
from ..models import UserManager
import os,json
from ..views import checkverifycode


DEFAULT_DIR = os.getenv("HOME", os.getcwd())

def getvalus(content,key):
    value = ""
    if(key in content):
        value = content.get(key,"")
        if(value==None):
            value = ""
    return value

def isNotNoneOrEmpty(value):
    return value!=None and value!=""

def checkRegInfo(regInfo):
    idname = getvalus(regInfo,"name")
    pusername = getvalus(regInfo,"account")
    mobile = getvalus(regInfo,"mobile")
    organization = getvalus(regInfo,"organization")
    ppassword = getvalus(regInfo,"password")
    ppassword2 = getvalus(regInfo,"password2")
    email = getvalus(regInfo,"email")
    return  isNotNoneOrEmpty(idname) and isNotNoneOrEmpty(pusername) and isNotNoneOrEmpty(mobile) and isNotNoneOrEmpty(organization) and isNotNoneOrEmpty(ppassword) \
            and isNotNoneOrEmpty(ppassword2) and ppassword2==ppassword and isNotNoneOrEmpty(email)

@view_config(route_name='authority.signup', renderer='../templates/regist.jinja2')
def main_signup_view(request):
    headers = [('Cache-Control', 'no-cache')]
    result = {"openid": "", "sceneid": "", "status": "", "result": ""}
    try:
        if request.method == "POST" and request.POST != None and len(request.POST)>0 and  'verifycode' in request.session:
            if not checkverifycode(request.POST,request.session):
                result["openid"] =  request.POST.get("openid")
                result["sceneid"] = request.POST.get("sceneid")
                result["result"] = "验证码不正确"
                ac_path = os.path.join(DEFAULT_DIR, "data.log")
                with open(ac_path, 'wb') as fp:
                    fp.write(json.dumps(result).encode("utf-8"))
                return result

            if checkRegInfo(request.POST):
                try:
                    request.session.clear()
                    mgr = UserManager(request.dbsession)
                    idname = request.POST.get("name")
                    pusername = request.POST.get("account")
                    mobile = request.POST.get("mobile")
                    organization = request.POST.get("organization")
                    ppassword = request.POST.get("password")
                    openid = request.POST.get("openid")
                    email = request.POST.get("email")
                    sceneid = request.POST.get("sceneid")

                    result["openid"] = openid
                    result["sceneid"] = sceneid


                    if(mgr.checkUserExist(pusername)):
                        result["result"] = "用户名已被注册"
                        return result

                    elif mgr.checkUserEmailExist(email):
                        result["result"] = "邮箱地址已被注册"
                        return result
                    elif mgr.checkUserMoblieExist(mobile):
                        result["result"] = "手机号码已被注册"
                        return result
                    else:
                        organizationaddress = request.POST.get("organizationaddress","")
                        level = request.POST.get("joblevel")
                        education = request.POST.get("education")
                        university = request.POST.get("university")
                        qq = request.POST.get("qq")

                        userReg = UserRegInfo()
                        user = User()
                        user.name = pusername
                        user.passwordMD5 = ppassword
                        user.token = ""
                        userReg.LoginUser = user
                        userReg.RealName = idname
                        userReg.MobilePhone = mobile
                        userReg.Organization = organization
                        userReg.OrgAddress = organizationaddress
                        userReg.Job = level
                        userReg.Education = education
                        userReg.University = university
                        userReg.QQ = qq
                        userReg.Email = email
                        userReg.RegistTime = datetime.now()
                        mgr.addUser(userReg)
                        html = \
                            '''
                            <html>
                            <head>
                            <title>SAUSAGE会员系统</title>
                            <meta http-equiv="Content-Language" content="zh-CN">
                            <meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
                            </head>
                            <body>
                            账号已成功注册
                            </body>
                            </html>
                            '''
                        if not openid:
                            html = \
                                '''
                                <html>
                                <head>
                                <title>SAUSAGE会员系统</title>
                                <meta http-equiv="Content-Language" content="zh-CN">
                                <meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
                                <meta http-equiv="refresh" content="3;url=%s">
                                </head>
                                <body>
                                账号已成功注册，3秒后跳转到登录页
                                </body>
                                </html>
                                ''' % ("./login?account=%s&openid=%s&sceneid=%s"%(pusername,openid,sceneid))

                        return Response(html, headers=headers)
                except Exception as ex:
                    print(ex)
                    result["result"] = "system error: save db data fail."
                    return result
            else:
                return {"openid": request.POST.get("openid",""),"sceneid":request.POST.get("sceneid",""), "result": "data error: some data required."}

        elif request.method == "GET" and request.GET != None:
            openid = getvalus(request.POST, "openid")
            sceneid =  getvalus(request.POST, "sceneid")
            return {"openid": openid, "sceneid":sceneid, "result": ""}

    except DBAPIError:
        return Response("server error", content_type='text/plain', status=500)
    result["result"] = "验证码或参数不正确"
    return result
