# -*- coding: utf-8 -*-
from odoo import models, fields, api


class JdBaseIrRuleCreator(models.Model):
    TMPL = u'''
<record id="rule_%(rule_id)s_company" model="ir.rule">
    <field name="name">%(name)s</field>
    <field name="model_id" ref="model_%(model_name)s"/>
    <field name="global" eval="%(global)s"/>
    <field name="perm_unlink" eval="%(unlink)d"/>
    <field name="perm_write" eval="%(write)d"/>
    <field name="perm_read" eval="%(read)d"/>
    <field name="perm_create" eval="%(create)d"/>
    <field name="domain_force">%(rule)s</field>
</record>    
    '''
    _name = 'jd.base.ir.rule.creator'
    _description = u'创建ir rule'
    module_id = fields.Many2one('ir.module.module', string=u'模块', required=True)
    ir_rule_ids = fields.One2many('rule.creator.line', 'creator_id', string=u'ir rule')
    can_read = fields.Boolean(string=u'读', required=True, default=True)
    can_write = fields.Boolean(string=u'写', required=True, default=False)
    can_create = fields.Boolean(string=u'增', required=True, default=False)
    can_delete = fields.Boolean(string=u'删', required=True, default=False)
    content = fields.Text(u'内容')

    @api.multi
    def on_create_xml(self):
        self.ensure_one()
        xml_list = []
        for rule in self.ir_rule_ids:
            if not rule.rule:
                continue
            model_name = rule.model_id.model
            desc = self.env[model_name]._description or model_name
            if rule.tail:
                desc = desc + u"-" + rule.tail
            has_group = len(rule.res_group_ids)
            val = {
                'rule_id': model_name.replace(".", "_"),
                'name': desc,
                'model_name': model_name.replace(".", "_"),
                'global': 'False' if has_group else 'True',
                'unlink': 1 if rule.can_delete else 0,
                'write': 1 if rule.can_write else 0,
                'read': 1 if rule.can_read else 0,
                'create': 1 if rule.can_create else 0,
                'rule': rule.rule
            }
            xml = self.TMPL % val
            xml_list.append(xml)
        self.content = "\r\n".join(xml_list)
        return {
            'type': 'ir.actions.act_url',
            'url': '/sys/utils/creator/ir_rule?creator_id=%d' % self.id,
            'target': 'new',
        }

    @api.multi
    @api.onchange('can_read', 'can_write', 'can_create', 'can_delete')
    def onchange_operate(self):
        self.ensure_one()
        for l in self.ir_rule_ids:
            l.can_read = self.can_read
            l.can_write = self.can_write
            l.can_create = self.can_create
            l.can_delete = self.can_delete

    @api.multi
    @api.onchange('module_id')
    def onchange_module_id(self):
        self.ensure_one()
        if self.module_id:
            model_data_model = self.env['ir.model.data']
            ir_model_model = self.env['ir.model']
            model_list = model_data_model.search([('module', '=', self.module_id.name), ('model', '=', 'ir.model')])
            line_ids = []
            for m in model_list:
                ir_model = ir_model_model.browse(m.res_id)
                if ir_model.transient:  # 向导模型不做处理
                    continue
                rule = "['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]"
                if not self.env[ir_model.model]._fields.get('company_id', None):  # 没有company_id的，不做处理
                    rule = ''
                line_ids.append({
                    'model_id': ir_model.id,
                    'can_read': 1,
                    'can_write': 0,
                    'can_create': 0,
                    'can_delete': 0,
                    'rule': rule,
                    'tail': u'公司隔离'
                })
            self.ir_rule_ids = line_ids


class RuleCreatorLine(models.Model):
    _name = 'rule.creator.line'
    _description = u'ir rule creator line'
    creator_id = fields.Many2one('jd.base.ir.rule.creator', required=True)
    model_id = fields.Many2one('ir.model', string=u'模型', required=True)
    can_read = fields.Boolean(string=u'读', required=True, default=True)
    can_write = fields.Boolean(string=u'写', required=True, default=False)
    can_create = fields.Boolean(string=u'增', required=True, default=False)
    can_delete = fields.Boolean(string=u'删', required=True, default=False)
    rule = fields.Char(string=u'规则')
    tail = fields.Char(u'规则名后缀', help=u'增加到分组名字后面')
    res_group_ids = fields.Many2many('res.groups', 'rel_rule_creator_line_res_groups', 'left_id', 'right_id',
                                     string=u'分组')
