# coding:utf-8
from django.db import connection
from django.template.loader import render_to_string
from django.http import HttpResponseNotFound, HttpResponseServerError, HttpResponseForbidden, HttpResponseBadRequest 

from django.http import HttpResponse, HttpResponseRedirect, JsonResponse

from datacenter import settings
import os
import datetime
import pdfkit
import requests

# 执行django原始sql语句 并返回一个数组对象
def query_json(sql):
    # 获得一个游标(cursor)对象
    cursor = connection.cursor()
    cursor.execute(sql)
    rawData = cursor.fetchall()
    col_names = [desc[0] for desc in cursor.description]
    result = []
    for row in rawData:
        objDict = {}
        # 把每一行的数据遍历出来放到Dict中
        for index, value in enumerate(row):
            objDict[col_names[index]] = value
        result.append(objDict)
    return result


def get_label_json(label_code):
    tblName = "t" + str(label_code).strip(' ')[0:4]
    sql = "SELECT * FROM label." + tblName + f" WHERE code = '{label_code}' ORDER BY tm DESC"
    return query_json(sql)


# 根据标签号取label_id, 没有返回0
def get_label_id(label_code):
    try:
        tblName = "t" + str(label_code).strip(' ')[0:4]
        sql = "SELECT * FROM label." + tblName + f" WHERE code = '{label_code}' ORDER BY tm DESC"
        ret = query_json(sql)
        return int(ret[0]["id"]) if len(ret) > 0 else 0
    except Exception as e:
        raise e


# 根据标签号取label_pk_id, 没有返回0
def get_label_pk_id(label_code):
    try:
        tblName = "t" + str(label_code).strip(' ')[0:4]
        sql = "SELECT * FROM label." + tblName + f" WHERE code = '{label_code}' AND package_id NOT IN (3,4) ORDER BY tm DESC"
        ret = query_json(sql)
        return int(ret[0]["parent_id"]) if len(ret) > 0 else 0
    except Exception as e:
        raise e


def page_not_found(request, *args, **kwargs):
    return HttpResponseNotFound(render_to_string('utils/404.html', request=request))


def forbidden(request, *args, **kwargs):
    return HttpResponseForbidden(render_to_string('utils/403.html', request=request))


def server_error(request, *args, **kwargs):
    return HttpResponseServerError(render_to_string('utils/500.html', request=request))


def bad_request(request, *args, **kwargs):
    return HttpResponseBadRequest(render_to_string('utils/404.html', request=request))


def download_pdf(request,what='default'):
    res={'e':''}
    base_url = 'https://davis.china315net.com/'
    keys = ['bill_number', 'name']
    c_name= '重庆焱翕盛商贸有限公司'
    for k in keys:
       if k not in keys:
           res['e'] = _('缺少参数') + k
           return JsonResponse(res)
    url = request.GET.get('url','')
    name = request.GET.get('name','')
    name = url.split("?id=")[1]
    if url.split("/")[0] == 'banquet':
        act = 'banquet'
    elif url.split("/")[0] == 'sales':
        act = 'marketActivity'
    else:
        res['e'] = '请求资源不存在'
        return JsonResponse(res)
    rurl = os.path.join(base_url,url)
    
    dt = datetime.datetime.now()
    strhtml = requests.get(rurl, )
    if strhtml.status_code != 200:  # 网页正常访问
        res['e'] = '资源无法访问，请稍后再试！'
        return JsonResponse(res)
    options = {
        'page-size': 'Letter',
        'margin-top': '0.75in',
        'margin-right': '0.75in',
        'margin-bottom': '0.75in',
        'margin-left': '0.75in',
        'encoding': "UTF-8",
        'custom-header': [
            ('Accept-Encoding', 'gzip')
        ],
        'cookie': [
            ('cookie-name1', 'cookie-value1'),
            ('cookie-name2', 'cookie-value2'),
        ],
        'no-outline': None
    } 
    if act == 'banquet':
        t_name='banquet'
    else :
        t_name='marketActivity'
    p = settings.MEDIA_ROOT + '/' + c_name + '/pdf/'+act+'/'+name+'.pdf'
    if what == 'default':
        if not os.path.exists(p):
            #if what != 'update':
            try:
                pdfkit.from_url(rurl, p ,options=options, )
            except:
                pass
        if os.path.exists(p):
            #if what == 'update':
                #os.remove(p)
            try:
                pdfkit.from_url(rurl, p, options=options, )
            except:
                pass
            res = download_FileResponse(p , name+".pdf")
            #os.remove(p+'/'+ name)
            return res
        else:
            res['e'] = '网络错误，请稍后再试！'
            return JsonResponse(res)
    elif what == 'update':
        if not os.path.exists(p):
            try:
                pdfkit.from_url(rurl, p, options=options, )
            except:
                pass
            res['e']=''
        else:
            os.remove(p)
            try:
                pdfkit.from_url(rurl, p, options=options, )
            except:
                pass

        return JsonResponse(res)

