#coding=utf-8

import datetime
import time
import hashlib
import math
import os
import sys
from datetime import timedelta
from calendar import monthrange

from django.conf import settings
from django.http import HttpResponse
from PIL import Image

def calc_sha1(file):
    sha1obj = hashlib.sha1()
    sha1obj.update(file)
    hash = sha1obj.hexdigest()
    return hash

def calc_md5(file):
    md5obj = hashlib.md5()
    md5obj.update(file)
    hash = md5obj.hexdigest()
    return hash

def get_page_info(request):
    try:
        page_index = int(request.GET.get('page')) - 1
    except:
        page_index = 0
    if page_index < 0: page_index = 0
        
    try:
        page_size = int(request.GET.get("limit"))
    except:
        page_size = settings.PAGE_SIZE

    return page_index,page_size

def get_page_data(request, rows):
    page_index,page_size = get_page_info(request)

    if page_index < 0 :
        page_index = 0
    begin = page_index * page_size
    end = (page_index + 1) * page_size
    return rows[begin:end], rows.count()

def strfdate(d):
    if d:
        return d.strftime('%Y-%m-%d')
    else:
        return ''

def strftime(t):
    if t:
        return t.strftime('%Y-%m-%d %H:%M')
    else:
        return ''

def strfsecond(second):
    sec = timedelta(seconds=second)
    d = datetime.datetime(1,1,1) + sec
    if d.hour > 0:
        if d.minute > 0:
            retval = "%d小时%d分钟" % (d.hour, d.minute)
        else:
            retval = "%d小时" % (d.hour)
    else:
        retval = "%d分钟" % (d.minute)
    return retval

def dump_form_errors(form):
    result = []
    for i in range(0, len(form.errors.keys())):
        name = form.errors.keys()[i]
        if name == '__all__':
            err = form.errors.values()[i][0]
        else:
            label = form.fields.get(name).label
            if label:
                label += ' - '
            else:
                label = ''
            err = label + ','.join(form.errors.values()[i])
        result.append(err)
    return '<br>'.join(result)

def read_file(fn, buf_size=262144):
    f = open(fn, "rb")
    while True:
        c = f.read(buf_size)
        if c:
            yield c
        else:
            break
    f.close()

def number2CNY(nin=None):
    def IIf( b, s1, s2):
        if b:
            return s1
        else:
            return s2

    cs =(u'零',u'壹',u'贰',u'叁',u'肆',u'伍',u'陆',u'柒',u'捌',u'玖',u'◇',u'分',u'角',u'圆',u'拾',u'佰',u'仟',u'万',u'拾',u'佰',u'仟',u'亿',u'拾',u'佰',u'仟',u'万')
    st = ''
    st1=''
    s = '%0.2f' % (nin)
    sln =len(s)
    if sln > 15:
        return None

    fg = (nin<1)
    for i in range(0, sln-3):
        ns = ord(s[sln-i-4]) - ord('0')
        st=IIf((ns==0)and(fg or (i==8)or(i==4)or(i==0)), '', cs[ns]) + IIf((ns==0)and((i<>8)and(i<>4)and(i<>0)or fg and(i==0)),'', cs[i+13]) + st
        fg = (ns==0)

    fg = False
    for i in [1,2]:
        ns = ord(s[sln-i]) - ord('0')
        st1 = IIf((ns==0)and((i==1)or(i==2)and(fg or (nin<1))), '', cs[ns]) + IIf((ns>0), cs[i+10], IIf((i==2) or fg, '', u'整')) + st1
        fg = (ns==0)
    st.replace(u'亿万',u'万')
    return IIf( nin==0, u'零', st + st1)

def add_month_interval(dt,inter):
    def _add_month_interval (dt,inter):
        m=dt.month+inter-1
        y=int(dt.year+math.floor(m/12))
        m=m % 12 +1
        return (y,m)

    y,m=_add_month_interval(dt,inter)
    y2,m2=_add_month_interval(dt,inter+1)
    maxD=( datetime.date(y2,m2,1)-datetime.timedelta(days=1) ).day
    d= dt.day<=maxD and dt.day or maxD
    return datetime.date(y,m,d)

def diff_month(d1, d2):
    return (d1.year - d2.year)*12 + d1.month - d2.month

def resize_image(filename, w):
    img = Image.open(filename).convert('RGB')
    wpercent = (w/float(img.size[0]))
    hsize = int((float(img.size[1])*float(wpercent)))
    img = img.resize((w,hsize), Image.ANTIALIAS)
    img.save(filename)

def attachment_response(export_data, filename='download.xls', content_type='application/vnd.ms-excel'):
    # Django 1.7 uses the content_type kwarg instead of mimetype
    try:
        response = HttpResponse(export_data, content_type=content_type)
    except TypeError:
        response = HttpResponse(export_data, mimetype=content_type)
    response['Content-Disposition'] = 'attachment; filename={}'.format(filename)
    return response

def attachment_save(export_data):
    # 删除过期文件
    now = int(time.time())
    files = os.listdir(settings.TMP_ROOT)
    for file in files:
        filePath = os.path.join(settings.TMP_ROOT, file)

        print filePath
        if os.path.isfile(filePath):
            last = int(os.stat(filePath).st_atime)
            if now - last > 180:
                os.remove(filePath)
                print(filePath + " was removed!")

    filename = '{}.xlsx'.format(now)
    full_filename = os.path.join(settings.TMP_ROOT, filename)
    open(full_filename, 'wb').write(getattr(export_data, 'xlsx'))
    return settings.TMP_URL + filename
