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

class SaleOrder(models.Model):
    _inherit = "sale.order"

    @api.multi
    def action_view_class(self):
        action = self.env.ref('jp_sale_product.select_class_action').read()[0]
        r = []
        for line in self.order_line:
            r.append([0, 0, {
                'product_id': line.product_id.id,
                'name': line.product_id.name,
                'class_name': line.class_name.id,
                'start_class_course_num': line.start_class_course_num,
                'end_class_course_num': line.end_class_course_num,
                'class_name_domain': [(6, 0, line.class_name_domain.ids)],
                'is_admission': line.is_admission,
                'course_line_id': line.course_line_id.id,
            }])
        action['context'] = {'default_order_line': r}
        return action

    @api.multi
    def write(self, vals):
        res = super(SaleOrder, self).write(vals)
        # if 'product_id' in vals and self.state == 'draft':
        #     self.change_student_batch()
        return res

    @api.multi
    def action_cancel(self):
        for line in self.order_line:
            line.st_batch_ids.unlink()
        res = super(SaleOrder, self).action_cancel()
        return res

    @api.multi
    def action_confirm(self):
        self.confirm_student_batch()
        res = super(SaleOrder, self).action_confirm()
        return res

    @api.multi
    def confirm_student_batch(self):
        # st_batch_id = []
        student_obj = self.env['jt.student']
        student_id = student_obj.search([('partner_id', '=', self.partner_id.id)])
        gender = ''
        if self.partner_id.sex == '1':
            gender = 'm'
        elif self.partner_id.sex == False:
            gender = False
        elif self.partner_id.sex == '2':
            gender = 'f'
        if not student_id:
            student_obj.create({
                'name': self.partner_id.name,
                'partner_id': self.partner_id.id,
                'company_id': self.env.user.company_id.id,
                'phone_number1': self.partner_id.phone,
                'cellphone': self.partner_id.mobile,
                'email': self.partner_id.email,
                'address': self.partner_id.street,
                'birth_date': self.partner_id.birthday,
                'gender': gender,
                'edu_level': self.partner_id.experience.id
            })
        student_id = student_obj.search([('partner_id', '=', self.partner_id.id)])
        today = fields.datetime.now() + timedelta(hours=8)
        time = datetime.strftime(today, '%Y-%m-%d')
        for item in self.order_line:
            if item.class_name:
                student_batch_lines = {
                    'batch_id': item.class_name.id,
                    'student_id': student_id.id,
                    'name': student_id.name,
                    'add_date': time,
                    'course_line_id': item.product_id.start_class_course.id,
                    'start_class_course_num': item.start_class_course_num,
                    'end_class_course_num': item.end_class_course_num,
                    'state': 'ing',
                    'order_id': item.order_id.id,
                    'sale_line_id': item.id
                }
                self.env['jt.student.batch'].create(student_batch_lines)
                item.is_admission = True

    # @api.multi
    # def change_student_batch(self):
    #     # st_batch_id = []
    #     student_obj = self.env['jt.student']
    #     student_id = student_obj.search([('partner_id', '=', self.partner_id.id)])
    #     today = fields.datetime.now() + timedelta(hours=8)
    #     time = datetime.strftime(today, '%Y-%m-%d')
    #     for item in self.order_line:
    #         student_batch_data = self.env['jt.student.batch'].search(
    #             [('order_id', '=', self.id), ('student_id', '=', student_id.id)])
    #         if self.state == 'draft' and any(student_batch_data) == False:
    #             student_batch_lines = {
    #                 'batch_id': item.product_id.batch_id,
    #                 'student_id': student_id.id,
    #                 'add_date': time,
    #                 'state': 'draft',
    #                 'order_id': item.order_id.id
    #             }
    #             self.env['jt.student.batch'].create(student_batch_lines)
    #         else:
    #             student_batch_data = self.env['jt.student.batch'].search(
    #                 [('order_id', '=', self.id), ('student_id', '=', student_id.id)])
    #             student_obj.change_batch(item, student_id, student_batch_data)

