# _*_ coding: utf-8 _*_
# Author: JasonWu( Jaronemo@msn.com)

from odoo import models, fields, api, _
from datetime import datetime, date
import calendar
from odoo.exceptions import UserError, ValidationError
from dateutil.relativedelta import relativedelta
import logging
from io import BytesIO

_logger = logging.getLogger(__name__)
try:
    import xlsxwriter
except ImportError:
    _logger.debug('Can not import xlsxwriter`.')


class JtTeacherBatch(models.Model):
    _name = 'jt.teacher.batch'
    _description = '老師排課'

    name = fields.Char(string='排課區間')
    month = fields.Char(string='月份', required=True, default=datetime.now().strftime('%m'))
    year = fields.Char('年份', required=True, default=datetime.now().strftime('%Y'))
    date_from = fields.Date(string='起：')
    date_to = fields.Date(string='迄：')
    line_ids = fields.One2many('jt.teacher.batch.line', 'order_id', compute='_compute_line_ids')
    # total_count = fields.Float(compute='_compute_total_count', store=True, )
    teacher_ids = fields.One2many('jt.teacher', 'partner_id', string='老師列表', readonly=True)
    state = fields.Selection(selection=[('1', '待排課'), ('2', '排課中'), ('3', '老師確認'), ('4', '完成排課')], string='狀態', default='1')
    company_id = fields.Many2one('res.company', 'Company',
                                 default=lambda self: self.env['res.company']._company_default_get())

    @api.constrains('date_from', 'date_to')
    def _check_start_end_dates(self):
        for sheet in self:
            if sheet.date_from > sheet.date_to:
                raise ValidationError(
                    _('啟始日不得大於結束日'))

    @api.constrains('date_from', 'date_to')
    def _check_sheet_date(self):
        for sheet in self:
            self.env.cr.execute(
                """
                SELECT id
                FROM jt_teacher_batch
                WHERE (date_from <= %s and %s <= date_to) AND company_id = %s 
                    AND id <> %s""",
                (sheet.date_to, sheet.date_from, sheet.company_id.id, sheet.id))
            if any(self.env.cr.fetchall()):
                raise ValidationError(
                    _('你不能有兩張重疊的時間表！\n'
                      '請使用菜單 \'時間表單\' '
                      '避免這個問題。'))

    @api.onchange('month')
    def onchange_month(self):
        if self.month:
            month_date = date(int(self.year), int(self.month), 1)

            self.date_from = month_date.replace(day=1)

            self.date_to = month_date.replace(day=calendar.monthrange(month_date.year, month_date.month)[1])

    @api.multi
    def _compute_line_ids(self):
        for sheet in self:
            if not all([sheet.date_from, sheet.date_to]):
                continue
            dates = sheet._get_dates()
            if not dates:
                continue
            timesheets = self.env['jt.teacher'].search([
                ('id', '!=', False),
            ])
            lines = self.env['jt.teacher.batch.line']
            for date in dates:
                for teacher in timesheets.mapped('id'):
                    timesheet = timesheets.filtered(
                        lambda x: (x.id == teacher))

                    lines |= self.env['jt.teacher.batch.line'].create(
                        sheet._get_default_analytic_line(
                            date=date,
                            project=teacher,
                            project_name=timesheet.partner_id,

                        ))
            sheet.line_ids = lines

    def _get_date_name(self, date):
        return fields.Date.from_string(date).strftime("%a\n%b/%d")

    def _get_default_value(self):
        res = self.env['jt.timing.manager'].search([])
        return res and res[0].id or False

    def _get_default_analytic_line(self, date, project, project_name):
        name_y = self._get_line_name(project_name)

        values = {
            'value_x': self._get_date_name(date),
            'value_y': name_y,
            'date': date,
            'teacher_id': project,


        }
        if self.id:
            values.update({
                'order_id': self.id,
                'time_duration': self._get_default_value(),
            })

        return values

    def _get_line_name(self, project_name):
        name = '{}'.format(project_name.name)
        return name

    @api.onchange('date_from', 'date_to')
    def _onchange_dates(self):
        self._compute_line_ids()

    def _get_dates(self):
        start = fields.Date.from_string(self.date_from)
        end = fields.Date.from_string(self.date_to)
        if end < start:
            return []
        dates = [fields.Date.to_string(start)]
        while start != end:
            start += relativedelta(days=1)
            dates.append(fields.Date.to_string(start))
        return dates

    @api.multi
    def copy(self, default=None):
        raise UserError(_('You cannot duplicate a sheet.'))

    @api.model
    def create(self, vals):
        vals['name'] = str(vals['year']) + '/' + str(vals['month']) + ' ' + '(起：' + vals['date_from'] + '~' + '迄：' + \
                       vals['date_to'] + ')'
        if "year" in vals:
            if not vals["year"].isdigit():
                raise UserError("輸入的年份不正確，請重新檢測")
        res = super(JtTeacherBatch, self).create(vals)
        return res

    @api.multi
    def write(self, vals):
        if "year" in vals:
            if not vals["year"].isdigit():
                raise UserError("輸入的年份不正確，請重新檢測")
        res = super(JtTeacherBatch, self).write(vals)
        return res

    @api.multi
    def show_import_form(self):
        action = self.env.ref('jptip_core.jt_teacher_import_action').read()[0]
        action['views'] = [(self.env.ref('jptip_core.jt_teacher_import_form_view').id, 'form')]
        return action

    @api.multi
    def show_security_form(self):
        action = self.env.ref('report.jptip_core.security_report.security_action').read()[0]
        action['views'] = [(self.env.ref('report.jptip_core.security_report.security_form_view').id, 'form')]
        return action


class JtTeacherBatchLine(models.Model):
    _name = 'jt.teacher.batch.line'

    name = fields.Char()
    order_id = fields.Many2one('jt.teacher.batch', ondelete='cascade', )
    teacher_id = fields.Many2one('jt.teacher', string='老師')
    date = fields.Date(
        string='Date',
    )
    value_x = fields.Char(
        string='日期',
    )
    value_y = fields.Char(
        string='老師名稱',
    )
    time_duration = fields.Many2one('jt.timing.manager', string='時間表')
    count_timesheets = fields.Integer(
        default=0,
    )
    company_id = fields.Many2one(related='teacher_id.company_id', string='Company', store=True, readonly=True)


    def _create_timesheet(self, amount):
        values = self._line_to_timesheet(amount)
        if self.env['account.analytic.line'].create(values):
            self.count_timesheets += 1

    @api.model
    def _diff_amount_timesheets(self, amount, timesheets):
        for timesheet in timesheets:
            diff_amount = timesheet.unit_amount - amount
            if diff_amount >= 0.0:
                timesheet.unit_amount = diff_amount
                break
            else:
                amount -= timesheet.unit_amount
                timesheet.write({'unit_amount': 0.0})

    @api.model
    def _line_to_timesheet(self, amount):
        return {
            'name': '/',
            'date': self.date,
            'teacher_id': self.teacher_id.id,
            'order_id': self.order_id.id,
            'time_duration': amount,
            # 'company_id': self.sheet_id.company_id.id,
        }
