# -*- coding:utf-8 -*-
# 项目: jdg-core-base
# Copyright 2018 JDG <www.yunside.com>
# Created by bjccdsrlcr (longjie.jiang@yunside.com) @ 2018/11/4

from odoo import models, fields, api
from odoo.exceptions import ValidationError
import logging

_logger = logging.getLogger(__name__)

class IrUiMenuConfig(models.Model):
    _name = 'jd.ir.ui.menu.config'
    _description = u'菜单表'
    _order = 'create_date desc'
    """
    关联菜单，提供审核、反审核、确认、作废这4个通用按钮。
    其他特殊按钮通过many2many配置。
    """

    # _sql_constraints = [
    #     ('name_uniq', 'unique (name)', u'名字重复！')
    # ]

    menu_id = fields.Many2one('ir.ui.menu', string=u'菜单', ondelete='cascade',
                              domain=lambda self: self.get_menu_domain(), required=True)
    name = fields.Char(string=u'名称', required=True)
    perm_read = fields.Boolean(string=u'读', default=True, help=u'该群组对于该菜单是否有读权限')
    perm_write = fields.Boolean(string=u'编辑', default=False, help=u'该群组对于该菜单是否有编辑权限')
    perm_unlink = fields.Boolean(string=u'删除', default=False, help=u'该群组对于该菜单是否有删除权限')
    perm_create = fields.Boolean(string=u'创建', default=False, help=u'该群组对于该菜单是否有创建权限')
    perm_audit = fields.Boolean(string=u'审核/启用', default=False, help=u'该群组对于该菜单是否有审核权限')
    perm_unaudit = fields.Boolean(string=u'反审核/停用', default=False, help=u'该群组对于该菜单是否有反审核权限')
    perm_confirm = fields.Boolean(string=u'确认', default=False, help=u'该群组对于该菜单是否有确认权限')
    perm_cancel = fields.Boolean(string=u'作废', default=False, help=u'该群组对于该菜单是否有作废权限')
    perm_export = fields.Boolean(string=u'导出', default=False, help=u'该群组对于该菜单是否有导出权限')

    special_button_ids = fields.Many2many('jd.button',
                                          'jd_base_jd_acls_jd_button',
                                          'menu_config_id',
                                          'button_id',
                                          string=u'特殊按钮访问控制')
    
    @api.multi
    @api.constrains('name')
    def _check_name(self):
        for item in self:
            cr = self.env.cr
            sql = '''
            SELECT count(1)
            FROM jd_ir_ui_menu_config
            WHERE name = %(name)s
            '''
            params = {'name': item.name}
            if isinstance(item.id, int):
                sql += ''' AND id != %(record_id)s'''
                params.update({'record_id': item.id})
            cr.execute(sql, params)
            count = cr.fetchone()[0]
            if count:
                raise ValidationError(u'名称不能重复\r\n错误详情：\r\n'
                                      u'已存在名称为【%s】的菜单项配置' % item.name)

    def get_menu_domain(self):
        """
        只允许选择叶子节点的菜单
        :return:
        """
        all_menu_ids = self.env['ir.ui.menu'].sudo().search([('child_id', '=', False)])
        extra_menu_ids = []
        # for menu_id in all_menu_ids:
        #     extra_menu_ids.append(menu_id.id)
        all_menu_ids = all_menu_ids.ids
        remain_menu_ids = set(all_menu_ids) - set(extra_menu_ids)
        return [('id', 'in', list(remain_menu_ids))]

    @api.model
    def create(self, values):
        """
        获取自动单号
        :param values:
        :return:
        """
        return super(IrUiMenuConfig, self).create(values)

    @api.onchange('menu_id')
    def onchange_menu(self):
        for item in self:
            item.name = item.menu_id._get_full_name()

    @api.model
    def init_menu(self):
        all_menu_ids = self.env['ir.ui.menu'].sudo().search([('child_id', '=', False)])
        extra_menu_ids = []
        all_menu_ids = all_menu_ids.ids
        remain_menu_ids = set(all_menu_ids) - set(extra_menu_ids)
        for menu_id in remain_menu_ids:
            menu_id = self.env['ir.ui.menu'].browse(int(menu_id))
            name = menu_id._get_full_name()
            record_id = self.search([('name', '=', name)])
            if record_id:
                continue
            value = {
                'name': name,
                'menu_id': menu_id.id,
                'perm_read': True,
                'perm_write': True,
                'perm_unlink': True,
                'perm_create': True,
                'perm_audit': True,
                'perm_unaudit': True,
                'perm_confirm': True,
                'perm_cancel': True,
                'perm_export': True,
            }
            self.create(value)
