# _*_ coding: utf-8 _*_
# Author: Monica( nikochild@gmail.com)
import logging
import dateutil
from odoo import models, fields, api, _
# from odoo.exceptions import ValidationError
from odoo.exceptions import UserError
from dateutil.relativedelta import relativedelta
from dateutil.rrule import *
from dateutil.parser import *
import datetime
from itertools import groupby
from odoo.fields import Date
import calendar

CODE_FORMAT = "%s%02d"
# KEY_FORMAT = "%04d%02d%02d"
KEY_FORMAT = "%02d"


class JptipBatch(models.Model):
    _name = 'jt.batch'
    _inherit = ['mail.thread', 'mail.activity.mixin', 'utm.mixin', 'format.address.mixin']

    class_state = fields.Selection(selection=([('draft', '草稿'), ('ing', '開課中'), ('stop', '已停班')]), string='Status',
                                   copy=False, default='draft', index=True, readonly=True, track_visibility='onchange')

    name = fields.Char(string='班級名稱', copy=False, track_visibility='onchange')
    code = fields.Char(string='班級代碼', copy=False, track_visibility='onchange')
    start_date = fields.Date(string='開始日期', default=fields.Date.today())
    end_date = fields.Date(string='結束日期')
    course_id = fields.Many2one(comodel_name='jt.course', string='所屬課程', required=True, track_visibility='onchange')
    # limit = fields.Integer(string='每次上課堂數')
    reserved = fields.Integer(string='保留堂數')
    start_class_course = fields.Many2one('jt.course.line', string='開始級數', track_visibility='onchange')
    start_class_course_num = fields.Integer(string='開始堂數', default=1)
    # start_class_course_num = fields.Many2one('jt.course.num', string='開始堂數')
    end_class_course = fields.Many2one('jt.course.line', string='結束級數', track_visibility='onchange')
    # end_class_course_num = fields.Many2one('jt.course.num', string='結束級數')
    end_class_course_num = fields.Integer(string='結束堂數')
    max_unit_load = fields.Integer(string='最多錄取人數')
    min_unit_load = fields.Integer(string='最低開課人數')
    teacher_id = fields.Many2one(comodel_name='jt.teacher', string='講師')
    sup_teacher_id = fields.Many2one(comodel_name='jt.teacher', string='代講')
    foreign_teacher_id = fields.Many2one(comodel_name='jt.teacher', string='外師')
    class_timetable = fields.One2many(comodel_name='class.timetable', inverse_name='class_name', string='班級課表')
    backup_class_timetable = fields.One2many(comodel_name='backup.class.timetable', inverse_name='class_name', string='班級課表')

    time_of_class = fields.Many2one(comodel_name='jt.timing', string='上課開始時間')
    holiday = fields.Many2many(comodel_name='jt.holiday')  # 展開課程時的假日
    st_batch_id = fields.One2many(comodel_name='jt.student.batch', inverse_name='batch_id', string='班級')
    class_room = fields.Many2one(comodel_name='jptip.class.room', string='教室')
    class_time = fields.Many2many(comodel_name='jt.time.session.manager', string='課堂時間', track_visibility='onchange')
    class_session = fields.Many2one('jt.time.session', string='時段', )
    week = fields.Char(string='上課星期', track_visibility='onchange')
    exam_batch_ids = fields.One2many('jt.exam', 'batch_id', string='測驗', copy=False, store=True)
    event_batch = fields.Boolean(string='活動課程', track_visibility='onchange')
    jt_batch_outline = fields.One2many(comodel_name='jt.batch.outline', inverse_name='class_name', string='總表')
    company_id = fields.Many2one('res.company', 'Company',
                                 default=lambda self: self.env['res.company']._company_default_get(),
                                 track_visibility='onchange')
    first_extend = fields.Boolean(default=True)
    cultural_experience = fields.Date(string='文化體驗日')

    # @api.model
    # def create(self, vals):
    #     if not vals.get("code", None):  # 说明当前是手动创建
    #         # ClassCodeNumber = self.env["jptip_core.class_code_number"]
    #         # ClassCodeNumber = self.env["class.code.number"]
    #         key = self.env["class.code.number"].generate_key_from_date(vals.get("start_date", None))
    #         cus_code = self.env["class.code.number"].next_code_by_key(key)
    #         course_id = self.env['jt.course'].browse(vals["course_id"])
    #         vals["code"] = "%s%s" % (course_id.code, cus_code)
    #         if not vals.get("name", None):
    #             vals['name'] = "[%s]%s" % (vals["code"], course_id.name)
    #         res = super(JptipBatch, self).create(vals)
    #     if vals.get("code", None):
    #         res = super(JptipBatch, self).create(vals)
    #     return res

    @api.multi
    def write(self, vals):
        vals_date = vals.get("start_date", None)
        if vals_date and vals_date[2:4] != self.code[1:3]:
            for batch in self:
                # if batch.date and batch.date != vals_date and batch.code:
                # self.env["class.code.number"].recover_if_biggest(batch.code)
                key = self.env["class.code.number"].generate_key_from_date(vals_date)
                cus_code = self.env["class.code.number"].next_code_by_key(key)
                course_id = self.env['jt.course'].browse(batch.course_id.id)
                vals["code"] = "%s%s" % (course_id.code, cus_code)
        return super(JptipBatch, self).write(vals)

    @api.onchange('course_id')
    def start_course(self):
        if self.course_id and self.course_id.course_ids:
            course = sorted(self.course_id.course_ids, key=lambda x: x.id)
            values = {
                'start_class_course': course[0].id,
            }
            self.update(values)

    @api.multi
    def _delect_timetable(self):
        class_table_obj = self.env['class.timetable'].search([('class_name', '=', self.id)])
        time_team_obj = self.env['class.timetable.team'].search([('class_name', '=', self.id)]).unlink()
        batch_class_line_obj = self.env['jt.batch.class.line'].search([('class_name', '=', self.id)]).unlink()
        return class_table_obj.unlink()

    @api.multi
    def remove_holiday(self, start, end, week, schedule_date=None, change=None):
        domain = [('schedule_date', '>=', start)]
        holiday_index = []
        if any([end]):
            domain += [('schedule_date', '<=', end)]
        holiday = self.env['jt.holiday'].search(domain)
        try:
            if week.find(',') > -1 or int(week) <= 7:
                time_list = self._get_time_list(start, end, week)
                for hd_index in holiday:
                    hd = datetime.datetime.strptime(hd_index.schedule_date, '%Y-%m-%d')
                    if hd in time_list:
                        holiday_index.append(time_list.index(hd))
                return time_list, holiday_index
        except ValueError:
            raise UserError("請將%s上課星期用逗號區隔" % (week))
        else:
            raise UserError("請將%s上課星期用逗號區隔" % (week))

    @api.multi
    def _get_time_list(self, start, end, week):
        try:
            week = week.split(',')
        except:
            week = week
        cache_time = []
        for i in range(len(week)):
            try:
                WEEK = list(
                    rrule(WEEKLY, wkst=SU, byweekday=(int(week[i]) - 1), dtstart=parse(start), until=parse(end)))
            except:
                WEEK = list(rrule(WEEKLY, count=2000, wkst=SU, byweekday=(int(week[i]) - 1), dtstart=parse(start)))
            cache_time.extend(WEEK)
        time_list = sorted(cache_time)
        return time_list

    @api.multi
    def _get_time_table(self, time_list, holiday, wizard=None):
        res = []
        if wizard is None:
            class_name = self
            class_once_limit = len(self.class_time)
            course_line = sorted(self.course_id.course_ids, key=lambda x: x['id'])
            # start_course_num = self.start_class_course_num.num
            start_course_num = self.start_class_course_num
            start_course_ori = self.start_class_course
            end_course_ori = self.end_class_course or course_line[-1]
            class_room = self.class_room
            teacher = self.teacher_id.id or False
            time = sorted(self.class_time, key=lambda x: x['begin_time'])
            time_of_class = self.time_of_class.id
            end_up = True
        else:
            class_name = wizard.class_name
            class_once_limit = len(wizard.class_time)
            course_line = sorted(wizard.course_id.course_ids, key=lambda x: x['id'])
            # start_course_num = self.start_class_course_num.num
            start_course_num = wizard.start_class_course_num
            start_course_ori = wizard.start_class_course
            end_course_ori = wizard.end_class_course or course_line[-1]
            class_room = wizard.class_room
            teacher = wizard.teacher_id.id or False
            time = sorted(wizard.class_time, key=lambda x: x['begin_time'])
            time_of_class = wizard.time_of_class.id
            end_up = False
        time_day = 0
        start_course = course_line.index(start_course_ori)
        end_course = course_line.index(end_course_ori)
        for j in course_line[start_course:end_course + 1]:
            # 一級總共幾堂
            if wizard is None:
                reserved_class = self.reserved
                # end_course_num = self.end_class_course_num.num or 0
                end_course_num = self.end_class_course_num or 0
            else:
                reserved_class = wizard.reserved
                # end_course_num = wizard.end_class_course_num.num or 0
                end_course_num = wizard.end_class_course_num or 0
            if j.id == end_course_ori.id:
                if start_course == end_course and end_course_num != 0:
                    total_class = end_course_num - start_course_num + 1 + reserved_class
                    i = start_course_num - 1
                else:
                    end_course_num = end_course_num if end_course_num else j.class_num
                    total_class = end_course_num + reserved_class
                    i = 0
            else:
                if time_day == 0:
                    end_course_num = j.class_num
                    total_class = j.class_num - start_course_num + 1 + reserved_class
                    i = start_course_num - 1
                else:
                    end_course_num = j.class_num
                    total_class = j.class_num + reserved_class
                    i = 0

            total_class_day = total_class // class_once_limit
            no_int = total_class % class_once_limit
            if no_int != 0:
                total_class_day += 1
            # 特別日
            case_day = int(j.case_day)
            cas_string = j._fields['case_day'].string
            question_day = int(j.question_day)
            question_string = j._fields['question_day'].string
            circumcision = int(j.circumcision)
            circumcision_str = j._fields['circumcision'].string
            # 堂數開始
            for day in range(total_class_day):
                time_day += 1
                while time_day - 1 in holiday:
                    for once_class in range(class_once_limit):
                        h = self.env['jt.holiday'].search(
                            [('schedule_date', '=', time_list[time_day - 1].strftime('%Y-%m-%d')),('company_id', '=', self.company_id.id)])
                        case_day_str = u'停課'
                        res.append({
                            'class_name': class_name.id,
                            'date': time_list[time_day - 1].strftime('%Y-%m-%d'),
                            'day_of_week': time_list[time_day - 1].strftime('%a'),
                            'class_time_begin': time[once_class].id,
                            'course_line_id': j.id,
                            'time_day': time_day - 1,
                            'time_of_class': time_of_class,
                            'case_day_str': '%s' % case_day_str,
                            'state': 'close',
                            'ps': h.name,
                        })
                    time_day += 1
                for once_class in range(class_once_limit):
                    i += 1
                    case_day_str = ''
                    try:
                        if i <= end_course_num and time_day - 1 not in holiday:
                            if i == case_day: # 案內日
                                case_day_str = cas_string
                            if i == question_day: # 問卷日
                                case_day_str = question_string
                            if i == circumcision: # 締切日
                                case_day_str = circumcision_str
                            if i == end_course_num:
                                case_day_str = u'修了日'
                                if j.id == end_course_ori.id and any([class_name.end_date]) == False:
                                    class_name.update({
                                        'end_date': time_list[time_day - 1].strftime('%Y-%m-%d'),
                                    })
                            if time_day == 1 and once_class == 0:
                                case_day_str = u'開課日'
                            if i == 1 and once_class == 0:
                                case_day_str = u'開課日'
                            res.append({
                                'class_name': class_name.id,
                                'date': time_list[time_day - 1].strftime('%Y-%m-%d'),
                                'day_of_week': time_list[time_day - 1].strftime('%a'),
                                'time_of_class': time_of_class,
                                'class_time_begin': time[once_class].id,
                                'class_room': class_room or False,
                                'sequence': i,
                                'teacher': teacher,
                                'time_day': time_day - 1,
                                'course_seq_day': day + 1,  # 級天數
                                'course_seq': '%s：%d' % (j.code, i),
                                'course_line_id': j.id,
                                'case_day_str': '%s' % case_day_str,
                                'state': 'open',
                            })
                        else:
                            if reserved_class > 0:
                                case_day_str = u'停課'
                                res.append({
                                    'class_name': class_name.id,
                                    'date': time_list[time_day - 1].strftime('%Y-%m-%d'),
                                    'day_of_week': time_list[time_day - 1].strftime('%a'),
                                    'class_time_begin': time[once_class].id,
                                    'course_line_id': j.id,
                                    'time_day': time_day - 1,
                                    'time_of_class': time_of_class,
                                    'case_day_str': '%s' % case_day_str,
                                    'state': 'reserved',
                                })
                                if not any([class_name.end_date]) or any([end_up]):
                                    class_name.update({
                                        'end_date': time_list[time_day - 1].strftime('%Y-%m-%d'),
                                    })
                                reserved_class -= 1
                            else:
                                break;
                    except:
                        break;
        self.write({'class_state': 'ing'})
        return res

    def cancel_lock(self):
        self.first_extend = not self.first_extend
        if self.end_date:
            self.end_date =None

    def show_day(self):
        check_week = self.week.split(',')
        for i in range(len(check_week)):
            if int(i) + 1 == 6 or int(i) + 1 == 7:
                for line in self.class_time:
                    if line.name[1] == u'早':
                        raise UserError("課堂時間與上課星期無法對應，請確認")
        doc = []
        if not self.class_timetable:
            self.first_extend = False
        if self.class_timetable:
            if self.first_extend == True:
                self._delect_timetable()
                self.env['note.note'].search([('class_name', '=', self.id), ('company_id', '=', self.company_id.id)]).unlink()
                self.first_extend = False
            if self.first_extend == False:
                for line in self.class_timetable.filtered(lambda x: x.date >= self.start_date):
                    time_team_obj = self.env['class.timetable.team'].search([('class_name', '=', self.id), ('course_line_id', '=', line.course_line_id.id),('date','<',self.start_date)]).unlink()
                    batch_class_line_obj = self.env['jt.batch.class.line'].search([('class_name', '=', self.id), ('course_line_id', '=', line.course_line_id.id),('date','<',self.start_date)]).unlink()
                    self.env['note.note'].search([('class_name', '=', self.id), ('company_id', '=', self.company_id.id),('course_seq','=',line.course_seq)]).unlink()
                    if line.course_line_id.id not in doc:
                        doc.append(line.course_line_id.id)
                    line.unlink()
        if self.jt_batch_outline:
            for line in self.jt_batch_outline:
                if line.course_line_id.id in doc:
                    line.unlink()

        start = self.start_date
        end = self.end_date
        time = self.class_time
        week = self.week
        time_list, holiday = self.remove_holiday(start, end, week)
        time_table = self._get_time_table(time_list, holiday)
        self.class_timetable = time_table
        for line in self.class_timetable:
            if line.course_seq:
                course_seq = line.course_seq
            elif not line.course_seq:
                course_seq = ''
            list = {
                'date': line.date,
                'class_name': self.id,
                'course_seq': line.course_seq,
                'company_id': self.company_id.id,
                'memo': self.name + '-' + course_seq + '-' + line.date
            }
            start_time = None
            for row in line.class_name.class_time.sorted(key=lambda r: r.id, reverse=False):
                start_time = row.begin_time
            if line.case_day_str == '開課日':
                new = self.env['note.note'].create(list)
                new.write({
                    'tag_ids':[(6, 0, self.env['note.tag'].search([('name', '=', '開課日')]).ids)],
                    'type': '案內日',
                    'memo': '[%s]%s[%s]%s %s' % ('開課日', start_time, line.class_name.code, line.class_name.name, line.course_line_id.code)
                })
                for row in self.company_id.school_staff:
                    reg = {
                        'res_id': new.id,
                        'res_model': 'note.note',
                        'partner_id': row.partner_id.id,
                    }
                    if not self.env['mail.followers'].search([('res_id', '=', new.id), ('res_model', '=', 'note.note'),('partner_id', '=', row.partner_id.id)]):
                        follower_id = self.env['mail.followers'].create(reg)
            elif line.case_day_str == '案內日':
                new1 = self.env['note.note'].create(list)
                new1.write({
                    'tag_ids':[(6, 0, self.env['note.tag'].search([('name', '=', '案內日')]).ids)],
                    'type': '案內日',
                    'memo': '[%s]%s[%s]%s %s' % ('案內日', start_time, line.class_name.code, line.class_name.name, line.course_line_id.code)
                })
                for row in self.company_id.school_staff:
                    reg1 = {
                        'res_id': new1.id,
                        'res_model': 'note.note',
                        'partner_id': row.partner_id.id,
                    }
                    if not self.env['mail.followers'].search([('res_id', '=', new1.id), ('res_model', '=', 'note.note'),('partner_id', '=', row.partner_id.id)]):
                        follower_id = self.env['mail.followers'].create(reg1)
            elif line.case_day_str == '問卷日':
                new2 = self.env['note.note'].create(list)
                new2.write({
                    'tag_ids':[(6, 0, self.env['note.tag'].search([('name', '=', '問卷日')]).ids)],
                    'type': '問卷日',
                    'memo': '[%s]%s[%s]%s %s' % ('問卷日', start_time, line.class_name.code, line.class_name.name, line.course_line_id.code)
                })
                for row in self.company_id.school_staff:
                    reg2 = {
                        'res_id': new2.id,
                        'res_model': 'note.note',
                        'partner_id': row.partner_id.id,
                    }
                    if not self.env['mail.followers'].search([('res_id', '=', new2.id), ('res_model', '=', 'note.note'),('partner_id', '=', row.partner_id.id)]):
                        follower_id = self.env['mail.followers'].create(reg2)
            elif line.case_day_str == '締切日':
                new3 = self.env['note.note'].create(list)
                new3.write({
                    'tag_ids': [(6, 0, self.env['note.tag'].search([('name', '=', '締切日')]).ids)],
                    'type': '締切日',
                    'memo': '[%s]%s[%s]%s %s' % ('締切日', start_time, line.class_name.code, line.class_name.name, line.course_line_id.code)
                })
                for row in self.company_id.school_staff:
                    reg3 = {
                        'res_id': new3.id,
                        'res_model': 'note.note',
                        'partner_id': row.partner_id.id,
                    }
                    if not self.env['mail.followers'].search([('res_id', '=', new3.id), ('res_model', '=', 'note.note'),('partner_id', '=', row.partner_id.id)]):
                        follower_id = self.env['mail.followers'].create(reg3)
            elif line.case_day_str == '修了日':
                new4 = self.env['note.note'].create(list)
                new4.write({
                    'tag_ids': [(6, 0, self.env['note.tag'].search([('name', '=', '修了日')]).ids)],
                    'type': '修了日',
                    'memo': '[%s]%s[%s]%s %s' % ('修了日', start_time, line.class_name.code, line.class_name.name, line.course_line_id.code)
                })
                for row in self.company_id.school_staff:
                    reg4 = {
                        'res_id': new4.id,
                        'res_model': 'note.note',
                        'partner_id': row.partner_id.id,
                    }
                    if not self.env['mail.followers'].search([('res_id', '=', new4.id), ('res_model', '=', 'note.note'),('partner_id', '=', row.partner_id.id)]):
                        follower_id = self.env['mail.followers'].create(reg4)
        team = self.env['class.timetable.team'].get_team(self.class_timetable)
        outline = self.env['jt.batch.outline']._get_batch_outline(self.id)

    @api.multi
    def close_replace_timetable(self, close_class, schedule_date=None):
        holiday = sorted(close_class, key=lambda x: (x.class_name, x.time_day))
        holiday_class = groupby(holiday, lambda x: x.class_name)
        for class_class, class_timetable in holiday_class:
            time_table = self.env['class.timetable']
            team_obj = self.env['class.timetable.team']
            outline = self.env['jt.batch.outline']
            class_timetable = list(class_timetable)
            time = class_class.week
            start = class_class.start_date
            end = ''
            time_list, holiday_day = class_class.remove_holiday(start, end, time)
            clock_list = class_class.class_time
            clock = sorted(clock_list, key=lambda x: x['begin_time'])
            limit = len(class_class.class_time)
            course_line = sorted(class_class.course_id.course_ids, key=lambda x: x['id'])
            # start_class_num = class_class.start_class_course_num.num
            start_class_num = class_class.start_class_course_num
            start_course_ori = class_timetable[-1].course_line_id
            end_course_ori = class_class.end_class_course or course_line[-1]
            start_course = course_line.index(start_course_ori)
            end_course = course_line.index(end_course_ori)
            course = [course.id for course in course_line[start_course:end_course + 1]]
            time_day = class_timetable[-1].time_day
            change_list = time_table.search([('class_name', '=', class_class.id), ('state', '!=', 'close'),
                                             ('time_day', '>', time_day), ('course_line_id', 'in', course),
                                             ('company_id', '=', self.env.user.company_id.id)])

            if any(change_list):
                time_day_f = change_list[-1].time_day
            else:
                time_day_f = class_timetable[-1].time_day
            times = 0
            change = 0
            reserved_change = 0
            start_num = class_timetable[0].sequence
            for j in course_line[start_course:end_course + 1]:
                # end_class_num = class_class.end_class_course_num.num or 0
                end_class_num = class_class.end_class_course_num or 0
                if class_class.reserved != 0:
                    if j.id == class_timetable[0].course_line_id.id:
                        reserved_class = len(
                            change_list.filtered(
                                lambda x: x.course_line_id.id == j.id and x.state == 'reserved')) - len(
                            class_timetable)
                        if reserved_class < 0:
                            reserved_change = abs(reserved_class)
                            reserved_class = 0
                    else:
                        reserved_class = len(
                            change_list.filtered(lambda x: x.course_line_id.id == j.id and x.state == 'reserved'))
                else:
                    reserved_class = class_class.reserved

                if j.id == end_course_ori.id and end_class_num != 0:
                    if start_course == end_course:
                        total_class = end_class_num - start_num + 1 + int(reserved_class)
                        i = start_num - 1
                        seq_day = class_timetable[0].course_seq_day - 1
                    else:
                        end_class_num = end_class_num if end_class_num else j.class_num
                        if reserved_change != 0:
                            total_class = end_class_num + int(reserved_class - reserved_change)
                            reserved_change = 0
                        else:
                            total_class = end_class_num + int(reserved_class)
                        i = 0
                        seq_day = 0
                else:
                    if times == 0:
                        end_class_num = j.class_num
                        total_class = (j.class_num - start_num + 1) + int(reserved_class)
                        i = start_num - 1
                        seq_day = class_timetable[0].course_seq_day - 1
                    else:
                        end_class_num = j.class_num
                        if reserved_change != 0:
                            total_class = j.class_num + int(reserved_class - reserved_change)
                            reserved_change = 0
                        else:
                            total_class = j.class_num + int(reserved_class)
                        i = 0
                        seq_day = 0
                total_class_day = total_class // limit
                no_int = total_class % limit
                if no_int != 0:
                    total_class_day += 1
                case_day = int(j.case_day)
                cas_string = j._fields['case_day'].string
                question_day = int(j.question_day)
                question_string = j._fields['question_day'].string
                circumcision = int(j.circumcision)
                circumcision_str = j._fields['circumcision'].string
                for day in range(total_class_day):
                    seq_day += 1
                    time_day += 1
                    change += 1
                    try:
                        change_list[times + 1]
                    except:
                        time_day_f += 1
                    for once_class in range(limit):
                        if reserved_class > 0 or i <= end_class_num:
                            times += 1
                            i += 1
                        case_day_str = ''
                        if i <= end_class_num:
                            if i == case_day:
                                case_day_str = cas_string
                            if i == question_day:
                                case_day_str = question_string
                            if i == circumcision:
                                case_day_str = circumcision_str
                            if i == end_class_num:
                                case_day_str = u'修了日'
                                if j.id == end_course_ori.id:
                                    class_class.update({
                                        'end_date': time_list[time_day_f].strftime('%Y-%m-%d'),
                                    })
                            if i == start_class_num and class_class.start_class_course.id == j.id:
                                case_day_str = u'開課日'
                            if i == 1 and once_class == 0:
                                case_day_str = u'開課日'
                            try:
                                change_list[times - 1].update({
                                    'name': '[%s]%s：%d' % (class_class.code, j.code, i),
                                    'sequence': i,
                                    'course_seq': '%s：%d' % (j.code, i),
                                    'case_day_str': case_day_str,
                                    'course_seq_day': seq_day,
                                    'course_line_id': j.id,
                                    'state': 'open',
                                })
                            except:
                                time_table.create({
                                    'class_name': class_class.id,
                                    'course_seq': '%s：%d' % (j.code, i),
                                    'sequence': i,
                                    'course_seq_day': seq_day,
                                    'class_room': class_class.class_room or False,
                                    'date': time_list[time_day_f].strftime('%Y-%m-%d'),
                                    'day_of_week': time_list[time_day_f].strftime('%a'),
                                    'class_time_begin': clock[once_class].id,
                                    'course_line_id': j.id,
                                    'time_day': time_day_f,
                                    'time_of_class': class_class.time_of_class.id,
                                    'case_day_str': '%s' % case_day_str,
                                    'state': 'open',
                                })
                        else:
                            if reserved_class > 0:
                                case_day_str = u'停課'
                                try:
                                    change_list[times - 1].update({
                                        'name': '[%s]%s：%d' % (class_class.code, j.code, 0),
                                        'sequence': 0,
                                        'course_seq': '',
                                        'case_day_str': case_day_str,
                                        'course_seq_day': 0,
                                        'state': 'reserved',
                                        'teacher': False,
                                        'team_id': False,
                                    })
                                except:
                                    time_table.create({
                                        'sequence': 0,
                                        'course_seq': '',
                                        'class_name': class_class.id,
                                        'date': time_list[time_day_f].strftime('%Y-%m-%d'),
                                        'day_of_week': time_list[time_day_f].strftime('%a'),
                                        'class_time_begin': clock[once_class].id,
                                        'course_line_id': j.id,
                                        'time_day': time_day_f,
                                        'time_of_class': class_class.time_of_class.id,
                                        'case_day_str': case_day_str,
                                        'course_seq_day': 0,
                                        'state': 'reserved',
                                    })
                                class_class.update({
                                    'end_date': time_list[time_day_f].strftime('%Y-%m-%d'),
                                })
                                reserved_class -= 1
                            else:
                                break;
            if schedule_date != True:
                for holiday_time in class_timetable:
                    h = self.env['jt.holiday'].search([('schedule_date', '=', holiday_time.date),('company_id', '=', self.company_id.id)])
                    holiday_time.update({
                        'sequence': 0,
                        'name': '',
                        'course_seq': '',
                        'class_time_begin': holiday_time.class_time_begin.id,
                        'time_day': holiday_time.time_day,
                        'case_day_str': '停課',
                        'course_seq_day': 0,
                        'state': 'close',
                        'team_id': False,
                        'ps': h.name,
                    })
            give_get_team = time_table.search([('class_name', '=', class_class.id), ('state', '!=', 'close'),
                                               ('time_day', '>', class_timetable[-1].time_day),
                                               ('course_line_id', 'in', course),
                                               ('sequence', '!=', 0),
                                               ('company_id', '=', self.env.user.company_id.id)])
            team_obj.get_team(give_get_team)
            outline._get_batch_outline(class_class.id)

    @api.multi
    def action_view_exam(self):
        exam_ids = self.mapped('exam_batch_ids').ids
        action = self.env.ref('jptip_core.act_batch_exam1').read()[0]
        action['domain'] = [('id', 'in', exam_ids)]
        action['context'] = {}
        return action


