# -*- coding: utf-8 -*-
from odoo import models, fields, api
from odoo.exceptions import ValidationError
from odoo.osv import expression
from odoo import tools
import operator


class IrUiMenu(models.Model):
    _inherit = 'ir.ui.menu'

    complete_name = fields.Char(compute='_compute_complete_name', string='完整路径', store=True)

    @api.multi
    def get_needaction_data(self):
        """
        数据量大时候，加载会慢，暂时关闭
        # TODO
        """
        return dict([[id.id, {'needaction_enabled': False, 'needaction_counter': False}] for id in self])

    @api.model
    def hide_menu_by_group(self):
        '''
        只允许系统管理员看到系统菜单
        :return:
        '''
        menu_xml_ids = [
            {'name': '应用', 'xml_id': 'base.menu_module_tree', 'groups': ['base.group_no_one']},
            {'name': '应用', 'xml_id': 'base.menu_management', 'groups': ['base.group_no_one']},
        ]
        for menu in menu_xml_ids:
            # 根据XML_ID获取对象
            menu_id = self.env.ref(menu['xml_id'])
            vals = {'name': menu['name'],
                    'groups_id': [
                        (6, 0, [self.env.ref(g).id for g in menu['groups']])],
                    }
            menu_id.write(vals)


    # 取消web_icon_data放在缓存中
    @api.model
    @tools.ormcache_context('self._uid', keys=('lang',))
    def load_menus_root(self):
        fields = ['name', 'sequence', 'parent_id', 'action']
        menu_roots = self.get_user_roots()
        menu_roots_data = menu_roots.read(fields) if menu_roots else []
        return {
            'id': False,
            'name': 'root',
            'parent_id': [-1, ''],
            'children': menu_roots_data,
            'all_menu_ids': menu_roots.ids,
        }

    @api.model
    @tools.ormcache_context('self._uid', 'debug', keys=('lang',))
    def load_menus(self, debug):
        """ Loads all menu items (all applications and their sub-menus).

        :return: the menu root
        :rtype: dict('children': menu_nodes)
        """
        fields = ['name', 'sequence', 'parent_id', 'action', 'web_icon']
        menu_roots = self.get_user_roots()
        menu_roots_data = menu_roots.read(fields) if menu_roots else []
        menu_root = {
            'id': False,
            'name': 'root',
            'parent_id': [-1, ''],
            'children': menu_roots_data,
            'all_menu_ids': menu_roots.ids,
        }
        if not menu_roots_data:
            return menu_root

        # menus are loaded fully unlike a regular tree view, cause there are a
        # limited number of items (752 when all 6.1 addons are installed)
        menus = self.search([('id', 'child_of', menu_roots.ids)])
        menu_items = menus.read(fields)

        # add roots at the end of the sequence, so that they will overwrite
        # equivalent menu items from full menu read when put into id:item
        # mapping, resulting in children being correctly set on the roots.
        menu_items.extend(menu_roots_data)
        menu_root['all_menu_ids'] = menus.ids  # includes menu_roots!

        # make a tree using parent_id
        menu_items_map = {menu_item["id"]: menu_item for menu_item in menu_items}
        for menu_item in menu_items:
            parent = menu_item['parent_id'] and menu_item['parent_id'][0]
            if parent in menu_items_map:
                menu_items_map[parent].setdefault(
                    'children', []).append(menu_item)

        # sort by sequence a tree using parent_id
        for menu_item in menu_items:
            menu_item.setdefault('children', []).sort(key=operator.itemgetter('sequence'))

        return menu_root
