#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    demeter web page
    name:upload.py
    author:rabin
"""
from __load__ import *
from datetime import *
import os
import uuid
from PIL import Image

class index_path(Load):
	"""
	@api {post} /upload 上传图片
	@apiVersion 1.0.0
	@apiName upload
	@apiGroup Common

	@apiParam {String} file 文件流名称

	@apiSuccess {Bool} status 状态
	@apiSuccess {String}   msg  描述
	@apiSuccess {Number}   code  状态码
	@apiSuccess {Object[]} data 返回数据
	@apiSuccess {String}   data.src  图片地址

	@apiErrorExample 操作成功
	{"status": 1, "msg": "操作成功", "code": 0, "data": {"src":"url"}}
	@apiErrorExample 操作失败
	{"status": 2, "msg": "\u64cd\u4f5c\u5931\u8d25", "code": 0, "data": {}}
	"""
 	@auth
	@Web.setting
	def post(self, *args, **kwargs):
		url = self.request.protocol + "://" + self.request.host
		file_metas = self.request.files["file"]
		type = self.input('type', 1)
		# print(file_metas)
		day = str(date.today())
		day = day.split('-')
		for meta in file_metas:
			#meta['filename']
			file_name =  str(uuid.uuid5(uuid.uuid1(), 'file'))
			file_path = day[0] + '/' + day[1] + '/' + day[2]
			file_path = File.mkdirs(os.path.join(Demeter.path, 'runtime','upload', file_path)) + '/' + Demeter.md5(file_name) + '.jpg'
			with open(file_path, 'wb') as up:
				up.write(meta['body'])

		if type:
			#裁图类型,暂时居中裁图
			file_path = self.crop(file_path)
		self.out('yes', {'src':url + file_path.replace(Demeter.path + 'runtime', '')})

	def crop(file):
		img = Image.open(file) #打开图片句柄    
		width = img.size[0]
		height = img.size[1]
		size = 0
		if width < height:
			size = width
		else:
			size = height
		#img.thumbnail((500, 500))
		left = width/4
		crop = img.crop((left, 0, size+left, size))
		file = file + '_crop_center.jpg'
		crop.save(file)
		return file