# -*- encoding: utf-8 -*-
# 项目：JDG-
# 模块名称：
# 描述：
# Copyright 2018 JDG <www.yunside.com>
# Created by wxh (xianhuo.weng@yunside.com) at  2018/10/9 - 下午5:51

from odoo import api, fields, models, exceptions
from core.middleware.utils import random_get, encrypt_param
from odoo.tools import config
import werkzeug
import base64
from time import time


class Attachment(models.AbstractModel):
    _name = 'jd.int.attachment'
    _description = u'系统集成的附件工具'

    @api.model
    def make_url(self, res_model=None, res_id=None, attachment_ids=None, res_field=None, is_return_id=False,
                 is_timestamp=False, filename_field=None):

        url_list = []
        attachment_rec_list = []
        gateway_host = config.get('gateway_host', None)
        if not gateway_host and res_model and res_id:
            raise exceptions.MissingError(u'配置文件缺少gateway_host配置项')

        if not attachment_ids:
            domain = [('res_model', '=', res_model), ('res_id', '=', int(res_id))]
            if res_field:
                if type(res_field) == list:
                    domain.append(('res_field', 'in', res_field))
                else:
                    domain.append(('res_field', '=', res_field))
            else:
                # 此冗余的domain是为了规避('res_field', '=', False)过滤
                domain.append(('id', '>', 0))

            # 如果传入的res_field是数组，则按序返回url数组。
            if type(res_field) == list:
                attachment_rec = self.env['ir.attachment'].sudo().search(domain)
                for field in res_field:
                    # 如果有多个，则取当前关联附件的最新附件
                    target_rec = attachment_rec.filtered(lambda r: r.res_field == field).sorted(key=lambda r: r.write_date, reverse=True)
                    if not target_rec:
                        attachment_rec_list.append(None)
                    else:
                        # 每个field对应一个最新的附件
                        attachment_rec_list.append(target_rec[0])
            else:
                attachment_rec_list = self.env['ir.attachment'].sudo().search(domain, order='write_date desc') or [None]
        else:
            attachment_rec_list = self.env['ir.attachment'].sudo().browse(attachment_ids)

        current_attachment_ids = []
        for attachment_rec in attachment_rec_list:
            # 若当前附件为空则返回url默认值 空字符串
            if not attachment_rec:
                url_list.append('')
                current_attachment_ids.append(None)
                continue
                
            data_node_id = self.env['ir.config_parameter'].sudo().get_param('jadedragon.microapp.data.node.id')
            if not data_node_id:
                raise exceptions.MissingError(u'当前系统缺失节点id信息，删除失败。请联系系统管理员')
            data_node_id = int(data_node_id)

            current_attachment_ids.append(attachment_rec.id)
            param = {
                'attachment_id': attachment_rec.id, 'data_node_id': data_node_id,
            }
            
            if is_timestamp:
                param.update({'timestamp': time()})

            url = gateway_host + '/file/read?' + encrypt_param(param)
            # 是否添加文件文件名前缀
            if filename_field:
                res_model = attachment_rec.res_model
                res_id = attachment_rec.res_id
                res_field = attachment_rec.res_field
                filename = getattr(self.env[res_model].sudo().browse(res_id), filename_field, None)
                if not filename:
                    filename = self.env[res_model]._fields[res_field].string
                url = filename.replace(' ', '') + ',' + url
            url_list.append(url)
        if is_return_id:
            return url_list, current_attachment_ids
        else:
            return url_list
