# -*- coding: utf-8 -*-
# Copyright 2018 JDG <www.yunside.com>
# Created by LLH <lianghua.liu@yunside.com> at 2019/8/19
"""
菜单表批量创建
"""

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

import logging
_logger = logging.getLogger(__name__)


class JdBaseWizardBatchCreateMenuConfig(models.TransientModel):
    _name = 'jd.base.wizard.batch.create.menu.config'
    _description = u'菜单表批量创建'

    menu_ids = fields.Many2many('ir.ui.menu', 'left_id', 'right_id',
                                string=u'菜单', domain=lambda self: self.get_menu_domain(), required=True)

    def get_menu_domain(self):
        """
        1、只允许选择叶子节点的菜单
        2、不允许选择已经创建过的菜单
        :return:
        """
        all_menu_ids = self.env['ir.ui.menu'].sudo().search([('child_id', '=', False)]).ids
        extra_menu_ids = []

        # 查询已有菜单表配置的menu_ids
        sql = """
            SELECT DISTINCT
              menu_id
            FROM jd_ir_ui_menu_config
        """
        cr = self.env.cr
        cr.execute(sql)
        extra_menu_data = cr.dictfetchall()
        if extra_menu_data:
            for data in extra_menu_data:
                extra_menu_ids.append(data['menu_id'])

        remain_menu_ids = set(all_menu_ids) - set(extra_menu_ids)
        return [('id', 'in', list(remain_menu_ids))]

    def do_confirm(self):
        """
        根据所选择的菜单，批量创建菜单表
        名称格式：menu_id._get_full_name + '-' + 权限项
        :return:
        """
        self.ensure_one()
        item = self[0]

        perm_dict = {'perm_read': '查看',
                     'perm_write': '编辑',
                     'perm_unlink': '删除',
                     'perm_create': '创建',
                     'perm_audit': '审核',
                     'perm_unaudit': '反审核',
                     'perm_confirm': '确认',
                     'perm_cancel': '作废',
                     'perm_export': '导出',
                     }

        for menu_id in item.menu_ids:

            menu_name = menu_id._get_full_name()

            for perm in perm_dict:
                self.env['jd.ir.ui.menu.config'].create({'menu_id': menu_id.id,
                                                         'name': menu_name + '-' + perm_dict[perm],
                                                         perm: True})
        return {
            'type': 'ir.actions.client',
            'tag': 'reload',
        }
