from openpyxl.workbook import Workbook
from django.conf import settings
from datetime import datetime
from openpyxl.styles import Font, Fill
from rest_framework.serializers import Serializer
from .models import ExamTest, AnswerDetail
from django.http import HttpResponse
from docxtpl import DocxTemplate, InlineImage
from docx.shared import Mm
from io import BytesIO
from .serializers import ExamTestDetailSerializer
from crm.serializers import CandidateSerializer
import os
BASE_DIR = settings.BASE_DIR

def export_test(tests):
    '''
    params: serializer tests
    return: xlsx path
    '''
    wb = Workbook()
    ws1 = wb.active
    ws1.title = '用户表'
    ws1.append(['类型','用户姓名', '用户单位', '工作类别', '押题卷', '得分', '耗时', '答题时间'])
    row = ws1.row_dimensions[1]
    row.font = Font(bold=True)
    for i in tests:
        ws1.append([i['type'], i['consumer_name'], i['consumer_company_name'], i['workscope_name'], i['paper_name'], i['score'], i['took_format'], i['start_time']])
    filename = 'tests' + datetime.now().strftime("%Y%m%d%H%M%S") +'.xlsx'
    path = '/media/export/' + filename
    wb.save((BASE_DIR + path).replace('\\', '/'))
    return path

def gen_candidate(obj):
    """
    生成证书
    """
    data = {}
    data['number'] = obj.number
    data['name'] = obj.consumer_name
    data['company_name'] = obj.company_name
    data['date1'] = obj.train_start_date.strftime("%Y年%m月%d日")
    data['date2'] = obj.train_end_date.strftime("%Y年%m月%d日")
    data['date3'] = obj.issue_date.strftime("%Y年%m月%d日")
    data['train_name'] = obj.train_name
    filename = data['number']+'.docx'
    path = '/media/export/' + filename
    fullpath = BASE_DIR + path
    #开始生成word
    doc = DocxTemplate(BASE_DIR + "/tmp/c1.docx")
    doc.render(data)
    doc.save(fullpath)
    return path

def exportw_test(obj, bool):
    """
    导出个人考试记录word版本
    """
    filename = obj.exam.name + '-' + str(obj.exam.id) + '-' + obj.consumer_detail['name'] + '-' + str(obj.score) + '.docx'
    path = '/media/export/' + filename
    fullpath = BASE_DIR + path
    if bool or (not os.path.exists(fullpath)):
        data = ExamTestDetailSerializer(instance=obj).data
        #开始生成word
        doc = DocxTemplate(BASE_DIR + "/tmp/examtest.docx")
        data['qdimgs'] = []
        data['xcimgs'] = []
        for i in data['exam_']['qdimgs']:
            data['qdimgs'].append(InlineImage(doc, BASE_DIR + i,width=Mm(40)))
        for i in data['exam_']['xcimgs']:
            data['xcimgs'].append(InlineImage(doc, BASE_DIR + i,width=Mm(40)))
        doc.render(data)
        doc.save(fullpath)       
    # output = BytesIO()
    # doc.save(output)
    # output.seek(0)
    # res = HttpResponse(content_type='application/msword')
    # res['Content-Disposition'] = 'attachment;filename='+filename+'.docx'
    # res.write(output.getvalue())
    return path