# _*_ coding: utf-8 _*_
# Author: JasonWu( Jaronemo@msn.com)
from odoo import models, fields, api


class JptipTeacher(models.Model):
    """ Defining a Teacher information """
    _name = 'jt.teacher'
    _description = 'Teacher Information'

    # partner_id = fields.Many2one('res.partner', 'Partner ID',
    #                              ondelete="cascade",
    #                              delegate=True, required=True)
    name = fields.Char(index=True)
    display_name = fields.Char(compute='_compute_display_name', store=True, index=True)
    partner_id = fields.Many2one('res.partner', 'Partner ID')
    work_phone = fields.Char('電話')
    mobile_phone = fields.Char('行動電話')
    work_email = fields.Char('E-mail')
    faculty_subject_ids = fields.One2many('jt.teacher.line', 'order_id', string='授課列表')
    company_id = fields.Many2one('res.company', '公司',
                                 default=lambda self: self.env['res.company']._company_default_get())

    @api.onchange('partner_id')
    def onchange_partner_id(self):
        for line in self:
            if line.partner_id:
                line.name = line.partner_id.name
                line.company_id = self.env.user.company_id.id
                line.mobile_phone = line.partner_id.mobile
                line.work_phone = line.partner_id.phone
                line.work_email = line.partner_id.email

    @api.depends('company_id', 'name')
    def _compute_display_name(self):
        diff = dict(show_address=None, show_address_only=None, show_email=None)
        names = dict(self.with_context(**diff).name_get())
        for teacher in self:
            teacher.display_name = names.get(teacher.id)
    # @api.model
    # def create(self, vals):
    #     teacher_id = super(JptipTeacher, self).create(vals)
    #     teacher_obj = self.env['res.partner']
    #     teacher_vals = {
    #         'name': teacher_id.name,
    #         'email': teacher_id.work_email,
    #     }
    #     user_id = teacher_obj.create(teacher_vals)
    #     return teacher_id


class JtTeacherLine(models.Model):
    _name = 'jt.teacher.line'
    _description = '用来展示授课列表明细'
    _order = 'order_id, id'

    order_id = fields.Many2one('jt.teacher', string='参照老师主表', required=True, ondelete='cascade', index=True,
                               copy=False)
    course_id = fields.Many2one('jt.course', string='課程系列')
    name = fields.Char('系列名稱', related='course_id.name', store=True, readonly=True)
    code = fields.Char('系列代碼(前置)', related='course_id.code', store=True, readonly=True)
    course_begin_code = fields.Many2many('jt.course.line', string='開始')
    company_id = fields.Many2one(related='order_id.company_id', string='Company', store=True, readonly=True)

    @api.multi
    @api.onchange('course_id')
    def course_line_onchange(self):
        if self.course_id:
            self.course_begin_code = [(6, 0, self.course_id.course_ids.ids)]
