# _*_ coding: utf-8 _*_
# Author: Monica( nikochild@gmail.com)
from odoo import models, fields, api, _
import logging,datetime
from odoo.tools.translate import _
from odoo.exceptions import UserError, ValidationError
import xlrd
import base64
from itertools import groupby


class JptipTeacherExport(models.AbstractModel):
    _name = 'report.jptip_teacher_export_xlsx.teacher_export_xlsx'
    _inherit = 'report.report_xlsx.abstract'

    @api.multi
    def generate_xlsx_report(self, workbook, data, objects):
        sheet = workbook.add_worksheet(_('教師排班資訊'))
        sheet.set_landscape()
        sheet.fit_to_pages(1, 0)
        sheet.set_zoom(80)
        bold = workbook.add_format({'bold': True})
        title_style = workbook.add_format({'bold': True,
                                           'bg_color': '#FFFFCC',
                                           'bottom': 1})
        sheet_title = [_('姓名'),
                       _('1'),
                       _('2'),
                       _('3'),
                       _('4'),
                       _('5'),
                       _('6'),
                       _('7'),
                       _('8'),
                       _('9'),
                       _('10'),
                       _('11'),
                       _('12'),
                       _('13'),
                       _('14'),
                       _('15'),
                       _('16'),
                       _('17'),
                       _('18'),
                       _('19'),
                       _('20'),
                       _('21'),
                       _('22'),
                       _('23'),
                       _('24'),
                       _('25'),
                       _('26'),
                       _('27'),
                       _('28'),
                       _('29'),
                       _('30'),
                       _('31')
                       ]
        ex_title = [_('範例(休假留空)'),
                    _('E'),
                    _('E'),
                    _('E'),
                    _('E'),
                    _('A'),
                    _(''),
                    _(''),
                    _('E'),
                    _('E'),
                    _('E'),
                    _('E'),
                    _('A'),
                    _(''),
                    _(''),
                    _('E'),
                    _('E'),
                    _('E'),
                    _('E'),
                    _('A'),
                    _(''),
                    _(''),
                    _('E'),
                    _('E'),
                    _('E'),
                    _('E'),
                    _('A'),
                    _(''),
                    _(''),
                    _(''),
                    _(''),
                    _(''),
                    ]
        col = {
            1: 'date_1',
            2: 'date_2',
            3: 'date_3',
            4: 'date_4',
            5: 'date_5',
            6: 'date_6',
            7: 'date_7',
            8: 'date_8',
            9: 'date_9',
            10: 'date_10',
            11: 'date_11',
            12: 'date_12',
            13: 'date_13',
            14: 'date_14',
            15: 'date_15',
            16: 'date_16',
            17: 'date_17',
            18: 'date_18',
            19: 'date_19',
            20: 'date_20',
            21: 'date_21',
            22: 'date_22',
            23: 'date_23',
            24: 'date_24',
            25: 'date_25',
            26: 'date_26',
            27: 'date_27',
            28: 'date_28',
            29: 'date_29',
            30: 'date_30',
            31: 'date_31'
        }
        teacher_batch_id = self.env['jt.teacher.batch'].browse(objects.id)
        if int(datetime.datetime.strptime(teacher_batch_id.date_to, '%Y-%m-%d').day) == 28:
            sheet_title.remove('29')
            sheet_title.remove('30')
            sheet_title.remove('31')
        elif int(datetime.datetime.strptime(teacher_batch_id.date_to, '%Y-%m-%d').day) == 29:
            sheet_title.remove('30')
            sheet_title.remove('31')
        elif int(datetime.datetime.strptime(teacher_batch_id.date_to, '%Y-%m-%d').day) == 30:
            sheet_title.remove('31')
        sheet.set_row(0, None, None, {'collapsed': 1})
        sheet.write_row(0, 0, sheet_title, title_style)
        sheet.write_row(1, 0, ex_title, title_style)
        sheet.freeze_panes(1, 0)
        i = 2
        line1 = self.env['jt.teacher.batch.line1'].search([('order_id', '=', objects.id)])
        for o in line1:
            sheet.write(i, 0, o.teacher_id.name or '', bold)
            j = 0
            for a in range(1, 32):
                j += 1
                key = col[a]
                sheet.write(i, j, o[key].name or '', )
            i += 1


