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

CSV_TEMPLATE = '''
id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
%s
'''


class JdBcAppModelAccessCreatorWizard(models.Model):
    _name = 'jd.bc.app.model.access.creator'
    _description = u'ModelAccessCreator'
    name = fields.Char(string=u'名称', index=True, required=True)
    module_id = fields.Many2one('ir.module.module',
                                string=u'模块',
                                required=False,
                                index=False)
    group_ids = fields.Many2many('res.groups',
                                 'ref_model_access_creator_group',
                                 'creator_id',
                                 'group_id',
                                 string=u'权限分组',
                                 required=False,
                                 index=False)
    access_ids = fields.One2many('jd.bc.app.access.line',
                                 'creator_id',
                                 string=u'模型权限')
    access_csv = fields.Text(u'Access Content')
    all_read = fields.Boolean(u'全部可读', default=True)
    all_write = fields.Boolean(u'全部可写', default=False)
    all_create = fields.Boolean(u'全部可增', default=False)
    all_delete = fields.Boolean(u'全部可删', default=False)

    @api.multi
    @api.onchange('module_id', 'group_ids')
    def on_change_module(self):
        model_data_model = self.env['ir.model.data']
        ir_model_model = self.env['ir.model']
        for each in self:
            access_ids = []
            if each.module_id.id and len(each.group_ids) > 0:
                model_list = model_data_model.search([('module', '=', each.module_id.name),
                                                      ('model', '=', 'ir.model')])
                for g in each.group_ids:
                    for m in model_list:
                        ir_model = ir_model_model.browse(m.res_id)
                        if ir_model.transient:  # 向导模型不做处理
                            continue
                        try:
                            # 代码里已经删除的模型,但数据库中还保留，也不做处理。
                            test_model = self.env[ir_model.model]
                        except:
                            continue
                        access_ids.append({
                            'group_id': g.id,
                            'model_id': m.res_id,
                            'model_name': m.name,
                            'can_read': True,
                            'can_write': True,
                            'can_create': True,
                            'can_delete': False
                        })

            each.access_ids = access_ids

    @api.onchange('all_read')
    def on_change_all_read(self):
        for each in self:
            for line in each.access_ids:
                line.can_read = each.all_read

    @api.onchange('all_write')
    def on_change_all_write(self):
        for each in self:
            for line in each.access_ids:
                line.can_write = each.all_write

    @api.onchange('all_create')
    def on_change_all_create(self):
        for each in self:
            for line in each.access_ids:
                line.can_create = each.all_create

    @api.onchange('all_delete')
    def on_change_all_delete(self):
        for each in self:
            for line in each.access_ids:
                line.can_delete = each.all_delete

    @api.multi
    def create_model_access_file(self):
        self.ensure_one()
        item = self[0]
        file_lines = []
        ir_model_data_model = self.env['ir.model.data']
        line_template = "%(id)s,%(name)s,%(model_id)s,%(group_id)s,%(read)d,%(write)d,%(create)d,%(unlink)d"
        for line in item.access_ids:
            model_name_list = [each_model.strip() for each_model in line.model_id.modules.split(",")]
            group_data = ir_model_data_model.search([('model', '=', 'res.groups'),
                                                     ('res_id', '=', line.group_id.id)])
            if len(group_data) == 0:
                continue
                # raise exceptions.ValidationError(
                #     u'在模块【%s】下，找不到分组【%s】对应的元数据。' % (line.model_id.modules, line.group_id.name))
            read = 1 if line.can_read else 0
            write = 1 if line.can_write else 0
            create = 1 if line.can_create else 0
            unlink = 1 if line.can_delete else 0
            operator = u''
            if read:
                operator += u'查'
            if write:
                operator += u'改'
            if create:
                operator += u'增'
            if unlink:
                operator += u'删'
            if not read and not write and not create and not unlink:
                continue
            file_lines.append(line_template % {
                'id': "%s_%d" % (line.model_name, line.group_id.id),
                'name': u'%s-%s-%s' % (line.group_id.name, line.model_id.name, operator),
                'model_id': "model_%s" % line.model_id.model.replace(".", "_"),
                'group_id': "%s.%s" % (group_data[0].module, group_data[0].name),
                'read': read,
                'write': write,
                'create': create,
                'unlink': unlink
            })
        item.access_csv = CSV_TEMPLATE % "\r\n".join(file_lines)
        return {
            'type': 'ir.actions.act_url',
            'url': '/sys/utils/creator/model_access?creator_id=%d' % item.id,
            'target': 'new',
        }


class JdBcAppModelAccessCreatorLine(models.Model):
    _name = 'jd.bc.app.access.line'
    _description = u'ModelAccessCreatorLine'
    creator_id = fields.Many2one('jd.bc.app.model.access.creator', string=u'ModelAccessCreator')
    group_id = fields.Many2one('res.groups',
                               string=u'分组',
                               required=False,
                               index=False)
    can_read = fields.Boolean(string=u'读',
                              required=False,
                              index=False,
                              default=True)
    can_write = fields.Boolean(string=u'写',
                               required=False,
                               index=False,
                               default=False)
    can_create = fields.Boolean(string=u'增',
                                required=False,
                                index=False,
                                default=False)
    can_delete = fields.Boolean(string=u'删',
                                required=False,
                                index=False,
                                default=False)
    model_name = fields.Char(string=u'外部标识')
    model_id = fields.Many2one('ir.model',
                               string=u'模型',
                               required=False,
                               index=False)
