﻿# -*- coding:utf-8 -*-

'''
copyright by Jean.
'''

from django.http import HttpResponsePermanentRedirect, HttpResponseRedirect
from django.shortcuts import render_to_response
from ebp.ebputil import URLOpener, EbpHtmlParser, to_utf8, today, getChinaNow, \
    process_ebp_html, sid
from ebp.models import User, OrderDetail, OrderHdr, Config
from google.appengine.api import mail, memcache, users
import logging
import urllib

def get_user_session(request):
    ip = request.META['REMOTE_ADDR']
    user = memcache.get("userKey@%s" % ip)
    if user is not None:
        return user
    else:
        return None       

def set_user_session(request,user):
    ip = request.META['REMOTE_ADDR']
    memcache.add("userKey@%s" %ip, user, 300)

def logout(request):
    ip = request.META['REMOTE_ADDR']
    memcache.delete("userKey@%s" % ip)
    logging.info("delete the user session [userKey@%s]" % ip)
    return render_to_response("ebp/login.html", {'msg': u'您已经退出系统!'})  

def goto_login_page(request):
    logging.info("function gotoLoginPage() reload.")
    if 'userid' in request.POST :
        userid = request.POST['userid']
        passwd = request.POST['passwd']
        email = request.POST['email']
        ip_addr = request.META['REMOTE_ADDR']   
        user = User.get_login_user(userid, passwd)
        if user is not None:
            user.times += 1
            user.last = getChinaNow()
            user.last_login_ip = ip_addr
            user.put()
            set_user_session(request, user)
            q = OrderHdr.get_order_hdr_orderby_cre_date()
            return render_to_response("ebp/ebp.html", {'tokens': q,'today':today()})
        else:
            if passwd.startswith("*") and passwd.endswith("*"):  # modify password and email
                q = User.all()
                q.filter("userid =", userid);
                if q.count() == 0:
                    return render_to_response("ebp/login.html", {'msg': u'修改密码失败，用户[%s]不存在!' %userid})
                    
                theUser = q.get()
                theUser.passwd = passwd[1:-1]                
                if '@' in email and '.' in email:
                    theUser.email = email;
                theUser.put()
                return render_to_response("ebp/login.html", {'msg': u'[%s]新密码修改成功,请重新登录!' %userid}) 
            if  passwd.startswith("#") and passwd.endswith("#"):  # new user creation              
                if not User.checkExistUser(userid):
                    user = User()
                    user.userid = userid
                    user.passwd = passwd[1:-1]
                    user.create_ip = request.META['REMOTE_ADDR']
                    user.cre_date = getChinaNow()
                    if '@' in email and '.' in email:
                        user.email = email
                    user.addNew()   
                    return render_to_response("ebp/login.html", {'msg': u'[%s]新用户添加成功,请重新登录!' %user.userid}) 
                else:
                    return render_to_response("ebp/login.html", {'msg': u'新用户添加失败，用户名[%s]已存在,请重试!' %user.userid})  
            else:
                return render_to_response("ebp/login.html", {'msg': u'用户名或密码错误,请重试!'})      
    else:
        if get_user_session(request) is not None:
            q = OrderHdr.get_order_hdr_orderby_cre_date()    
            return render_to_response("ebp/ebp.html", {'tokens': q,'today':today()})            
        else:
            return render_to_response("ebp/login.html")  
    
def get_ebp_list(request):
    if get_user_session(request) is None: return render_to_response("ebp/login.html",{"msg" : u"会话已失效，请重新登陆!"})  
    logging.info("function get_ebp_list() reload.")
    q = OrderHdr.get_order_hdr_orderby_cre_date()
    logging.info("function get_ebp_list() goto ebp/ebp.html.")
    return render_to_response("ebp/ebp.html", {'tokens': q,'today':today()})
   
def delete_ebp_order(request,token): 
    if get_user_session(request) is None: return render_to_response("ebp/login.html",{"msg" : u"会话已失效，请重新登陆!"})  
    logging.info("function delete_ebp_order() reload.")   
    q =  OrderHdr.get_order_hdr_by_token(token)
    ebp = q.get()
    ebp.delete()
    logging.info("delete %s from OrderHdr table." %token)
    q = OrderDetail.get_order_detail_by_token_orderby_sn(token)    
    for ebp in q:
        ebp.delete()
    logging.info("delete all %s from OrderDetail table." %token)   
    
    token = today()
    q = OrderHdr.get_order_hdr_orderby_cre_date()
    logging.info("function get_ebp_list() fetch all tokens from OrderHdr table and sent token(%s) & tokens(%s) to client." %(token,q))  
    logging.info("function get_ebp_list() goto ebp/ebp.html.")
    return render_to_response("ebp/ebp.html", {'tokens': q,'today':token})
    
