# _*_ coding: utf-8 _*_
# Author: Monica( nikochild@gmail.com)

from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError
from itertools import groupby


class JtBatchClassConflict(models.Model):
    _name = 'jt.batch.class.conflict'

    name = fields.Char()
    conflict = fields.Text(string='狀態')
    have_class = fields.Text(string='上課')
    teacher_id = fields.Many2one('jt.teacher', string='講師')
    show_team_id = fields.Boolean()
    class_line = fields.Many2one('jt.batch.class.line', ondelete='cascade')
    type = fields.Selection(selection=([('OK', '符合'), ('NO', '不符合')]), string='Status', copy=False, index=True)
    team_id = fields.Many2many('class.timetable.team')

    @api.multi
    def check_conflict_teacher(self, teams):
        team_obj = self.env['class.timetable.team']
        for team in teams:
            team_teacher = team.teacher1_id or team.teacher_id
            check_team_conflict = []
            team_teacher_conflict = team_obj.search(
                [('date', '=', team.date), ('state', '=', 'open'), ('id', '!=', team.id),
                 ('class_time_begin', 'in', team.class_time_begin.ids),('work_line_id','!=',False)])
            if any(team_teacher_conflict):
                # 有設定代講或講師
                filtered_conflict = team_teacher_conflict.filtered(lambda x: any([x.teacher_id, x.teacher1_id]))
                if any(filtered_conflict):
                    for conflict_team in filtered_conflict:
                        conflict_team_teacher = conflict_team.teacher1_id or conflict_team.teacher_id
                        # 有衝突
                        if conflict_team_teacher.id == team_teacher.id:
                            team.conflict_teacher = 1
                            conflict_team.conflict_teacher = 1
                            check_team_conflict.append(conflict_team)
                            check_team_conflict.append(team)
                if any(check_team_conflict):
                    self.env['jt.batch.conflict'].all_conflict_lines(check_team_conflict, create=1,
                                                                     type_m='teacher')
            # 原本是有衝突,上面檢查沒有
            if team.conflict_teacher == 1 and not any(check_team_conflict):
                team.conflict_teacher = 0
                self.env['jt.batch.conflict'].all_conflict_lines(team, create=0, type_m='teacher')

    @api.multi
    def arrange_teacher_to_class(self):
        teacher = self.teacher_id
        team_obj = self.env['class.timetable.team']
        set_teacher, set_room, duration_ids, team_line = self.class_line.have_class_teacher(self.class_line.id)
        time_t = team_obj.search(
            [('work_line_id', '=', self.class_line.id), ('state', '=', 'open'),
             ('date', 'in', set_teacher)])
        if any(time_t):
            no_teacher_team = time_t.filtered(lambda x: not any(x.teacher_id))
            if any(no_teacher_team):
                for team_teacher in no_teacher_team:
                    team_teacher.teacher_id = teacher.id
                    timetable = team_teacher.class_timetable
                    for timet in timetable:
                        timet.update({
                            'teacher': teacher.id
                        })
                self.check_conflict_teacher(no_teacher_team)
            else:
                raise UserError('請先取消講師設定')


    @api.multi
    def arrange_teacher1_to_class(self):
        teacher = self.teacher_id
        time_t = self.team_id
        if any(time_t):
            no_teacher1_team = time_t.filtered(lambda x: not any(x.teacher1_id))
            if any(no_teacher1_team):
                for team_teacher in no_teacher1_team:
                    team_teacher.teacher1_id = teacher.id
                    timetable = team_teacher.class_timetable
                    for timet in timetable:
                        timet.update({
                            'teacher1': teacher.id
                        })
                self.check_conflict_teacher(no_teacher1_team)
            else:
                raise UserError('請先取消代講設定')


class JtBatchRoomConflict(models.Model):
    _name = 'jt.batch.room.conflict'

    name = fields.Char()
    conflict = fields.Text(string='狀態')
    have_class = fields.Text(string='上課')
    room_id = fields.Many2one('jptip.class.room', string='教室')
    class_line = fields.Many2one('jt.batch.class.line', ondelete='cascade')
    type = fields.Selection(selection=([('OK', '符合'), ('NO', '不符合')]), string='Status', copy=False, index=True)

    @api.multi
    def check_conflict_room(self, teams):
        team_obj = self.env['class.timetable.team']
        for team in teams:
            check_team_conflict = []
            if any(team.room_id):
                team_room_conflict = team_obj.search(
                    [('date', '=', team.date), ('state', '=', 'open'), ('id', '!=', team.id),
                     ('class_time_begin', 'in', team.class_time_begin.ids), ('room_id', '=', team.room_id.id)])
                if any(team_room_conflict):
                    for conflict_team in team_room_conflict:
                        team.conflict_room = 1
                        conflict_team.conflict_room = 1
                        check_team_conflict.append(conflict_team)
                        check_team_conflict.append(team)
                if any(check_team_conflict):
                    self.env['jt.batch.conflict'].all_conflict_lines(check_team_conflict, create=1,
                                                                     type_m='room')
                if team.conflict_room == 1 and not any(check_team_conflict):
                    team.conflict_teacher = 0
                    self.env['jt.batch.conflict'].all_conflict_lines(team, create=0, type_m='room')

    @api.multi
    def arrange_room(self):
        room = self.room_id
        team_obj = self.env['class.timetable.team']
        set_teacher, set_room, duration_ids, team_line = self.class_line.have_class_teacher(self.class_line.id)
        time_t = team_obj.search(
            [('work_line_id', '=', self.class_line.id), ('state', '=', 'open'),
             ('date', 'in', set_room)])
        if any(time_t):
            no_room_team = time_t.filtered(lambda x: not any(x.room_id))
            if any(no_room_team):
                for team_room in no_room_team:
                    team_room.room_id = room.id
                    timetable = team_room.class_timetable
                    for timet in timetable:
                        timet.update({
                            'class_room': room.id
                        })
                self.check_conflict_room(no_room_team)