class JtBatchOutline(models.Model):
    _name = 'jt.batch.outline'
    _order = 'date_from, course_line_id'

    name = fields.Char(default='date')
    class_name = fields.Many2one('jt.batch', string='班級名稱', ondelete='cascade')
    course_line_id = fields.Many2one('jt.course.line', string='級數')
    duration = fields.Char(string='區間')
    start_class_course_num = fields.Integer(string='開始級數')
    date_from = fields.Date(string='開始日期')
    end_class_course_num = fields.Integer(string='結束級數')
    date_to = fields.Date(string='結束日期')
    company_id = fields.Many2one(related='class_name.company_id', string='Company', store=True, readonly=True)

    @api.multi
    def open_examination_list(self):
        action = self.env.ref('jptip_core.batch_exam_view_action').read()[0]
        action['context'] = {}
        action['context'] ={'default_batch_course_id': self.course_line_id.id, 'default_batch_id': self.class_name.id}
        return action

    @api.multi
    def _get_batch_outline(self, class_name=None):
        class_name_id = self.env['jt.batch'].browse(class_name)
        if any(class_name_id):
            if not any([class_name_id.event_batch]):
                # class_name_id.jt_batch_outline.unlink()
                timetable = class_name_id.class_timetable
                case_day_str = ['開課日', '修了日']
                timetable_case_day = timetable.filtered(lambda x: x.case_day_str in case_day_str)
                timetable_case_day_f = sorted(timetable_case_day, key=lambda x: (x.course_line_id, x.date))
                timetable_case_day_g = groupby(timetable_case_day_f, lambda x: x.course_line_id)
                ori_outline = dict((out.id, out) for out in class_name_id.jt_batch_outline)
                for course, course_line in timetable_case_day_g:
                    course_line = list(course_line)
                    if not any(class_name_id.jt_batch_outline.filtered(lambda x: x.course_line_id.id == course.id)):
                        k = self.create({
                            'class_name': class_name_id.id,
                            'course_line_id': course.id,
                            'date_from': course_line[0].date,
                            'date_to': course_line[-1].date,
                            'start_class_course_num': course_line[0].sequence,
                            'end_class_course_num': course_line[-1].sequence,
                            'duration': '%s-%s, %s~%s' % (
                                course_line[0].sequence, course_line[-1].sequence, course_line[0].date,
                                course_line[-1].date),
                        })
                    else:
                        outlines = class_name_id.jt_batch_outline.filtered(lambda x: x.course_line_id.id == course.id)
                        if outlines.id in ori_outline:
                            ori_outline.pop(outlines.id)
                        outlines.date_from = course_line[0].date
                        outlines.date_to = course_line[-1].date
                        outlines.start_class_course_num = course_line[0].sequence
                        outlines.end_class_course_num = course_line[-1].sequence
                        outlines.duration = '%s-%s, %s~%s' % (
                            course_line[0].sequence, course_line[-1].sequence, course_line[0].date,
                            course_line[-1].date)
                for key, out in ori_outline.items():
                    out.unlink()