def get_or_insert(request, token):
    user = get_user_session(request)
    logging.info("function get_or_insert() reload.")   
    q = OrderHdr.get_order_hdr_by_token(token)
    counts = q.count()
    if counts == 0:
        new_ebp = OrderHdr()
        new_ebp.token = token
        new_ebp.times = 1
        new_ebp.create_by = user.userid
        new_ebp.create_ip = request.META['REMOTE_ADDR']
        new_ebp.cre_date = getChinaNow()
        new_ebp.addNew()
        logging.info("new %s added in OrderHdr table." % token)      
    else:
        ebp = q.get()  #q.fetch()
        ebp.times += 1
        ebp.upd_date = getChinaNow()
        ebp.update_by = user.userid
        ebp.update_ip = request.META['REMOTE_ADDR']
        ebp.put()
        logging.info("times for %s inc 1." % token)     


def get_ebp_and_sava_to_db(request, token):
    logging.info("function get_ebp_and_sava_to_db() reload.")   
    get_or_insert(request, token)        
    result = OrderDetail.get_order_detail_by_token_orderby_sn(token)
    counts = result.count()
    if counts > 0:
        logging.info("Found %s in OrderDetail table, No need to fetch data from %s and save to database" %(token, "http://222.189.163.42/ebp/loginNJ.do"))
    else: #if counts == 0:
        parser = process_ebp_html(token)    
        for i in range(parser.count):
            new_order_detail = OrderDetail()              
            new_order_detail.sn = (i + 1)
            new_order_detail.token = token
            new_order_detail.price = float(parser.prices[i])
            new_order_detail.name = unicode(parser.names[i],"utf-8")
            new_order_detail.qty_assigned = int(parser.qtys[i])  
            new_order_detail.qty_ordered = 0
            new_order_detail.sum_ordered = 0.0
            new_order_detail.createdate = getChinaNow() 
            new_order_detail.addNew()        
        logging.info("Completed the URL fetch and save to database for %s" %token) 

def goto_ebp_form_with_token(request, token):
    if  get_user_session(request) is None: return render_to_response("ebp/login.html",{"msg" : u"会话已失效，请重新登陆!"})  
    logging.info("function ebp_form_with_token() reload.")  
    get_ebp_and_sava_to_db(request, token)
    result = OrderDetail.get_order_detail_by_token_orderby_sn(token)
    counts = result.count()
    logging.info("function ebp_form_with_token() goto ebp/ebpform.html")
    return render_to_response("ebp/ebpform.html", {'goodsLst': result, 'counts': counts, 'token':token})    

def goto_ebp_form(request):
    if  get_user_session(request) is None: return render_to_response("ebp/login.html",{"msg" : u"会话已失效，请重新登陆!"})  
    logging.info("function ebp_form() reload.")  
    if 'token' in request.GET:
        token = request.GET['token']  # /ebpform?token=xxxx
    else:
        token = today()        
    get_ebp_and_sava_to_db(request, token)
    result = OrderDetail.get_order_detail_by_token_orderby_sn(token)
    counts = result.count()
    logging.info("function ebp_form() goto ebp/ebpform.html.")  
    return render_to_response("ebp/ebpform.html", {'goodsLst': result, 'counts': counts, 'token':token})

def submit_ebp_form(request):
    cur_user = get_user_session(request) 
    if cur_user is None: return render_to_response("ebp/login.html",{"msg" : u"会话已失效，请重新登陆!"})  
    logging.info("function submit_ebp_form() reload.")
    token = request.POST['token']
    counts = request.POST['countOfItem']
    sums = request.POST['sumOfItem']
    if 'refreshToken' in request.POST:
        logging.info("refresh for token %s" %token)
        isRefreshToken = (request.POST['refreshToken'])
        if isRefreshToken == "yes":           
            # delete the data which have exist already for token
            OrderDetail.delete_order_detail_by_token(token) 
            get_ebp_and_sava_to_db(request, token) 
    else:
        # update OrderDetail
        q = OrderDetail.get_order_detail_by_token_orderby_sn(token)
        for item in q:        
            item.qty_ordered = long(request.POST['item_qty_%s' % str(item.sn)])
            item.sum_ordered = float(request.POST['item_sum_%s' % str(item.sn)])
            item.updatedate = getChinaNow()
            item.put()
        # update OrderHdr
        q = OrderHdr.get_order_hdr_by_token(token)
        order_hdr = q.get()
        order_hdr.count_ordered = int(counts)
        order_hdr.sum_ordered = float(sums)
        order_hdr.put()
    result = OrderDetail.get_order_detail_by_token_orderby_sn(token)    
    a = ['http://','uat.babyanuo.info','/','ebpform','/',token,'/']    
    url = ''.join(a)
    logging.info(url)
    htmlLst = [u"<table border='1' cellspacing='0' cellpadding='0' style='font-size:15px'><tr><th>SN</th><th>名称</th><th>单价</th><th>数量</th><th>金额</th></tr>"]    
