# -*- coding: utf-8 -*-
# 项目: jdg-core-base
# Copyright 2018 JDG <www.yunside.com>
# Created by HJH <jiahao.huang@yunside.com> at 2022/05/17

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

_logger = logging.getLogger(__name__)


class JdSystemLogConfig(models.Model):
    _name = 'jd.system.log.config'
    _inherit = 'jdg.abstract.base.data.m'
    _description = u'单据监控配置'

    name = fields.Char(string=u'名称', required=False)
    company_id = fields.Many2one('res.company', string=u'组织', required=False, default=False, readonly=True)
    line_ids = fields.One2many('jd.system.log.config.line', 'parent_id', string=u'监控明细', copy=True)

    @api.model
    def create(self, vals):
        number = vals.get('number', '/')
        if number == '/':
            number = self.env['ir.sequence'].next_by_code(self._name)
            vals.update({'number': number})
        return super(JdSystemLogConfig, self).create(vals)
    
    @api.multi
    def validation(self):
        for item in self:
            if not item.line_ids:
                raise ValidationError(u'未配置任何单据监控明细，请进行配置后再启用')
            cr = self.env.cr
            sql = """
              SELECT
                number
              FROM jd_system_log_config
              WHERE state = 'enable'
                AND id != %s
              LIMIT 1;
            """
            cr.execute(sql, (item.id,))
            rec = cr.dictfetchone()
            if rec and rec.get('number'):
                raise ValidationError(u'已存在状态为【启用】的单据监控配置【%s】，请停用该配置后重试' % rec['number'])
    
    @api.multi
    def do_enable(self):
        for item in self:
            item.validation()
        super(JdSystemLogConfig, self).do_enable()


class JdSystemLogConfigLine(models.Model):
    _name = 'jd.system.log.config.line'
    _description = u'单据监控配置明细'

    parent_id = fields.Many2one('jd.system.log.config', string=u'单据监控配置')
    model_id = fields.Many2one('ir.model', string=u'单据', required=True)
    mon_create = fields.Boolean(string=u'创建')
    mon_write = fields.Boolean(string=u'修改')
    mon_write_field_ids = fields.Many2many('ir.model.fields', 'rel_log_write_model_fields', 'config_line_id', 'field_id', string=u'修改字段')
    mon_audit = fields.Boolean(string=u'审核')
    mon_unaudit = fields.Boolean(string=u'反审核')
    mon_cancel = fields.Boolean(string=u'作废')
    mon_unlink = fields.Boolean(string=u'删除')

    # domain 控制字段
    domain_model_id = fields.Char(string=u'单据domain', default=json.dumps([('id', 'in', [0])]), compute='_get_model_domain')
    domain_field_id = fields.Char(string=u'修改字段domain', default=json.dumps([('id', 'in', [0])]), compute='_get_fields_domain')

    @api.multi
    @api.depends('model_id')
    def _get_model_domain(self):
        for item in self:
            model_ids = [0]
            cr = self.env.cr
            sql = """
              SELECT
                array_agg(im.id)  AS ids
              FROM (
                SELECT
                  DISTINCT
                  im.id
                FROM (
                  SELECT
                    id,
                    split_part(action, ',', 2) :: INTEGER AS action_id
                  FROM ir_ui_menu
                  WHERE split_part(action, ',', 1) = 'ir.actions.act_window'
                ) ium
                  INNER JOIN ir_act_window iaw ON iaw.id = ium.action_id
                  INNER JOIN ir_model im ON im.model = iaw.res_model
                WHERE im.transient = FALSE
              ) im
            """
            cr.execute(sql)
            rec = cr.dictfetchone()
            if rec and rec.get('ids'):
                model_ids = rec['ids']
            item.domain_model_id = json.dumps([('id', 'in', model_ids)])

    @api.multi
    @api.depends('model_id', 'mon_write_field_ids')
    def _get_fields_domain(self):
        for item in self:
            fields_ids = [0]
            if item.model_id:
                cr = self.env.cr
                sql = """
                  SELECT
                    array_agg(id) AS ids
                  FROM ir_model_fields
                  WHERE model_id = %s
                """
                cr.execute(sql, (item.model_id.id, ))
                rec = cr.dictfetchone()
                if rec and rec.get('ids'):
                    fields_ids = rec['ids']
            item.domain_field_id = json.dumps([('id', 'in', fields_ids)])
    
    @api.multi
    @api.onchange('mon_write', 'model_id')
    def onchange_mon_write(self):
        for item in self:
            item.mon_write_field_ids = [(6, 0, [])]


class JdModelFields(models.Model):
    _inherit = 'ir.model.fields'

    @api.multi
    def name_get(self):
        res = []
        for field in self:
            res.append((field.id, '%s' % field.field_description))
        return res
