# -*- coding: utf-8 -*-
# Copyright 2018 JDG <www.yunside.com>
# Create by Carmen <carmen.ling@yunside.com> at 2018/5/17

from odoo import models, fields, api
from odoo.osv import expression
from odoo.exceptions import ValidationError
import core.middleware.utils as utils

STATE = [('draft', u'新建'), ('enable', u'启用'), ('disable', u'停用'), ('discard', u'废弃')]


class AbstractBaseDataMaster(models.AbstractModel):
    """
    主数据基类
    """

    _name = 'jdg.abstract.base.data.m'
    _inherit = 'jdg.abstract.base.data'
    _description = u"主数据基类"
    _order = 'number'

    state = fields.Selection(STATE, string=u'状态', default='draft', help=u'控制数据是否有效')
    time_enable = fields.Datetime(string=u'启用时间', readonly=True, help=u'由启用动作自动反写')
    time_disable = fields.Datetime(string=u'停用时间', readonly=True, help=u'由停用动作自动反写')
    time_discard = fields.Datetime(string=u'废弃时间', readonly=True, help=u'由废弃动作自动反写')

    uid_enable = fields.Many2one('res.users', string='启用者', readonly=True, help=u'由启用动作自动反写')
    uid_disable = fields.Many2one('res.users', string='停用者', readonly=True, help=u'由停用动作自动反写')
    uid_discard = fields.Many2one('res.users', string='废弃者', readonly=True, help=u'由废弃动作自动反写')

    @api.multi
    def do_enable(self):
        """
        启用主数据，修改数据状态，当有业务逻辑需要添加在子类中覆盖该方法时注意逻辑完整
        :return:
        """
        for record in self:
            # 检查是否有启用权限
            self.check_access_rights('audit')
            if record.state in ('draft', 'disable'):
                return record.with_context(force_company=record.company_id.id).jdg_sudo().write({
                    'state': 'enable',
                    'uid_enable': self.env.user.id,
                    'time_enable': fields.Datetime.now()
                })
            else:
                raise ValidationError('只有新建与停用状态下的数据才能启用')

    @api.multi
    @api.depends('state')
    def get_hide_edit_button(self):
        """
        编辑按钮可见性：根据状态控制编辑按钮可见性。子类中可以覆盖该方法添加更详细的控制条件。
        :return:
        """
        for each in self:
            each.hide_edit_button = True if each.state != 'draft' else False

    @api.multi
    def do_disable(self):
        """
        停用数据，修改数据状态，当有业务逻辑需要添加在子类中覆盖该方法时注意逻辑完整
        :return:
        """
        for record in self:
            if record.state == 'enable':
                # 检查是否有停用权限
                self.check_access_rights('unaudit')
                record.with_context(force_company=record.company_id.id).jdg_sudo().write({
                    'state': 'disable',
                    'uid_disable': self.env.user.id,
                    'time_disable': fields.Datetime.now()
                })
                return True
            else:
                raise ValidationError('只有启用状态下的数据才能停用')

    @api.multi
    def do_discard(self):
        """
        废弃数据，修改数据状态，当有业务逻辑需要添加在子类中覆盖该方法时注意逻辑完整
        :return:
        """
        for record in self:
            if record.state in ('disable', 'draft'):
                # self.check_access_rights_button('cancel')
                record.with_context(force_company=record.company_id.id).jdg_sudo().write({
                    'state': 'discard',
                    'uid_discard': self.env.user.id,
                    'time_discard': fields.Datetime.now()
                })
                return True
            else:
                raise ValidationError('只有新建和停用状态下的数据才能废弃')

    @api.multi
    def unlink(self):
        """
        启用过的数据不允许删除
        :return:
        """
        if any(item.state != 'draft' for item in self):
            if utils.is_prod():
                raise ValidationError('启用过的基础数据不允许删除')
        return super(AbstractBaseDataMaster, self).unlink()

    @api.multi
    def toggle_active_master(self):
        """
        归档
        Inverse the value of the field ``active`` on the records in ``self``.
        :return:
        """
        for record in self:
            if record.state == 'discard':
                if not record.active:
                    record.active = not record.active
            else:
                raise ValidationError('只有处于废弃状态的资料才能归档！')

    # @api.model
    # def name_search(self, name='', args=None, operator='ilike', limit=100):
    #     """
    #     名称模糊搜索，排除废弃的数据。
    #     """
    #     args = args or []
    #     if name:
    #         domain = ['|', ('number', '=ilike', '%' + name + '%'), ('name', operator, name)]
    #         if operator in expression.NEGATIVE_TERM_OPERATORS:
    #             domain = ['&', '!'] + domain[1:]
    #             domain.append(('state', '!=', 'discard'))
    #         else:
    #             domain.append(('state', '!=', 'discard'))
    #     else:
    #         domain = [('state', '!=', 'discard')]
    #     records = self.search(domain + args, limit=limit)
    #     return records.name_get()