class JtBatchConflict(models.Model):
    _name = 'jt.batch.conflict'

    name = fields.Char()
    class_line = fields.Many2one('jt.batch.class.line')
    team_id = fields.Many2many('class.timetable.team')
    order_id = fields.Many2one('jt.batch.class', required=True, ondelete='cascade')
    class_name = fields.Many2one('jt.batch', string='班級名稱')
    course_id = fields.Many2one('jt.course', string='課程系列')
    course_line_id = fields.Many2one('jt.course.line', string='課程級數')
    str_of_1 = fields.Text(string='星期一', compute='_get_str_of')
    str_of_2 = fields.Text(string='星期二', compute='_get_str_of')
    str_of_3 = fields.Text(string='星期三', compute='_get_str_of')
    str_of_4 = fields.Text(string='星期四', compute='_get_str_of')
    str_of_5 = fields.Text(string='星期五', compute='_get_str_of')
    str_of_6 = fields.Text(string='星期六', compute='_get_str_of')
    str_of_7 = fields.Text(string='星期日', compute='_get_str_of')
    type = fields.Selection(selection=([('teacher', 'Teacher'), ('room', 'Room')]), string='Status', copy=False,
                            index=True)

    @api.multi
    def show_work_line(self):
        return {
            'res_id': self.class_line.id,
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'jt.batch.class.line',
            'view_id': self.env.ref('jptip_core.jt_batch_class_line_form_view').id,
            'type': 'ir.actions.act_window',
        }

    @api.multi
    def all_conflict_lines(self, team_lines, create, type_m):
        for team in team_lines:
            lines = self.search(
                [('class_line', '=', team.work_line_id.id), ('class_name', '=', team.class_name.id),
                 ('course_line_id', '=', team.course_line_id.id), ('type', '=', type_m)])
            if create == 1:
                if not any(lines):
                    lines = self.create({
                        'class_line': team.work_line_id.id,
                        'order_id': team.work_line_id.order_id.id,
                        'class_name': team.class_name.id,
                        'course_line_id': team.course_line_id.id,
                        'type': type_m,
                    })
                lines.update({
                    'team_id': [(4, team.id)]
                })
            else:
                if any(lines):
                    lines.update({
                        'team_id': [(2, team.id)]
                    })
                if not any(lines.team_id):
                    lines.unlink()

    @api.multi
    def _get_str_of(self):
        for str_of in self:
            day_of = {
                '0': ['str_of_1'],
                '1': ['str_of_2'],
                '2': ['str_of_3'],
                '3': ['str_of_4'],
                '4': ['str_of_5'],
                '5': ['str_of_6'],
                '6': ['str_of_7'],
            }
            for key, str in day_of.items():
                teacher_obj = self.env['jt.teacher']
                teams = str_of.team_id.filtered(lambda x: x.week == key)
                if any(teams):
                    a = list()
                    n = len(teams)
                    str_by_t = ''
                    day_date = ''
                    have_t_class = 0
                    all_class = 0
                    for team in teams:
                        teacher = 0
                        all_class += len(team.class_timetable.ids)
                        type = u'未排講師'
                        if any(team.teacher_id):
                            teacher = team.teacher_id.id
                            type = u'講師'
                            have_t_class += len(team.class_timetable.ids)
                        if any(team.teacher1_id):
                            teacher = team.teacher1_id.id
                            type = u'代講'
                            have_t_class += len(team.class_timetable.ids)
                        val = ({
                            'date': '%s(%s)\n' % (team.date[5:], team.room_id.name or ''),
                            'teacher': teacher,
                            'type': type,
                        })
                        a.append(val)
                    i = 0
                    while i <= n:
                        day_date += a[i]['date']
                        name = teacher_obj.browse(a[i]['teacher'])
                        if n > 1:
                            if a[i]['type'] != a[i + 1]['type']:
                                if any(name):
                                    str_by_t += '%s%s:%s\n' % (day_date, a[i]['type'], name.name)
                                    day_date = ''
                                else:
                                    str_by_t += '%s%s\n' % (day_date, a[i]['type'])
                                    day_date = ''
                            else:
                                if a[i]['teacher'] != a[i + 1]['teacher']:
                                    if any(name):
                                        str_by_t += '%s%s:%s\n' % (day_date, a[i]['type'], name.name)
                                        day_date = ''
                                    else:
                                        str_by_t += '%s%s\n' % (day_date, a[i]['type'])
                                        day_date = ''
                            i += 1
                            if i == n - 1:
                                name = teacher_obj.browse(a[i]['teacher'])
                                day_date += a[i]['date']
                                if any(name):
                                    str_by_t += '%s%s:%s\n' % (day_date, a[i]['type'], name.name)
                                else:
                                    str_by_t += '%s%s\n' % (day_date, a[i]['type'])
                                i += 2
                        else:
                            name = teacher_obj.browse(a[i]['teacher'])
                            if any(name):
                                str_by_t += '%s%s:%s\n' % (day_date, a[i]['type'], name.name)
                            else:
                                str_by_t += '%s%s\n' % (day_date, a[i]['type'])
                            i += 2
                    str_of[str[0]] = str_by_t