class BackupClassTimetable(models.Model):
    _name = 'backup.class.timetable'
    _order = 'id'

    name = fields.Char(string='Timetable Name')
    class_name = fields.Many2one(comodel_name='jt.batch', string='班級名稱', ondelete='cascade')
    date = fields.Date(string='日期')
    day_of_week = fields.Char(string='星期')
    course_seq_day = fields.Integer(string='級數天')
    course_line_id = fields.Many2one('jt.course.line', string='級數')
    time_of_class = fields.Many2one(comodel_name='jt.timing', string='上課開始時間')
    class_time_begin = fields.Many2one(comodel_name='jt.time.session.manager', string='上課時間')
    class_time_event = fields.Char(string='活動時間')
    class_room = fields.Many2one(comodel_name='jptip.class.room', string='教室')
    sequence = fields.Integer(string='排序')
    course_seq = fields.Char(string='級數排序')
    case_day_str = fields.Char(string='特別日')
    teacher = fields.Many2one(comodel_name='jt.teacher', string='講師', track_visibility='onchange', )
    teacher1 = fields.Many2one(comodel_name='jt.teacher', string='代講')
    ps = fields.Char(string='備註')
    time_day = fields.Integer(string='time_day')
    time_clock = fields.Char(string='時間')
    state = fields.Selection(selection=([('open', 'Open'), ('close', 'Close'), ('reserved', 'Reserved')]),
                             default='open', string='狀態')
    event = fields.Boolean()
    event_categ = fields.Many2one(comodel_name='jptip.event.category', string='活動類別')
    event_id = fields.Many2one(comodel_name='jptip.event', string='活動')
    same_teacher = fields.Boolean()
    team_id = fields.Many2one(comodel_name='class.timetable.team')
    company_id = fields.Many2one(related='class_name.company_id', string='Company', store=True, readonly=True)
    is_auditing = fields.Boolean(string='試聽課程')


