# -*- coding: utf-8 -*-
#  @date    161103 - Export excel with get_work_order_report function
"""
Data exportor (Excel, CSV...)
"""
import io
import math
from datetime import datetime

from xlsxwriter.workbook import Workbook
import tablib

from utils.tools import get_product_size


def get_customers(customer_list=None, file_format='csv'):
    """Generate customer data file for download."""
    if customer_list is None:
        customer_list = []

    data = tablib.Dataset()
    data.headers = ('客戶代碼', '客戶名稱')

    for c in customer_list:
        data.append((c.c_code, c.c_name))

    if file_format == 'csv':
        return data.csv

a


def get_maintenance_log(log_list=None, file_format='csv'):
    """Generate maintenance log to csv file for download."""
    if log_list is None:
        log_list = []

    data = tablib.Dataset()
    data.headers = ('機台', '維修項目', '開始時間',
                    '員工', '結束時間', '員工',
                    '總計時間')

    for log in log_list:
        m_code = log['m_code'].replace('<br>', '\n')
        data.append((log['machine_id'], m_code, log['start_time'],
                     log['who_start'], log['end_time'], log['who_end'],
                     log['total_time'][0])
                    )

    if file_format == 'csv':
        return data.csv

    return data


def get_w_m_performance_report(file_format='xls'):
    """Generate excel file for download by worker and machine performance."""
    row_number = 11
    data = tablib.Dataset()
    data.append(['個人效率期間表 ({})'.format(
        datetime.now().strftime("%Y/%m/%d"))] + [''] * (row_number - 1))
    data.append(['工號', '姓名', '日期', '標準量', '效率標準量',
                 '實質生產量', '總稼動時間', '總停機時間', '稼動 %', '數量效率 %',
                 '平均效率 %'])

    if file_format == 'xls':
        return data.xls

    return data


def get_loss_rate_report(report_data, file_format='csv'):
    """Generate csv file for download by machine loss rate."""
    data = tablib.Dataset()
    data.headers = ('機台', '機型', '良品數', '不良品數', '損耗率(%)',
                    '損耗金額(RMB)', '損耗率排名')

    rank = 0
    old_loss_rate = None
    for r in sorted(report_data, key=lambda k: k['loss_rate'], reverse=True):
        if old_loss_rate != r['loss_rate']:
            rank += 1
            old_loss_rate = r['loss_rate']

        record = [r['machine_id'], r['machine_type'], r['count_qty'],
                  r['event_qty'], r['loss_rate'], r['total_loss_money'],
                  rank]
        data.append(record)

    if file_format == 'csv':
        return data.csv

    return data


def get_loss_rate_detail_report(report_data, file_format='csv'):
    """Generate csv file for download by machine loss rate detail."""
    data = tablib.Dataset()
    data.headers = ('日期', '良品數', '不良品數', '損耗率(%)',
                    '損耗金額(RMB)')

    for r in sorted(report_data, key=lambda k: k['record_date']):
        record = [r['record_date'], r['count_qty'], r['event_qty'],
                  r['loss_rate'], r['total_loss_money']]
        data.append(record)

    if file_format == 'csv':
        return data.csv

    return data


def get_uptime_report(report_data='', file_format='xls'):
    """Generate excel file for download by uptime information."""
    data = tablib.Dataset()
    data.append_separator('製造部各工程稼動率一覽表')
    data.append(['月份：10', '星期', '', '', '', '', '',
                 '目標', '', '', '', ''])
    data.append(['', '', '加締卷取(%)', '組立(%)', '老化(%)',
                 'CUTTING(%)', 'TAPPING(%)', '加締卷取',
                 '組立', '老化', 'CUTTING', 'TAPPING'])

    if file_format == 'xls':
        return data.xls

    return data