class SaleOrderLine(models.Model):
    _inherit = "sale.order.line"

    course_line_id = fields.Many2one('jt.course.line', string='級數')
    class_name = fields.Many2one('jt.batch', string='班級')
    class_name_domain = fields.Many2many('jt.batch', string='class_domain')
    start_class_course_num = fields.Integer(string='開始堂數', default=1)
    end_class_course_num = fields.Integer(string='結束堂數')
    date_from = fields.Date(string='開始日期')
    date_to = fields.Date(string='結束日期')
    st_batch_ids = fields.One2many('jt.student.batch', 'sale_line_id', string='Student Batch')
    is_admission = fields.Boolean(string='是否已入班', default=False)
    is_course = fields.Boolean(string='是否為課程', relate='product_id.product_tmpl_id.is_course', store=True)
    class_name_tree_domain = fields.Many2many('jt.batch', string='class_tree_domain', compute='course_detail_onchange')
    is_transfer_crm = fields.Boolean(string='已轉入續報商機', default=False)

    def transfer_crm_batch(self,ids):
        res = []
        for line in ids:
            res.append([4, line])
        data = self.env['transfer.crm.batch'].create({
            'batch_line': res
        })
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'transfer.crm.batch',
            'name': '轉入CRM商機',
            'view_type': 'form',
            'view_mode': 'form',
            'res_id': data.id,
            'target': 'new',
        }

    def not_admission_method(self):
        self.st_batch_ids.unlink()
        if self.is_admission:
            self.is_admission = False

    def is_admission_method(self):
        if not self.is_admission:
            student_obj = self.env['jt.student']
            student_id = student_obj.search([('partner_id', '=', self.partner_id.id)])
            gender = ''
            if self.partner_id.sex == '1':
                gender = 'm'
            elif self.partner_id.sex == False:
                gender = False
            elif self.partner_id.sex == '2':
                gender = 'f'
            if not student_id:
                student_obj.create({
                    'name': self.partner_id.name,
                    'partner_id': self.partner_id.id,
                    'company_id': self.env.user.company_id.id,
                    'phone_number1': self.partner_id.phone,
                    'cellphone': self.partner_id.mobile,
                    'email': self.partner_id.email,
                    'address': self.partner_id.street,
                    'birth_date': self.partner_id.birthday,
                    'gender': gender,
                    'edu_level': self.partner_id.experience.id
                })
            student_id = student_obj.search([('partner_id', '=', self.partner_id.id)])
            if student_id:
                today = fields.datetime.now() + timedelta(hours=8)
                time = datetime.strftime(today, '%Y-%m-%d')
                for item in self:
                    if item.class_name:
                        student_batch_lines = {
                            'batch_id': item.class_name.id,
                            'student_id': student_id.id,
                            'name': student_id.name,
                            'add_date': time,
                            'course_line_id': item.product_id.start_class_course.id,
                            'start_class_course_num': item.start_class_course_num,
                            'end_class_course_num': item.end_class_course_num,
                            'state': 'ing',
                            'order_id': item.order_id.id,
                            'sale_line_id': item.id
                        }
                        self.env['jt.student.batch'].create(student_batch_lines)
                        item.is_admission = True
                    elif not item.class_name:
                        raise ValidationError(u'請選擇班級')

    @api.onchange('product_id')
    def course_classes_onchange(self):
        if self.product_id:
            self.end_class_course_num = self.product_id.classes
            self.is_course = self.product_id.product_tmpl_id.is_course

    @api.multi
    @api.onchange('product_id')
    def course_detail_onchange(self):
        outline_obj = self.env['jt.batch.outline']
        for line in self:
            outlines = outline_obj.search(
                [('course_line_id', '=', line.product_id.start_class_course.id),
                 ('date_from', '>=', fields.date.today())])
            if any(outlines):
                class_name = self.env['jt.batch'].search(
                    [('jt_batch_outline', 'in', outlines.ids), ('class_state', '=', 'ing')])
                # line.class_name = class_name[0].id
                line.class_name_domain = [(6, 0, class_name.ids)]
                line.class_name_tree_domain = [(6, 0, class_name.ids)] # tree view 專用 domain

    @api.multi
    @api.onchange('class_name')
    def num_onchange(self):
        for line in self:
            outline = line.class_name.jt_batch_outline.filtered(
                lambda x: line.product_id.start_class_course.id == x.course_line_id.id)
            if any(outline):
                line.start_class_course_num = outline.start_class_course_num
                line.end_class_course_num = outline.end_class_course_num
                line.date_from = outline.date_from
                line.date_to = outline.date_to
                # line.name = '%s \n %s' %(line.class_name.name,ouline.duration)

    @api.multi
    @api.onchange('start_class_course_num')
    def course_couse_num_onchange(self):
        if self.class_name:
            class_timetable = self.env['class.timetable'].search(
                [('course_line_id', '=', self.product_id.start_class_course.id),
                 ('class_name', '=', self.class_name.id),
                 ('sequence', '=', self.start_class_course_num)])
            self.date_from = class_timetable.date

    @api.multi
    @api.onchange('end_class_course_num')
    def course_couse_num_onchange(self):
        if self.class_name:
            class_timetable = self.env['class.timetable'].search(
                [('course_line_id', '=', self.product_id.start_class_course.id),
                 ('class_name', '=', self.class_name.id),
                 ('sequence', '=', self.end_class_course_num)])
            self.date_to = class_timetable.date

    @api.multi
    @api.onchange('product_id')
    def product_id_change(self):
        if not self.product_id:
            return {'domain': {'product_uom': []}}

        vals = {}
        domain = {'product_uom': [('category_id', '=', self.product_id.uom_id.category_id.id)]}
        if not self.product_uom or (self.product_id.uom_id.id != self.product_uom.id):
            vals['product_uom'] = self.product_id.uom_id
            vals['product_uom_qty'] = 1.0

        product = self.product_id.with_context(
            lang=self.order_id.partner_id.lang,
            partner=self.order_id.partner_id.id,
            quantity=vals.get('product_uom_qty') or self.product_uom_qty,
            date=self.order_id.date_order,
            pricelist=self.order_id.pricelist_id.id,
            uom=self.product_uom.id
        )

        result = {'domain': domain}

        title = False
        message = False
        warning = {}
        if product.sale_line_warn != 'no-message':
            title = _("Warning for %s") % product.name
            message = product.sale_line_warn_msg
            warning['title'] = title
            warning['message'] = message
            result = {'warning': warning}
            if product.sale_line_warn == 'block':
                self.product_id = False
                return result

        name = product.name_get()[0][1]
        start_class_course = product.start_class_course
        if product.description_sale:
            name += '\n' + product.description_sale
        vals['name'] = name
        vals['course_line_id'] = product.start_class_course.id
        # vals['start_class_course_num'] = product.batch_id.start_class_course_num
        # vals['end_class_course_num'] = product.batch_id.end_class_course_num or start_class_course.class_num
        self._compute_tax_id()

        if self.order_id.pricelist_id and self.order_id.partner_id:
            vals['price_unit'] = self.env['account.tax']._fix_tax_included_price_company(
                self._get_display_price(product), product.taxes_id, self.tax_id, self.company_id)

        self.update(vals)

        return result