class ClassTimetable(models.Model):
    _name = 'class.timetable'
    _order = 'id'

    name = fields.Char(string='Timetable Name')
    class_name = fields.Many2one(comodel_name='jt.batch', string='班級名稱', ondelete='cascade')
    date = fields.Date(string='日期')
    day_of_week = fields.Char(string='星期')
    course_seq_day = fields.Integer(string='級數天')
    course_line_id = fields.Many2one('jt.course.line', string='級數')
    time_of_class = fields.Many2one(comodel_name='jt.timing', string='上課開始時間')
    class_time_begin = fields.Many2one(comodel_name='jt.time.session.manager', string='上課時間')
    class_time_event = fields.Char(string='活動時間')
    class_room = fields.Many2one(comodel_name='jptip.class.room', string='教室')
    sequence = fields.Integer(string='排序')
    course_seq = fields.Char(string='級數排序')
    case_day_str = fields.Char(string='特別日')
    teacher = fields.Many2one(comodel_name='jt.teacher', string='講師', track_visibility='onchange', )
    teacher1 = fields.Many2one(comodel_name='jt.teacher', string='代講')
    ps = fields.Char(string='備註')
    time_day = fields.Integer(string='time_day')
    time_clock = fields.Char(string='時間')
    state = fields.Selection(selection=([('open', 'Open'), ('close', 'Close'), ('reserved', 'Reserved')]),
                             default='open', string='狀態')
    event = fields.Boolean()
    event_categ = fields.Many2one(comodel_name='jptip.event.category', string='活動類別')
    event_id = fields.Many2one(comodel_name='jptip.event', string='活動')
    same_teacher = fields.Boolean()
    team_id = fields.Many2one(comodel_name='class.timetable.team')
    company_id = fields.Many2one(related='class_name.company_id', string='Company', store=True, readonly=True)
    is_auditing = fields.Boolean(string='網站串聯')

    @api.multi
    @api.depends('class_name.code', 'course_seq', 'event_id.name')
    def name_get(self):
        res = []
        for record in self:
            if record.event == 0:
                name = "[%s]%s" % (record.class_name.name, record.course_seq)
            else:
                name = "%s" % (record.event_id.name)
            res.append((record.id, name))
        return res

    @api.model
    def create(self, values):
        if not values.get('name', False) or values['name'] == _('New'):
            batch = self.env['jt.batch'].browse(values.get('class_name', False))
            if not values.get('event'):
                values['name'] = '[%s]%s' % (batch.code, values.get('course_seq', False))
            else:
                event = self.env['jptip.event'].browse(values.get('event_id'))
                values['name'] = '%s' % event.name
        res = super(ClassTimetable, self).create(values)
        return res

    @api.multi
    @api.onchange('teacher')
    def compute_same_teacher(self):
        timetable_obj = self.env['class.timetable']
        timetable_id = timetable_obj.browse(self._origin.id)
        date = self.date
        teacher = self.teacher
        class_name = self.env['jt.batch'].search([('name', '=', self.class_name.name),
                                                  ('company_id', '=', self.env.user.company_id.id)])
        try:
            same_teacher = timetable_obj.search(
                [('date', '=', date), ('teacher', '=', teacher.id), ('class_name', '!=', class_name.id),
                 ('class_time_begin', '=', self.class_time_begin.id),
                 ('company_id', '=', class_name.company_id.id)])
            if any(same_teacher) and any([teacher]):
                self.same_teacher = True
            else:
                self.same_teacher = False
        except:
            return True

    @api.multi
    def cache_time_table(self):
        event_id = self.env['jptip.event'].browse(self.env.context.get('default_event_id'))
        if event_id.event_timetable:
            raise UserError("已安排活動在課程裡")
        else:
            for timetable in self:
                timetable.update({
                    'event_id': event_id.id,
                    'event_categ': event_id.event_categ,
                    'event': 1
                })
                event_id.update({
                    'event_timetable': timetable.id,
                    'event_batch': timetable.class_name,
                    'event_select': [(6, 0, [])]
                })
        return True

    @api.multi
    def shift_up_timetable(self):
        timetable_obj = self.env['class.timetable'] # 導到課表的環境
        course_line = self.env['jt.course.line'].search([('course_id', '=', self.course_line_id.course_id.id)]) # 級數的系列
        course_s = sorted(course_line, key=lambda x: x['id']) # 根據系列的id進行由小到大的排序
        up_course = course_s.index(self.course_line_id) # 給予索引位置
        pre_timetable = timetable_obj.search([('id', '<', self.id), ('class_name', '=', self.class_name.id),
                                              ('state', '=', 'reserved')]) # 找到此堂課之前的保留堂數
        if any(pre_timetable): # 如果有保留堂數的話
            pre = pre_timetable[-1] # 找到保留堂數的最後一堂
            shift_up_tmtb = timetable_obj.search([('class_name', '=', self.class_name.id),
                                                  ('course_line_id', 'in', [line.id for line in course_s[up_course:]]),
                                                  ('state', '!=', 'close'), ('id', '>=', self.id)]) # 後續所有課程都準備往上移動
            team_obj = self.env['class.timetable.team']
            team = team_obj.search([('class_name', '=', self.class_name.id),
                                    ('date', '=', pre.date),
                                    ('state', '!=', 'close'),
                                    ('company_id', '=', self.company_id.id)])
            pre.update({
                'sequence': self.sequence,
                'course_line_id': self.course_line_id.id,
                'case_day_str': self.case_day_str,
                'course_seq': self.course_seq,
                'name': self.name,
                'state': 'open',
                'course_seq_day': self.course_seq_day,
            })
            # 先改變序號再去get_team，因為原本序號是0會被排除
            if not any(team):
                team_id = team_obj.get_team(pre)[0]
            else:
                team_id = team.id
            pre.update({'team_id': team_id})
            for seq in range(len(shift_up_tmtb)):
                if seq == len(shift_up_tmtb) - 1:
                    shift_up_tmtb[seq].unlink()
                elif seq == len(shift_up_tmtb) - 2 and shift_up_tmtb[seq].case_day_str == u'停課':
                    if not any(shift_up_tmtb[seq + 1].team_id):
                        team_id = False
                    else:
                        team_id = shift_up_tmtb[seq].team_id
                    shift_up_tmtb[seq].update({
                        'sequence': shift_up_tmtb[seq + 1].sequence,
                        'name': shift_up_tmtb[seq + 1].name,
                        'case_day_str': shift_up_tmtb[seq + 1].case_day_str,
                        'state': 'reserved',
                        'course_line_id': shift_up_tmtb[seq + 1].course_line_id.id,
                        'course_seq': shift_up_tmtb[seq + 1].course_seq,
                        'team_id': team_id,
                        'course_seq_day': shift_up_tmtb[seq + 1].course_seq_day,
                    })
                else:
                    if not any(shift_up_tmtb[seq + 1].team_id):
                        team_id = False
                    else:
                        team_id = shift_up_tmtb[seq].team_id
                    shift_up_tmtb[seq].update({
                        'sequence': shift_up_tmtb[seq + 1].sequence,
                        'name': shift_up_tmtb[seq + 1].name,
                        'case_day_str': shift_up_tmtb[seq + 1].case_day_str,
                        'state': shift_up_tmtb[seq + 1].state,
                        'course_line_id': shift_up_tmtb[seq + 1].course_line_id.id,
                        'course_seq': shift_up_tmtb[seq + 1].course_seq,
                        'team_id': team_id,
                        'course_seq_day': shift_up_tmtb[seq + 1].course_seq_day,
                    })
        else:
            raise UserError("無法上移，沒有保留課表")
        return self.env['jt.batch.outline']._get_batch_outline(self.class_name.id)

    @api.multi
    def shift_down_timetable(self):
        timetable_obj = self.env['class.timetable']
        course_line = self.env['jt.course.line'].search([('course_id', '=', self.course_line_id.course_id.id)])
        start = self.class_name.start_date
        week = self.class_name.week
        time_list, holiday = self.env['jt.batch'].remove_holiday(start, '', week)
        course_s = sorted(course_line, key=lambda x: x['id'])
        down_course = course_s.index(self.course_line_id)
        shift_down_tmtb = timetable_obj.search([('class_name', '=', self.class_name.id),
                                                ('course_line_id', 'in', [line.id for line in course_s[down_course:]]),
                                                ('state', '!=', 'close'), ('id', '>', self.id)])
        clock_list = self.class_name.class_time
        clock = sorted(clock_list, key=lambda x: x['begin_time'])
        for seq in range(len(shift_down_tmtb) - 1, -1, -1):
            if seq == 0:
                shift_down_tmtb[seq].update({
                    'sequence': self.sequence,
                    'case_day_str': self.case_day_str,
                    'name': self.name,
                    'state': self.state,
                    'course_line_id': self.course_line_id.id,
                    'course_seq': self.course_seq,
                    'course_seq_day': self.course_seq_day,
                })
            else:
                if seq == len(shift_down_tmtb) - 1:
                    new = shift_down_tmtb[seq].copy()

                    team_id = new.team_id or False
                    if any(new.team_id):
                        team_id = self.env['class.timetable.team'].get_team(new)[0]
                    once_class = clock.index(new.class_time_begin) - (len(clock_list) - 1)
                    if once_class == 0:
                        time_day = new.time_day + 1
                        seq_day = new.course_seq_day + 1
                    else:
                        time_day = new.time_day
                        seq_day = new.course_seq_day
                    new.update({
                        'date': time_list[time_day].strftime('%Y-%m-%d'),
                        'day_of_week': time_list[time_day].strftime('%a'),
                        'time_day': time_day,
                        'course_seq_day': seq_day,
                        'class_time_begin': clock[once_class].id,
                        'team_id': team_id,
                    })
                shift_down_tmtb[seq].write({
                    'sequence': shift_down_tmtb[seq - 1].sequence,
                    'name': shift_down_tmtb[seq - 1].name,
                    'case_day_str': shift_down_tmtb[seq - 1].case_day_str,
                    'state': shift_down_tmtb[seq - 1].state,
                    'course_seq_day': shift_down_tmtb[seq - 1].course_seq_day,
                    'course_line_id': shift_down_tmtb[seq - 1].course_line_id.id,
                    'course_seq': shift_down_tmtb[seq - 1].course_seq
                })

        self.update({
            'sequence': 0,
            'name': '[%s]%s' % (self.class_name.code, 'False'),
            'case_day_str': u'停課',
            'state': 'reserved',
            'course_seq': False,
            'course_seq_day': False,
            'team_id': False,
        })
        self.env['class.timetable.team'].clear_empety_class_time(self.class_name, shift_down_tmtb.mapped('team_id').ids)
        return self.env['jt.batch.outline']._get_batch_outline(self.class_name.id)

    def class_scheduling(self):
        year = str(datetime.datetime.strptime(self.date, '%Y-%m-%d').year)
        month = str(datetime.datetime.strptime(self.date, '%Y-%m-%d').month)
        jt_batch_class_id = self.env['jt.batch.class'].search([('calendar_id.month','=',month), ('calendar_id.year','=',year), ('company_id', '=', self.company_id.id)])
        return {
            'res_id': jt_batch_class_id.id,
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'jt.batch.class',
            'view_id': self.env.ref('jptip_core.jt_batch_class_form_view').id,
            'type': 'ir.actions.act_window',
        }

    def new_activity(self):
        teacher = None
        if not self.is_auditing:
            self.is_auditing = True
        if self.teacher1:
            teacher = self.teacher1.id
        elif not self.teacher1:
            teacher = self.teacher.id
        event_plan_id = self.env['event.plan'].create({
            'name': '[%s]%s' % (self.class_name.code, self.class_name.name),
            'event_description': False,
            'x_datetime': self.date,
            'event_class_room': self.class_room.id or False,
            'event_teacher': teacher,
            'state': 'draft',
            'event_company': self.company_id.id,
            'x_category': '見學'
        })
        return {
            'res_id': event_plan_id.id,
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'event.plan',
            'view_id': self.env.ref('jptip_activity.event_plan_view_form').id,
            'type': 'ir.actions.act_window',
        }