def download_pdf1(request,):
    res={'e':''}
    base_url = 'https://davis.china315net.com/'
    keys = ['bill_number', 'name']
    c_name= '重庆焱翕盛商贸有限公司'
    for k in keys:
       if k not in keys:
           res['e'] = _('缺少参数') + k
           return JsonResponse(res)
    url = request.GET.get('url','')
    name = request.GET.get('name','')
    name = url.split("?id=")[1]
    if url.split("/")[0] == 'banquet':
        act = 'banquet'
    elif url.split("/")[0] == 'sales':
        act = 'marketActivity'
    else:
        res['e'] = '请求资源不存在'
        return JsonResponse(res)
    rurl = os.path.join(base_url,url)
    
    dt = datetime.datetime.now()
    strhtml = requests.get(rurl, )
    if strhtml.status_code != 200:  # 网页正常访问
        res['e'] = '资源无法访问，请稍后再试！'
        return JsonResponse(res)
    options = {
        'page-size': 'Letter',
        'margin-top': '0.75in',
        'margin-right': '0.75in',
        'margin-bottom': '0.75in',
        'margin-left': '0.75in',
        'encoding': "UTF-8",
        'custom-header': [
            ('Accept-Encoding', 'gzip')
        ],
        'cookie': [
            ('cookie-name1', 'cookie-value1'),
            ('cookie-name2', 'cookie-value2'),
        ],
        'no-outline': None
    } 
    if act == 'banquet':
        t_name='banquet'
    else :
        t_name='marketActivity'
    p = settings.MEDIA_ROOT + '/' + c_name + '/pdf/'+act+'/'+name+'.pdf'

    if not os.path.exists(p):
        #if what != 'update':
        try:
            pdfkit.from_url(rurl, p ,options=options, )
        except:
            pass
    if os.path.exists(p):
        #if what == 'update':
            #os.remove(p)
        try:
            pdfkit.from_url(rurl, p, options=options, )
        except:
            pass
        res = download_FileResponse(p , name+".pdf")
        #os.remove(p+'/'+ name)
        return res
    else:
        res['e'] = '网络错误，请稍后再试！'
        return JsonResponse(res)
    
        
def download_HttpResponse(filepath,name):
    """
        HttpResponse方式文件下载
    :return:
    """
    file = open(filepath,'rb')
    res = HttpResponse(file)
    res['Content-Type'] = 'application/octet-stream'
    res['Content-Disposition'] = 'attachment;filename="'+name+'"'
    return res

from django.http import StreamingHttpResponse
def download_StreamingHttpResponse(filepath,name):
    """
        StreamingHttpResponse方式文件下载
    :return:
    """
    file = open(filepath,'rb')
    res =StreamingHttpResponse(file)
    res['Content-Type']='application/octet-stream'
    res['Content-Disposition']= 'attachment;filename="'+name+'"'
    return res

from django.http import FileResponse
def download_FileResponse(filepath,name):
    """
        FileResponse方式文件下载
    :return:
    """
    file=open(filepath,'rb')
    res =FileResponse(file)
    res['Content-Type']='application/octet-stream'
    res['Content-Disposition']= 'attachment;filename="'+name+'"'
    return res