from odoo import models, fields, api, _
from datetime import datetime, date
import calendar
from odoo.exceptions import UserError, ValidationError



class RequestForMoney(models.Model):
    _name = 'request.for.money'
    _description = '每月請求書產生'

    name = fields.Char(string='名稱', required = True)
    month = fields.Char(string='月份', required=True, default=datetime.now().strftime('%m'))
    year = fields.Char('年份', required=True, default=datetime.now().strftime('%Y'))
    date_begin = fields.Date(string='起：')
    date_until = fields.Date(string='迄：')
    related_date_begin = fields.Date(string='起：', related='date_begin', readonly=True)
    related_date_until = fields.Date(string='迄：', related='date_until', readonly=True)
    request_details_ids = fields.One2many(comodel_name='request.document', inverse_name='request_for_money_id', string='明細')


    @api.constrains('date_begin', 'date_until')
    def _check_start_end_dates(self):
        for sheet in self:
            if sheet.date_begin > sheet.date_until:
                raise ValidationError(
                    _('啟始日不得大於結束日'))

    @api.constrains('date_begin', 'date_until')
    def _check_sheet_date(self):
        for sheet in self:
            self.env.cr.execute(
                """
                SELECT id
                FROM request_for_money
                WHERE (date_begin <= %s and %s <= date_until)
                    AND id <> %s""",
                (sheet.date_until, sheet.date_begin, sheet.id))
            if any(self.env.cr.fetchall()):
                raise ValidationError(
                    _('你不能有兩張重疊的時間表！\n'
                      '請使用菜單 \'時間表單\' '
                      '避免這個問題。'))

    @api.onchange('month')
    def onchange_month(self):
        if self.month:
            month_date = date(int(self.year), int(self.month), 1)

            self.date_begin = month_date.replace(day=1)

            self.date_until = month_date.replace(day=calendar.monthrange(month_date.year, month_date.month)[1])

    @api.multi
    def wizard_request_information(self):
        action = self.env.ref('jptip_request.loading_request_information_action').read()[0]
        return action