# -*- coding: utf-8 -*-
# Copyright 2018 JDG <www.yunside.com>
# Create by Carmen <carmen.ling@yunside.com> at 2018/5/17
# Updated by YGJ <guojian.ye@yunside.com> at 2018/6/23
from odoo import models, fields, api
from odoo.osv import expression
from odoo.tools import config


class AbstractBaseDataConfig(models.AbstractModel):
    """
    基础数据设置基类
    """

    _name = 'jdg.abstract.base.data.config'
    _inherit = 'jdg.abstract.base.data'
    _description = u"基础数据设置基类"
    _order = 'number desc'
    _seq_prefix = ''

    date_start = fields.Date(string=u'生效日期', required=True)
    date_end = fields.Date(string=u'失效日期', required=True)
    uid_config = fields.Many2one('res.users', string=u'设置者', readonly=True)
    is_valid = fields.Boolean(string=u'是否生效', compute='_compute_date')

    @api.model
    def create_default_sequence(self):
        """
        创建ir_sequence记录, code组合为(self._name).company_id
        在单据创建记录前检查是否有该模型该公司的ir_sequence，如果没有则创建
        注意：当context中指定了force_company时，取sequence的逻辑以force_company而不是当前用户的company_id
        TODO：每次单据创建记录时都会查询可能存在性能消耗，优化后消耗较小，后期如有必要可将方案修改为每次创建company后就创建相关的ir_sequence
        :return: {object: ir_sequence}
        """
        force_company = self._context.get('force_company')
        if not force_company:
            force_company = self.env.user.company_id.id
        seq_code = str(self._name) + ('.%s' % force_company)
        seq_rec = self.env['ir.sequence'].search(['&', ('code', '=', seq_code), ('company_id', '=', force_company)])
        if not seq_rec:
            prefix = config.get('system_prefix', '').strip()
            if self._seq_prefix:
                prefix += str(self._seq_prefix)
            seq_val = {
                'name': seq_code,
                'code': seq_code,
                'prefix': prefix,
                'padding': 6,
                'company_id': force_company
            }
            seq_rec = self.env['ir.sequence'].sudo().create(seq_val)
        return seq_rec

    @api.model
    def create(self, values):
        """
        获取自动单号
        :param values:
        :return:
        """
        if values.get('number', '/') == '/':
            seq_rec = self.create_default_sequence()
            values.update({
                'number': seq_rec._next()
            })
        return super(AbstractBaseDataConfig, self).create(values)

    @api.multi
    @api.depends('date_start')
    def do_effect_now(self):
        """
        起效
        :return:
        """
        return self.jdg_sudo().write({
            'uid_config': self.env.user.id,
            'date_start': fields.Datetime.now()
        })

    @api.multi
    @api.depends('date_start', 'date_end')
    def _compute_date(self):
        today = fields.Date.context_today(self)
        for item in self:
            if item.date_start <= today and item.date_end >= today:
                item.is_valid = True
            else:
                item.is_valid = False

    @api.multi
    def _check_date_exit(self):
        """
        子类中可以重写该方法，增减判断条件。
        :return:
        """
        for item in self:
            if not item.active:
                continue
            domain = []
            if item.date_start and item.date_end:
                domain = [('date_start', '<=', item.date_end),
                          ('date_end', '>=', item.date_start),
                          ('active', '=', True),
                          ('company_id', '=', item.company_id.id),
                          ('id', '!=', item.id)]
            record = self.env[self._name].search(domain)
            if record and len(record) > 0:
                return False
        return True

    @api.multi
    def _check_date(self):
        for item in self:
            if item.date_start and item.date_end:
                date_start_int = int("".join(item.date_start.split("-")))
                date_end_int = int("".join(item.date_end.split("-")))
                if date_end_int < date_start_int:
                    return False
        return True

    _constraints = [
        (_check_date_exit, u'已经存在时间范围重叠的内容！', ['date_start', 'date_end', 'active', 'company_id']),
        (_check_date, u'开始时间晚于结束时间！', ['date_start', 'date_end']),
    ]
