from django.http import HttpResponseRedirect, JsonResponse
from django.conf import settings
from django.db import connection
from utils.views import encrypt_p
from django.views.decorators.csrf import csrf_exempt
from .views import get_wx_access_token

import requests
import json
import datetime
import binascii

WX = settings.WX
WX_TJ = settings.WX_TJFW
WX_CK_UID = settings.TJ_CK_UID


# 微信公众号
# 连接微信服务器，准备换取CODE
def wx_tjfw_base_oauth(request, company_id, backurl):
    scope = 'snsapi_base'
    url = WX_TJ['oauth_direct_url_prefix'] + 'https://' + \
        request.get_host()+'/wxauth/tjfw/info/'+company_id+'/?scope='+scope

    param = {
        'backurl': backurl
    }
    state = json.dumps(param)
    state = binascii.hexlify(state.encode('utf8')).decode('utf-8')

    url = WX['url_oauth'].format(
        state=state,
        response_type='code',
        scope=scope,
        appid=WX_TJ['app_id'],
        redirect_url=url
    )
    return HttpResponseRedirect(url)


# 与微信服务器连接中，用CODE交换OPENID等相关信息
def wx_tjfw_base_oauth_info(request, company_id):
    data = {
        'e': ''
    }
    code = request.GET.get("code", '')
    state = binascii.unhexlify(request.GET.get('state')).decode('utf8')
    state = json.loads(state)

    if not code:
        data['e'] = 'code not found'
        return JsonResponse(data, safe=False)

    r = requests.get(WX['url_oauth_access_token'].format(
        WX_TJ['app_id'], WX_TJ['app_secret'], code))
    r = json.loads(r.content.decode("utf-8"))

    access_token = r['access_token']
    openid = r['openid']
    if not access_token or not openid:
        data['e'] = 'access_token or openid not found'
        return JsonResponse(data, safe=False)
    cur = connection.cursor()
    cur.execute("select id from sales_tjfwaccount where wx_openid='"+openid+"'")
    r = cur.fetchone()
    if r:
        tjfw_acct_id = str(r[0])
    else:
        cur.execute(
            "insert into sales_tjfwaccount(wx_openid) values ('"+openid+"') returning id")
        r = cur.fetchone()
        tjfw_acct_id = str(r[0])
    cur.close()

    state['tjfw_acct_id'] = tjfw_acct_id
    state = json.dumps(state)
    state = binascii.hexlify(state.encode('utf8')).decode('utf-8')

    url = "https://"+request.get_host()+'/wxauth/company/' + \
        company_id+'/?state='+state

    response = HttpResponseRedirect(url)
    return response


# 微信公众号
# 连接微信服务器，准备换取CODE
def wx_oauth(request, company_id):
    scope = 'snsapi_userinfo'
    cur = connection.cursor()
    s = "select wx_appid,wx_appsecret,id from sales_wxofficialaccounts where id=" +\
        "(select case when exists(select id from company_companycfg where company_id="+str(company_id)+" and tjfw_oauth=1)" +\
        " then 6 else (select id from sales_wxofficialaccounts where company_id=" + \
        str(company_id)+") end)"
    cur.execute(s)
    r = cur.fetchone()
    if r:
        appid = r[0]
    else:
        return JsonResponse({'e': '无授权数据'}, safe=False)
    cur.close()

    url = "https://"+request.get_host()+'/wxauth/company/info/' + \
        company_id+'/?wx_scope='+scope
    if appid == 'wx59969257ee0275da':
        url = WX_TJ['oauth_direct_url_prefix'] + url
    state = request.GET.get('state', '')
    url = WX['url_oauth'].format(
        state=state,
        response_type='code',
        scope=scope,
        appid=appid,
        redirect_url=url
    )
    return HttpResponseRedirect(url)


