#!/usr/bin/env python
# -*- coding:utf-8 -*-

import datetime, os
import hashlib

class UploadFile:
    '''
    USE METHOD:
            from app import static_path
            # static_path==filePath--> '/opt/code/...'

            article_little_img = self.request.files["article_little_img"][0]
            UploadFile(article_little_img, static_path)
    '''

    def __init__(self, fileobj, static_path):
        '''

        :param fileobj:
        :param static_path:
        '''
        self.fileobj = fileobj
        self.static_path = static_path
        self.md5 = None
        self.size = None
        self.saveFile(self.fileobj)

    def getFullName(self, fileobj):
        return fileobj['filename']

    def getFilePath(self):
        # 获取文件完整路径
        rootPath = self.static_path  # app里面总路径
        filePath = datetime.datetime.now().strftime("%Y%m%d")
        # for path in []:
        #     filePath = os.path.join(filePath, path)
        # return os.path.join(rootPath, 'admin', 'upload', 'img', filePath)
        return rootPath
    def saveFile(self, fileobj):
        self.fullName = self.getFullName(fileobj)
        self.filePath = self.getFilePath()

        # 检查路径是否存在，不存在则创建
        if not os.path.exists(self.filePath):
            os.makedirs(self.filePath)
        self.filePathName = os.path.join(self.filePath, self.fullName)
        md5_value = hashlib.md5()
        with open(self.filePathName, 'wb') as fp:
            fp.write(fileobj['body'])
        md5_value.update(fileobj['body'])
        self.md5 = md5_value.hexdigest()
        self.size = len(fileobj['body'])

    def getFileInfo(self):
        '''

        :return:
        '''
        # 获取当前上传成功文件的各项信息
        '''
        # 注意替换 static路径 --> 用总路径替换static_path 得到后面路径,然后. http://192.168.2.137:8888/ + sub_filepathname
        self.filePathName = '/opt/code/zzz/static/upload/img/123/123.png'
        static_path = '/opt/code/zzz/'
        url = http://192.168.2.137:8888/ + sub_filepathname
        '''
        return {
            'state': 1,
            'url': '',
            'title': '',
            'type': self.fullName.split('.')[0],
            'size': self.size,
            'md5': self.md5,
            'fileName': self.fullName,
            'filePath': self.filePath,
            'filePathName': self.filePathName,
            'fileDate': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        }