# _*_ coding: utf-8 _*_
from odoo import models, fields, api
from odoo.exceptions import UserError

class ExtendClass(models.TransientModel):
    _name = 'extend.class'

    original_start_date = fields.Date(string='原開始日期')
    original_end_date = fields.Date(string='原結束日期')
    original_start_class_course = fields.Many2one('jt.course.line',string='原開始級數')
    original_end_class_course = fields.Many2one('jt.course.line',string='原結束級數')
    or_start_class_course = fields.Many2one('jt.course.line', string='原開始級數', related='original_start_class_course', readonly=True)
    or_end_class_course = fields.Many2one('jt.course.line', string='原結束級數', related='original_end_class_course', readonly=True)
    course_id = fields.Many2one('jt.course', string='原始課程', readonly=True)
    week = fields.Char(string='原上課星期')
    new_start_date = fields.Date(string='展延開始日期')
    new_end_date = fields.Date(string='展延結束日期')
    new_start_class_course = fields.Many2one('jt.course.line',string='展延開始級數')
    new_end_class_course = fields.Many2one('jt.course.line',string='展延結束級數')
    company_id = fields.Many2one('res.company', 'Company')
    censor = fields.Text(string='錯誤訊息')
    check_pass = fields.Boolean(default=False)

    def censor_funtion(self):
        if not self.new_start_date:
            raise UserError("請輸入展延開始日期")
        if not self.new_start_class_course:
            raise UserError("請輸入展延開始級數")
        if not self.new_end_class_course:
            raise UserError("請輸入展延結束級數")
        active_ids = self.env.context.get('active_ids')
        jt_batch_id = self.env['jt.batch'].search([('id', '=', active_ids)], limit=1)
        self.censor = ''
        for line in jt_batch_id.class_timetable.filtered(lambda x: x.date >= self.new_start_date and x.course_seq != False):
            if (line.teacher or line.teacher1 or line.class_room):
                self.censor += '日期: %s, 級數: %s 已有安排教師或教室請取消才能展延課程\n' % (line.date if line.date else '', line.course_seq if line.course_seq else '')
        if len(self.censor) == 0:
            self.check_pass = True
        return {
            "type": "ir.actions.do_nothing",
        }

    def submit(self):
        if not self.new_start_date:
            raise UserError("請輸入展延開始日期")
        if not self.new_start_class_course:
            raise UserError("請輸入展延開始級數")
        if not self.new_end_class_course:
            raise UserError("請輸入展延結束級數")
        active_ids = self.env.context.get('active_ids')
        jt_batch_id = self.env['jt.batch'].search([('id', '=', active_ids)], limit=1)
        jt_batch_id.start_date, jt_batch_id.end_date, jt_batch_id.start_class_course, jt_batch_id.end_class_course = self.new_start_date, self.new_end_date, self.new_start_class_course, self.new_end_class_course
        jt_batch_id.show_day()
        jt_batch_id.start_date, jt_batch_id.start_class_course = self.original_start_date, self.original_start_class_course.id