#coding=utf-8

import datetime
from datetime import timedelta

import traceback
import tablib

from openpyxl.utils.exceptions import InvalidFileException

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:
            if d.second > 0:
                retval = "%d小时%d分钟%d秒" % (d.hour, d.minute, d.second)
            else:
                retval = "%d小时%d分钟" % (d.hour, d.minute)
        else:
            if d.second > 0:
                retval = "%d小时%d秒" % (d.hour, d.second)
            else:
                retval = "%d小时" % (d.hour)
    else:
        if d.minute > 0:
            if d.second > 0:
                retval = "%d分钟%d秒" % (d.minute, d.second)
            else:
                retval = "%d分钟" % (d.minute)
        else:
            retval = "%d秒" % (d.second)
    return retval


def clean_datetime_range(data, fieldname):
    if data is not None and fieldname in data and data[fieldname] != '':
        t = data[fieldname].split(' - ')
        data = data.copy()
        data[fieldname+'_after'] = t[0]
        data[fieldname+'_before'] = t[1] + ' 23:59:59'
        data.pop(fieldname)
    return data


class ExcelImporter():
    @staticmethod
    def validity(file):
        status = {
            'success': True,
            'errors': '',
            'data': []
        }
        if file == None:
            status['success'] = False
            status['errors'] = u"请上传数据文件"
        else:
            try:
                data = tablib.import_set(file, format='xlsx').dict
                if len(data) == 0:
                    status['success'] = False
                    status['errors'] = u"上传的文件内没有发现数据"
                else:
                    status['data'] = data
            except InvalidFileException:
                status['success'] = False
                status['errors'] = u"请上传<strong>xlsx</strong>格式的数据文件，老版本的xls格式不被支持！"
            except Exception as e:
                traceback.print_exc()
                status['success'] = False
                status['errors'] = u"导入失败"
        return status
