# _*_ coding: utf-8 _*_
# Author: Monica( nikochild@gmail.com)
from odoo import models, fields, api
from dateutil.relativedelta import relativedelta
from datetime import datetime, timedelta
from odoo.exceptions import ValidationError

class NewModule(models.Model):
    _name = 'jptip.event.category'
    _rec_name = 'name'
    _description = '活動類別'

    name = fields.Char()


class JptipEvent(models.Model):
    _name = 'jptip.event'
    _rec_name = 'name'
    _description = '活動事件管理'

    name = fields.Char(string='活動名稱')
    event_description = fields.Text(string='活動說明')
    event_date = fields.Datetime(string='活動日期', default=fields.Datetime.now())
    event_time = fields.Many2one('jt.time.session.manager', string='時段')
    event_categ = fields.Many2one('jptip.event.category', string='活動類別')
    event_class_room = fields.Many2one('jptip.class.room', string='教室')
    event_teacher = fields.Many2one('jt.teacher', string='老師')
    event_note = fields.Char(string='註記')
    event_timetable = fields.One2many('class.timetable', 'event_id', string='課表')
    event_select = fields.Many2many('class.timetable', string='衝突查詢結果')
    event_course = fields.Many2one('jt.course', string='課程')
    event_batch = fields.Many2one('jt.batch', string='班級')
    state = fields.Selection(selection=([('draft', '草稿'), ('ing', '活動')]), string='Status',
                             copy=False, default='draft', index=True, readonly=True, )
    company_id = fields.Many2one(related='event_batch.company_id', string='Company', store=True, readonly=True)
    event_id = fields.Many2one('event.plan')
    event_tree_domain = fields.Many2many('jptip.class.room', string='event_tree_domain', compute='onchange_event_date')
    event_tree_domain_teacher = fields.Many2many('jt.teacher', string='event_tree_domain', compute='onchange_event_date')

    @api.multi
    def check_event_time(self):
        time = self.event_time
        date = self.event_date
        course = self.event_course
        class_room = self.event_class_room
        teacher = self.event_teacher
        domain = [('date', '=', date), ('state', '=', 'open'), ('class_time_begin', '=', time.id), ('company_id', '=', self.env.user.company_id.id)]
        # if any(course):
        #     domain += [('course_line_id.course_id', '=', course.id)]
        if any(class_room):
            domain += ['|',('class_room', '=', class_room.id)]
        if any(teacher):
            domain += [('teacher', '=', teacher.id),('teacher1','=', False)]
            domain += ['|', ('teacher', '!=', False), ('teacher1', '=', teacher.id)]
        check = self.env['class.timetable'].search(domain)
        check_id = [check_id.id for check_id in check]
        self.update({
            'event_select': [(6, 0, check_id)]
        })
        return True

    @api.multi
    def _time_to_str(self):
        today = fields.datetime.now() + timedelta(hours=8)
        time = datetime.strftime(today, '%H:%M')
        return time

    @api.multi
    def cache_time_table(self):
        event_id = self.env['jptip.event'].browse(self.env.context.get('active_id'))
        for timetable in self:
            timetable.update({
                'event_id': event_id.id,
                'event': 1
            })

    @api.multi
    def creat_event_timetable(self, values):
        timetable_obj = self.env['class.timetable']
        if not self.event_time:
            raise ValidationError(u'請輸入時段')
        if not self.event_categ:
            raise ValidationError(u'請輸入活動類別')
        if not self.event_course:
            raise ValidationError(u'請輸入課程')
        if not self.event_batch:
            raise ValidationError(u'請輸入班級')
        if not any(self.event_timetable):
            timetable = timetable_obj.create({
                'class_name': self.event_batch.id,
                'teacher': self.event_teacher.id,
                'date': self.event_date,
                'class_room': self.event_class_room.id,
                'event': 1,
                'sequence': 1,
                'class_time_begin': self.event_time.id,
                'event_id': self.id,
                'state': 'open',
                'company_id': self.env.user.company_id.id,
            })
            self.update({'event_timetable': [(6, 0, [timetable.id])]})
            self.event_team(timetable)
        self.state = 'ing'
        return True

    @api.multi
    def event_team(self, event_timetable):
        team_obj = self.env['class.timetable.team']
        return team_obj.get_team(event_timetable)

    @api.onchange('event_date','event_time')
    def onchange_event_date(self):
        for row in self:
            if row.event_date and row.event_time:
                doc = []
                teacher = []
                class_timetable_id = self.env['class.timetable'].search([('date', '=', row.event_date), ('state', '=', 'open'), ('class_time_begin', '=', row.event_time.id), ('company_id', '=', self.env.user.company_id.id)])
                for line in class_timetable_id:
                    if line.class_room.id not in doc:
                        doc.append(line.class_room.id)
                for line in class_timetable_id:
                    if line.teacher.id not in teacher:
                        teacher.append(line.teacher.id)
                    if line.teacher1.id not in teacher:
                        teacher.append(line.teacher1.id)
                date = datetime.strptime(row.event_date, '%Y-%m-%d %H:%M:%S').strftime("%Y-%m-%d").split(' ')
                jt_batch_id = self.env['jt.teacher.batch'].search([('company_id', '=', self.env.user.company_id.id),('year','=',str(datetime.strptime(date[0], '%Y-%m-%d').year)), ('month','=',str(datetime.strptime(date[0], '%Y-%m-%d').month))], limit=1)
                result = {}
                class_room = self.env['jptip.class.room'].search([('id','not in', doc), ('company_id', '=', self.env.user.company_id.id)])
                teacher_setting = self.env['jt.teacher'].search([('id','not in', teacher), ('company_id', '=', self.env.user.company_id.id)])
                timing_id = self.env['jt.timing.manager'].search([('company_id', '=', self.env.user.company_id.id)])
                time_session = None
                for x in timing_id:
                    temp = []
                    for y in x.session_ids:
                        if y.id not in temp:
                            temp.append(y.id)
                    if row.event_time.id in temp:
                        time_session = x.id
                teacher = []
                for x in teacher_setting:
                    sql = "SELECT teacher_id FROM jt_teacher_batch_line1 WHERE teacher_id = %s AND company_id = %s AND order_id = %s AND date_%s = %s" % (x.id, self.env.user.company_id.id, jt_batch_id.id, str(datetime.strptime(date[0], '%Y-%m-%d').day), time_session)
                    self._cr.execute(sql)
                    for y in self._cr.dictfetchall():
                        if int(y['teacher_id']) not in teacher:
                            teacher.append(int(y['teacher_id']))
                teacher_setting = self.env['jt.teacher'].search([('id', 'in', teacher), ('company_id', '=', self.env.user.company_id.id)])
                result['domain'] = {'event_class_room': [('id', 'not in', doc), ('company_id', '=', self.env.user.company_id.id)], 'event_teacher': [('id', 'in', teacher), ('company_id', '=', self.env.user.company_id.id)]}
                row.event_tree_domain = [(6, 0,class_room.ids )]  # tree view 專用 domain
                row.event_tree_domain_teacher = [(6, 0, teacher_setting.ids)]  # tree view 專用 domain
                return result