# -*- coding: utf-8 -*-
# @File  : jd_unlock_apply.py
# Created by cx on 2020/7/20
# xuan.chen@yunside.com


from odoo import fields, api, models, exceptions
from odoo.exceptions import ValidationError
import json
from odoo.tools import config


class UnlockApply(models.Model):
    _name = 'jd.unlock.apply'
    _inherit = 'jdg.abstract.base.biz'
    _description = u'解锁申请单'
    _seq_prefix = 'UL'

    date = fields.Date(string=u'申请日期', default=fields.Date.context_today, index=True)
    date_start = fields.Date(string=u'开始日期', required=True)
    date_end = fields.Date(string=u'结束日期', required=True)
    model_ids = fields.Many2many('ir.model', 'rel_jd_unlock_apply_ir_model', 'left_id', 'right_id', string=u'单据范围')
    domain_model_ids = fields.Char(string=u'单据范围domain', compute='_get_domain_model_ids',
                                   default=json.dumps([('id', 'in', [0])]))

    @api.model
    def get_domain_model_ids(self):
        base_biz_class = self.env['jdg.abstract.base.biz'].__class__
        model_ids = []
        model_recs = self.env['ir.model'].sudo().search(
            [('model', 'not like', 'ir.'), ('model', 'not like', 'wizard.'), ('model', 'not like', 'abstract')])
        for rec in model_recs:
            if rec.model in self.env and issubclass(self.env[rec.model].__class__, base_biz_class):
                model_ids.append(rec.id)
        return model_ids

    @api.multi
    @api.depends('company_id')
    def _get_domain_model_ids(self):
        """
        只能选择继承了业务单据基类的模型
        :return:
        """
        for item in self:
            model_ids = item.get_domain_model_ids()
            if not model_ids:
                model_ids = [0]
            item.domain_model_ids = json.dumps([('id', 'in', model_ids)])

    @api.multi
    def select_model(self):
        """
        全选单据
        :return:
        """
        for item in self:
            item.model_ids = None
            model_ids = item.get_domain_model_ids()
            if model_ids:
                item.model_ids = [(6, 0, model_ids)]

    @api.multi
    def delete_model(self):
        for item in self:
            item.model_ids = None

    @api.multi
    def verify_data(self):
        for item in self:
            if not item.model_ids:
                raise ValidationError(u'请填写需锁定的单据')

    @api.multi
    def do_confirm(self):
        for item in self:
            item.verify_data()
        super(UnlockApply, self).do_confirm()

    @api.multi
    def do_audit(self):
        for item in self:
            item.verify_data()
        super(UnlockApply, self).do_audit()