class ClassTimetableTeam(models.Model):
    _name = 'class.timetable.team'

    name = fields.Char(string='課表日期', compute='compute_name')
    date = fields.Date(string='日期')
    week = fields.Char(string='星期')
    class_timetable = fields.One2many('class.timetable', 'team_id', string='班級課表')
    class_name = fields.Many2one('jt.batch', string='班級', ondelete='cascade')
    course_line_id = fields.Many2one('jt.course.line', string='級數')  # course_line
    state = fields.Selection(selection=([('open', 'Open'), ('close', 'Close'), ('lock', 'Lock')]),
                             default='open', string='狀態')
    work_line_id = fields.Many2one('jt.batch.class.line')
    class_time_begin = fields.Many2many('jt.time.session.manager', string='時段')
    teacher_id = fields.Many2one('jt.teacher', string='講師')
    teacher1_id = fields.Many2one('jt.teacher', string='代講')
    teacher2_id = fields.Many2one('jt.teacher', string='外師')
    room_id = fields.Many2one('jptip.class.room', string='教室')
    class_session = fields.Many2many('jt.time.session', string='時段')
    company_id = fields.Many2one(related='class_name.company_id', string='Company', store=True, readonly=True)
    conflict_teacher = fields.Boolean()
    conflict_room = fields.Boolean()

    @api.multi
    @api.depends('class_timetable')
    def compute_name(self):
        for team in self:
            if any(team.class_timetable):
                hour = '%s-%s' % (team.class_timetable[0].class_time_begin.begin_time,
                                  team.class_timetable[-1].class_time_begin.end_time) or False
                team.name = "%s %s" % (team.date, hour)

    @api.multi
    def clear_empety_class_time(self, class_name, team_id):
        clear_id = self.env['class.timetable.team'].search(
            [('class_name', '=', class_name.id), ('id', 'not in', team_id),
             ('company_id', '=', self.env.user.company_id.id)])
        for clear in clear_id:
            if not any(clear.class_timetable):
                clear.unlink()

    @api.multi
    def get_team(self, res):
        if res:
            team_id = []
            teams = groupby(res, lambda x: x['date'])
            for date, classtime in teams:
                classtime = list(classtime)
                classtime_ids = [time.id for time in classtime if time.sequence != 0]
                classtime_id = self.env['class.timetable'].search([('id', '=', classtime[0].id)])
                hour = '%s-%s' % (classtime[0].class_time_begin.begin_time, classtime[-1].class_time_begin.end_time)
                session = self.env['jt.time.session'].search([('company_id', '=', self.env.user.company_id.id)])
                session_id = session.filtered(lambda x: any(
                    sessions in x.time_duration_ids.ids for sessions in classtime_id.class_name.class_time.ids))
                date_str = datetime.datetime.strptime(date, '%Y-%m-%d')

                if any(classtime_ids):
                    vals = ({
                        'name': "%s %s" % (date, hour),
                        'date': date,
                        'week': datetime.datetime.strptime(date, '%Y-%m-%d').weekday(),
                        'class_time_begin': [(6, 0, [time.class_time_begin.id for time in classtime])],
                        'class_timetable': [(6, 0, classtime_ids)],
                        'course_line_id': classtime_id.course_line_id.id,
                        'class_name': classtime_id.class_name.id,
                        'teacher_id': classtime_id.teacher.id or False,
                        'room_id': classtime_id.class_room.id,
                        'class_session': [(6, 0, session_id.ids)],
                        'company_id': classtime_id.company_id.id
                    })
                    team = super(ClassTimetableTeam, self).create(vals)
                    team_id.append(team.id)
                    work_obj = self.env['jt.batch.class']
                    arrange_teacher = self.env['jt.teacher.batch']
                    work_ids = work_obj.search([('date_from', '<=', date), ('date_to', '>=', date),
                                                ('company_id', '=', classtime_id.company_id.id)])
                    teacher_work = arrange_teacher.search(
                        [('month', '=', date_str.month), ('year', '=', date_str.year),
                         ('company_id', '=', classtime_id.company_id.id)])
                    if not any(teacher_work):
                        teacher_work = arrange_teacher.create({
                            'month': date_str.month,
                            'year': '%s' % date_str.year,
                            'date_from': date_str.replace(day=1).strftime('%Y-%m-%d'),
                            'date_to': date_str.replace(
                                day=calendar.monthrange(date_str.year, date_str.month)[1]).strftime('%Y-%m-%d'),
                            'company_id': classtime_id.company_id.id,
                        })
                    if not any(work_ids):
                        work_ids = work_obj.create({
                            'calendar_id': teacher_work.id,
                            'name': '%s/%s' % (date_str.year, date_str.month),
                            'date_from': date_str.replace(day=1),
                            'date_to': date_str.replace(day=calendar.monthrange(date_str.year, date_str.month)[1]),
                            'company_id': classtime_id.company_id.id,
                        })
                    work_lines_obj = self.env['jt.batch.class.line']
                    work_lines = work_lines_obj.search(
                        [('class_name', '=', team.class_name.id), ('order_id', '=', work_ids.id),
                         ('course_line_id', '=', team.course_line_id.id),
                         ('company_id', '=', classtime_id.company_id.id)])
                    if not any(work_lines):
                        work_lines = work_lines_obj.create({
                            'name': team.name,
                            'class_name': classtime_id.class_name.id,
                            'day_of_1': [(6, 0, [team.filtered(
                                lambda x: (x.week == '0')).id] or False)],
                            'day_of_2': [(6, 0, [team.filtered(
                                lambda x: (x.week == '1')).id] or False)],
                            'day_of_3': [(6, 0, [team.filtered(
                                lambda x: (x.week == '2')).id] or False)],
                            'day_of_4': [(6, 0, [team.filtered(
                                lambda x: (x.week == '3')).id] or False)],
                            'day_of_5': [(6, 0, [team.filtered(
                                lambda x: (x.week == '4')).id] or False)],
                            'day_of_6': [(6, 0, [team.filtered(
                                lambda x: (x.week == '5')).id] or False)],
                            'day_of_7': [(6, 0, [team.filtered(
                                lambda x: (x.week == '6')).id] or False)],
                            'course_id': team.class_name.course_id.id,
                            'course_line_id': team.course_line_id.id,
                            'order_id': work_ids.id,
                            'class_time': [(6, 0, session_id.ids)],
                            'date': date,
                            'time_detail': hour,
                        })
                    else:
                        week_int = int(team.week)
                        day_of = {
                            'day_of_1': 0,
                            'day_of_2': 1,
                            'day_of_3': 2,
                            'day_of_4': 3,
                            'day_of_5': 4,
                            'day_of_6': 5,
                            'day_of_7': 6
                        }
                        for key, vals in day_of.items():
                            if day_of[key] == week_int:
                                work_lines.write({
                                    key: [(4, team.id)]
                                })
            self.clear_empety_class_time(classtime_id.class_name, team_id)
        return team_id

    @api.multi
    def cancel_conflict(self, teacher):
        for team in self:
            team_teacher_conflict = self.env['class.timetable.team'].search(
                [('date', '=', team.date), ('state', '=', 'open'), ('id', '!=', team.id),
                 ('class_time_begin', '=', team.class_time_begin.ids), ('conflict_teacher', '=', True)])
            if len(team_teacher_conflict) == 1:
                check_conflict = []
                check_teacher = team_teacher_conflict.teacher1_id or team_teacher_conflict.teacher_id
                if check_teacher.id == teacher.id:
                    team_teacher_conflict.conflict_teacher = 0
                    check_conflict.extend([team, team_teacher_conflict])
                    self.env['jt.batch.conflict'].all_conflict_lines(check_conflict, create=0, type_m='teacher')
            else:
                self.env['jt.batch.conflict'].all_conflict_lines(team, create=0, type_m='teacher')

    @api.multi
    def cancel_arrange_teacher(self):
        for team in self:
            teacher = team.teacher1_id or team.teacher_id
            if team.conflict_teacher == 1 and not any(team.teacher1_id):
                team.cancel_conflict(teacher)
                team.conflict_teacher = 0
            team.teacher_id = False
            for timetable in team.class_timetable:
                timetable.update({
                    'teacher': False
                })

    @api.multi
    def cancel_arrange_teacher1(self):
        for team in self:
            teacher = team.teacher1_id
            if team.conflict_teacher == 1:
                team.cancel_conflict(teacher)
            team.teacher1_id = False
            for timetable in team.class_timetable:
                timetable.update({
                    'teacher1': False
                })
            if any(team.teacher_id):
                self.env['jt.batch.class.conflict'].check_conflict_teacher(team)

    @api.multi
    def cancel_arrange_room(self):
        for team in self:
            team_room_conflict = self.env['class.timetable.team'].search(
                [('date', '=', team.date), ('state', '=', 'open'), ('id', '!=', team.id),
                 ('class_time_begin', '=', team.class_time_begin.ids), ('room_id', '=', team.room_id.id)])
            if len(team_room_conflict) == 1:
                check_conflict = []
                team_room_conflict.conflict_room = 0
                check_conflict.append(team)
                check_conflict.append(team_room_conflict)
                self.env['jt.batch.conflict'].all_conflict_lines(check_conflict, create=0, type_m='room')
            else:
                self.env['jt.batch.conflict'].all_conflict_lines(team, create=0, type_m='room')
            team.conflict_room = 0
            team.room_id = False
            for timetable in team.class_timetable:
                timetable.update({
                    'class_room': False
                })

    # @api.multi
    # def arrange_teacher1_to_class(self):
    #     for team in self:
    #         teacher = team.teacher1_id
    #         for timetable in team.class_timetable:
    #             timetable.update({
    #                 'teacher1': teacher.id
    #             })

    @api.multi
    def arrange_teacher1_to_class(self):
        team_line = self.env.context.get('default_team_id')
        team = self.env['class.timetable.team'].browse(team_line)
        # active_id = self.env.context.get('active_id')
        work_line = self.env['jt.batch.class.line'].browse(self.env.context.get('active_id'))
        work_line.with_context(t1_date=[team.date])
        return work_line.get_conflict([team.date], [team.date], team.class_time_begin.ids, team, teacher1=True)

    @api.multi
    def arrange_room(self):
        for team in self:
            room_id = team.room_id
            for timetable in team.class_timetable:
                timetable.update({
                    'class_room': room_id.id
                })