# 微信公众号
# 与微信服务器连接中，用CODE交换OPENID等相关信息
def wx_oauth_info(request, company_id):
    data = {
        'e': ''
    }

    code = request.GET.get("code", '')

    state = binascii.unhexlify(request.GET.get('state')).decode('utf8')
    param = json.loads(state)
    tjfw_acct_id = param['tjfw_acct_id']
    backurl = param['backurl']

    wxgz = 0
    wxgzurl = ''
    cur = connection.cursor()
    cur.execute(
        "select wx_appid,wx_appsecret,id,wxgz,wxgzurl from sales_wxofficialaccounts where company_id="+company_id)
    rs = cur.fetchall()
    if rs:
        r = rs[0]
        appid = r[0]
        secret = r[1]
        wx_official_account_id = str(r[2])
        wxgz = r[3]
        wxgzurl = r[4]
    else:
        appid = WX_TJ['app_id']
        secret = WX_TJ['app_secret']
        wx_official_account_id = WX_TJ['wx_official_account_id']

    r = requests.get(WX['url_oauth_access_token'].format(appid, secret, code))
    r = json.loads(r.content.decode("utf-8"))
    access_token = r['access_token']
    openid = r['openid']
    if not access_token or not openid:
        data['e'] = 'access_token or openid not found'
        return JsonResponse(data, safe=False)
        
    subscribe=0
    if wxgz:
        js_token=get_wx_access_token(wx_official_account_id)
        if js_token['e'] == '':
            js_token = js_token['token']
            rs=requests.get(WX['url_cgibin_userinfo'].format(js_token,openid))
            rs=json.loads(rs.content.decode("utf-8"))
            if not 'errcode' in rs:
                subscribe = rs['subscribe']
                if subscribe == 0 and wxgzurl:
                    return HttpResponseRedirect(wxgzurl)
                    
    user_url = "https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh-CN"
    d = requests.get(user_url.format(access_token, openid))
    d = d.content.decode("utf-8")
    if not d:
        data['e'] = 'get wechat user info failed'
        return JsonResponse(data, safe=False)
    d = json.loads(d)
    if 'errcode' in d:
        data['e'] = 'get user info err,code:'+d['errcode']
        return JsonResponse(data, safe=False)
    nickname = d['nickname'].replace("'", "")
    sex = str(d['sex'])
    headimgurl = d['headimgurl']
    province = d['province'].replace("'", "")
    city = d['city'].replace("'", "")
    language = d['language']
    s = "select id from sales_consumeraccount where wx_openid='" + \
        openid+"' and wx_account_id="+wx_official_account_id
    cur.execute(s)
    r = cur.fetchone()
    consumer_id = ''
    if r:
        consumer_id = str(r[0])
        s = f"""update sales_consumeraccount set 
                    wx_nickname = '{nickname}',
                    wx_headimgurl = '{headimgurl}',
                    gender = {sex},
                    wx_province = '{province}',
                    wx_city = '{city}',
                    wx_language = '{language}'  
                where id = {consumer_id}
            """
        cur.execute(s)
    else:
        s = "insert into sales_consumeraccount(" +\
            "wx_openid,wx_nickname,wx_headimgurl,wx_province,gender," +\
            "wx_city,wx_language,wx_account_id,tjfwacct_id" +\
            ") values ('" +\
            openid+"','"+nickname+"','"+headimgurl+"','"+province+"',"+sex+",'" +\
            city+"','"+language+"',"+wx_official_account_id+","+tjfw_acct_id +\
            ") returning id"
        cur.execute(s)
        r = cur.fetchone()
        consumer_id = str(r[0])
    cur.close()

    response = HttpResponseRedirect(backurl)

    response.set_cookie(WX_CK_UID+'_'+company_id+"_0", encrypt_p(str(
        consumer_id)), expires=datetime.datetime.now()+datetime.timedelta(days=7))
    response.set_cookie('TJWX_openid', encrypt_p(
        openid), expires=datetime.datetime.now()+datetime.timedelta(days=7))
    response.set_cookie("TJWX_consumer_id", str(
        consumer_id), expires=datetime.datetime.now()+datetime.timedelta(days=7))
    return response


# 获取授权链接
@csrf_exempt    
def get_wx_oauth_url(request):
    data={
        'e':''
    }
    company_id = request.GET.get('company_id','')
    back_url = request.GET.get('back_url','')
    app_id = request.GET.get('app_id','0')
    if company_id and back_url:
        scope = 'snsapi_base'
        url = WX_TJ['oauth_direct_url_prefix'] + 'https://' + \
            request.get_host()+'/wxauth/tjfw/info/'+company_id+'/?scope='+scope

        param = {
            'backurl': back_url
        }
        state = json.dumps(param)
        state = binascii.hexlify(state.encode('utf8')).decode('utf-8')

        url = WX['url_oauth'].format(
            state=state,
            response_type='code',
            scope=scope,
            appid=WX_TJ['app_id'],
            redirect_url=url
        )
        data['url'] = url
    else:
        data['e'] = '数据丢失'
    return JsonResponse(data)