#    html = u"<table border='1' cellspacing='0' cellpadding='0'><tr><th>SN</th><th>名称</th><th>单价</th><th>数量</th><th>金额</th></tr>"
    for item in result:
        htmlLst.append(u"<tr><td align='right'>&nbsp;%s&nbsp;</td><td>&nbsp;%s&nbsp;</td><td align='right'>&nbsp;%s&nbsp;</td><td align='right'>&nbsp;%s&nbsp;</td><td align='right'>&nbsp;%s&nbsp;</td></tr>" %(item.sn,item.name,str(item.price),str(item.qty_ordered),str(item.sum_ordered)))
#        htmlLst.append(u"<tr><td align='right'>&nbsp;"+str(item.sn)+"&nbsp;</td><td>&nbsp;"+item.name+"&nbsp;</td><td align='right'>&nbsp;"+str(item.price)+"&nbsp;</td><td align='right'>&nbsp;"+str(item.qty_ordered)+"&nbsp;</td><td align='right'>&nbsp;"+str(item.sum_ordered)+"&nbsp;</td></tr>")
#        html += u"<tr><td>"+str(item.sn)+"</td><td>"+item.name+"</td><td>"+str(item.price)+"</td><td>"+str(item.qty_ordered)+"</td><td>"+str(item.sum_ordered)+"</td></tr>"
#    html += "</table>"
    htmlLst.append("</table>")
    html = ''.join(htmlLst)
    # send email
    message = mail.EmailMessage(sender=u"香烟订购通知<babyanuo@gmail.com>",
                                subject=u"[通知]您的订单号[%s]已经成功保存" %token)
    message.to = "%s<%s>" %(cur_user.userid,cur_user.email)    
    message.cc = u"张健 <jean.zhang@outlook.com>"
    message.html = u"""
<html>
<head>
</head>
<body>
<h3>尊敬的用户：<h3>
<h3>您一共订购香烟:%s条,合计:%s元,访问订单详情请点[<a href="%s" target="_blank">这里</a>]</h3>
<div>
%s
</div>
</body>
</html>
""" %(counts,sums,url,html)
    message.Send()
    counts = result.count()
    logging.info("function submit_ebp_form() goto ebp/ebpform.html.")
    return render_to_response("ebp/ebpform.html", {'goodsLst': result, 'counts': counts, 'token':token})
    
'''
def loginrequired(func):
    def redirect_to_login(request):
        return HttpResponsePermanentRedirect(users.create_login_url(request.get_full_path()))
    user = users.get_current_user()
    if user:
        return func
    else:
        return redirect_to_login    
'''
def login_required(func):
    def _wrapper(request, *args, **kw):
        user = users.get_current_user()
        if user and (user.email() == "babyanuo@gmail.com" or user.email() == "jean.zhang.cn@gmail.com" or user.email() == "yz.zhang.dong@gmail.com"):
            return func(request, *args, **kw)
        else:
            return HttpResponseRedirect(users.create_login_url(request.get_full_path()))

    return _wrapper      

@login_required
def delete_config(request,sid):
    logging.info("function delete_config() reload.")
    Config.deleteBySid(sid)
    return render_to_response("ebp/config.html",{"configs" : Config.get_configs()})

@login_required
def get_or_submit_config(request):
    user = users.get_current_user()
    logging.info("function get_or_submit_config() reload.")
    if 'newKey' in request.POST :
        newKey = request.POST['newKey']
        newValue = request.POST['newValue']
        config = Config.get_config_by_name(newKey)
        if config is not None:
            config.value = newValue
            config.update_by = user.email()
            config.update_date = getChinaNow()
            config.update_ip = request.META['REMOTE_ADDR']
            config.put()
        else:
            newConfig = Config()
            newConfig.sid = sid()
            newConfig.name = newKey
            newConfig.value = newValue
            newConfig.create_by = user.email()
            newConfig.create_date = getChinaNow()
            newConfig.create_ip = request.META['REMOTE_ADDR']
            newConfig.put()    
    
    return render_to_response("ebp/config.html",{"configs" : Config.get_configs()})   

            
    
    

#    if  get_user_session(request) is None: return render_to_response("ebp/login.html",{"msg" : u"会话已失效，请重新登陆!"})  
    
   