def get_work_order_report(report_data, file_format='csv'):
    """Generate csv file for download by work order."""
    # data = tablib.Dataset()
    # data.headers = ('製令編號', '料號', '客戶', '產品規格',
    #                 '投入數', '應繳庫數',
    #                 '加締捲取', '組立', '老化', '選別', '加工切角')

    # for r in sorted(report_data, key=lambda k: k['order_no']):
    #     try:
    #         intput_count = int(r['input_count'])
    #     except (TypeError, ValueError):
    #         intput_count = -1

    #     record = [r['order_no'], r['part_no'], r['customer'], r['product'],
    #               intput_count, math.floor(intput_count / 1.03),
    #               r['step1_status'], r['step2_status'], r['step3_status'],
    #               r['step4_status'], r['step5_status']]
    #     data.append(record)

    # if file_format == 'csv':
    #     return data.csv

    # return data

    output = io.BytesIO()

    if file_format == 'xls':
        workbook = Workbook(output, {'in_memory': True})
        worksheet = workbook.add_worksheet()

        # merge_format = workbook.add_format({
        #     'bold': 1,
        #     'border': 1,
        #     'align': 'center',
        #     'valign': 'vcenter'})

        worksheet.merge_range('A1:A3', '製令編號')
        worksheet.merge_range('B1:B3', '料號')
        worksheet.merge_range('C1:C3', '客戶')
        worksheet.merge_range('D1:D3', '產品規格')
        worksheet.merge_range('E1:E3', '投入數')
        worksheet.merge_range('F1:F3', '應繳庫數')
        worksheet.write('G1', '加締捲取')
        worksheet.write('H1', '組立')
        worksheet.write('I1', '老化')
        worksheet.write('J1', '選別')
        worksheet.write('K1', '加工切角')

        for col_name in ('G', 'H', 'I', 'J', 'K'):
            worksheet.write(col_name + '2', '機器')
            worksheet.write(col_name + '3', '良品數')

        row = 4
        for r in sorted(report_data, key=lambda k: k['order_no']):
            try:
                intput_count = int(r['input_count'])
            except (TypeError, ValueError):
                intput_count = -1

            worksheet.merge_range('A{}:A{}'.format(row, row + 2),
                                  r['order_no'])
            worksheet.merge_range('B{}:B{}'.format(row, row + 2), r['part_no'])
            worksheet.merge_range('C{}:C{}'.format(row, row + 2),
                                  r['customer'])
            worksheet.merge_range('D{}:D{}'.format(row, row + 2), r['product'])
            worksheet.merge_range('E{}:E{}'.format(row, row + 2), intput_count)
            worksheet.merge_range('F{}:F{}'.format(row, row + 2),
                                  math.floor(intput_count / 1.03))

            for process in range(1, 6):
                row_tag = chr(71 + process - 1)
                worksheet.write_string('{}{}'.format(row_tag, row),
                                       r['step{}_status'.format(process)])
                machine = r['step{}_machine'.format(process)]
                count = r['step{}_count'.format(process)]

                worksheet.write_string('{}{}'.format(row_tag, row + 1),
                                       machine if machine else '')
                worksheet.write_string('{}{}'.format(row_tag, row + 2),
                                       str(count) if count else '')

            row += 3

        workbook.close()
        output.seek(0)

    return output.read()


def get_order_report(report_data, file_format='csv'):
    """Generate csv file for download by machine loss rate detail."""
    data = tablib.Dataset()
    data.headers = ('製令編號', '客戶', '規格', '投入數', '需求數',
                    '加締捲曲', '組立', '老化', '選別', '加工切腳')

    for r in sorted(report_data, key=lambda k: k['order_no']):
        record = [r['order_no'], r['customer'], get_product_size(r['part_no']),
                  r['input_count'], r['require_count'],
                  r['step1_prod_qty'], r['step2_prod_qty'],
                  r['step3_prod_qty'], r['step4_prod_qty'],
                  r['step5_prod_qty']]
        data.append(record)

    if file_format == 'csv':
        return data.csv

    return data


    return dat