# -*- coding: utf-8 -*-
# Copyright 2018 JDG <www.yunside.com>
# Created by summerrain <summerrain5445@gmail.com> at 2018/8/1

from odoo import models, fields, api
import os
import base64

class BaseDisk(models.Model):
    _name = 'jd.base.disk'
    _description = u'网盘管理'
    _order = 'id asc'

    image = fields.Binary(string=u'文件缩略图', readonly=True, compute='_get_image')
    name = fields.Char(string=u'文件名称', default='/', readonly=True)
    file = fields.Binary(string=u'文件内容', store=True, attachment=True)
    file_category = fields.Many2one('jd.base.disk.category', string=u'文件分类', required=True)
    file_size = fields.Char(string=u'文件大小', default='0', readonly=True, compute='_get_file_size', store=True)
    note = fields.Char(string=u'备注信息')

    @api.multi
    @api.depends('file')
    def _get_image(self):
        """
        不同文件类型使用不同图标 TODO: 支持更多类型和图标
        by Shengli
        :return:
        """
        for item in self:
            if item.file:
                abs_path = os.path.abspath('.')
                img_base_path = 'base/app_base/jd_base/static/src/img/'
                file_name = item.name
                if file_name.endswith('.xls') or file_name.endswith('.xlsx'):
                    img_path = os.path.join(abs_path, img_base_path, 'icon-xls-m.png')
                elif file_name.endswith('.doc') or file_name.endswith('.docx'):
                    img_path = os.path.join(abs_path, img_base_path, 'icon-doc-m.png')
                elif file_name.endswith('.ppt') or file_name.endswith('.pptx'):
                    img_path = os.path.join(abs_path, img_base_path, 'icon-ppt-m.png')
                elif file_name.endswith('.pdf'):
                    img_path = os.path.join(abs_path, img_base_path, 'icon-pdf-m.png')
                else:
                    img_path = os.path.join(abs_path, img_base_path, 'icon-default-m.png')
                with open(img_path, 'rb') as f:
                    item.image = base64.b64encode(f.read())


    @api.multi
    @api.depends('file')
    def _get_file_size(self):
        for item in self:
            if item.file:
                bin_data = item.file and item.file.decode('base64') or ''
                attachment_size = str(len(bin_data) / 1024) + 'KB'
                item.file_size = attachment_size


class BaseDiskCategory(models.Model):
    _name = 'jd.base.disk.category'
    _description = u'文件类型'
    _order = 'id asc'

    name = fields.Char(string=u'文件类型', required=True)
    description = fields.Char(string=u'类型描述')