class JptipTeacherImport(models.TransientModel):
    _name = "wizard.jt.teacher.import"

    name = fields.Char('import')
    data = fields.Binary(string='文件')
    data_name = fields.Char(u'匯入檔名')

    @api.multi
    def import_teacher(self):
        col = {
            '1': 'date_1',
            '2': 'date_2',
            '3': 'date_3',
            '4': 'date_4',
            '5': 'date_5',
            '6': 'date_6',
            '7': 'date_7',
            '8': 'date_8',
            '9': 'date_9',
            '10': 'date_10',
            '11': 'date_11',
            '12': 'date_12',
            '13': 'date_13',
            '14': 'date_14',
            '15': 'date_15',
            '16': 'date_16',
            '17': 'date_17',
            '18': 'date_18',
            '19': 'date_19',
            '20': 'date_20',
            '21': 'date_21',
            '22': 'date_22',
            '23': 'date_23',
            '24': 'date_24',
            '25': 'date_25',
            '26': 'date_26',
            '27': 'date_27',
            '28': 'date_28',
            '29': 'date_29',
            '30': 'date_30',
            '31': 'date_31'
        }
        active_ids = self.env.context.get('active_ids')
        batch_id = self.env['jt.teacher.batch'].search([('id', '=', active_ids)], limit=1)
        print(self.env.user.company_id.name)
        if int(datetime.datetime.strptime(batch_id.date_to, '%Y-%m-%d').day) == 28:
            del col['29']
            del col['30']
            del col['31']
        elif int(datetime.datetime.strptime(batch_id.date_to, '%Y-%m-%d').day) == 29:
            del col['30']
            del col['31']
        elif int(datetime.datetime.strptime(batch_id.date_to, '%Y-%m-%d').day) == 30:
            del col['31']
        if self.data:
            xls = xlrd.open_workbook(file_contents=base64.decodestring(self.data))
            sheet = xls.sheet_by_index(0)
            title = sheet.row_values(0)
            line1_obj = self.env['jt.teacher.batch.line1']
            res = list()
            teacher_time = dict()
            teacher_time_obj = self.env['jt.timing.manager'].search([('company_id', '=', self.env.user.company_id.id)])
            for time in teacher_time_obj:
                teacher_time[time.name] = time.id
            teacher_time[''] = ''
            for row in range(2, sheet.nrows):
                lines = dict()
                vals = sheet.row_values(row)
                value = dict(zip(title, vals))
                i = 0
                teacher_name = sheet.cell(row, i).value
                if len(teacher_name) == 0:
                    continue
                teacher_id = self.env['jt.teacher'].search(
                    [('name', 'ilike', teacher_name.strip()), ('company_id', '=', self.env.user.company_id.id)])
                if len(teacher_id) > 1:
                    for f in teacher_id:
                        if f.name.strip() == teacher_name.strip():
                            teacher_id = f
                line1_obj.search(
                    [('order_id', '=', self.env.context.get('active_id')), ('teacher_id', '=', teacher_id.id),
                     ('company_id', '=', self.env.user.company_id.id)]).unlink()
                if any(teacher_id):
                    lines['order_id'] = self.env.context.get('active_id')
                    lines['teacher_id'] = teacher_id.id
                    for n, key in col.items():
                        lines[key] = teacher_time[value[n]]
                    line1_obj.create(lines)
                else:
                    raise UserError(u'請輸入正確的老師名字 第%s, %s' % (row + 1, teacher_name))
        self.env['jt.teacher.batch'].browse(self.env.context.get('active_id')).gen_jt_teacher_line()
