# -*- coding: utf-8 -*-
# Copyright 2018 JDG <www.yunside.com>
# Created by YGJ <guojian.ye@yunside.com> at 2018/8/16

from odoo import models, fields, api

from odoo.exceptions import ValidationError

from odoo.osv import expression


class ClosedBillRecord(models.Model):
    _name = 'jdg.closed.bill'
    _inherit = 'jdg.abstract.base'
    _description = u'关账记录'
    _order = 'number asc'

    date_start = fields.Date(string=u'关账日期起')
    date_end = fields.Date(string=u'关账日期止')
    closed_models = fields.Text(string=u'关账范围')
    closed_uid = fields.Many2one('res.users', string=u'关账人')
    closed_time = fields.Datetime(string=u'关账时间')

    @api.model
    def create(self, values):
        """
        获取自动单号
        :param values:
        :return:
        """
        if values.get('number', '/') == '/':
            values.update({
                'number': self.env['ir.sequence'].next_by_code(self._name)
            })
        return super(ClosedBillRecord, self).create(values)

    @api.multi
    def _check_date_exit(self):
        for item in self:
            domain = []
            if item.date_start and item.date_end:
                domain = [('date_start', '<=', item.date_end),
                          ('date_end', '>=', item.date_start),
                          ('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

    _constraints = [
        (_check_date_exit, u'存在时间范围重叠的关账记录！', ['date_start', 'date_end', 'company_id']),
    ]
