from rest_framework.viewsets import ModelViewSet
from apps.system.mixins import CreateUpdateCustomMixin
from apps.edu.serializers import CertificateSerializer
from apps.edu.models import Certificate
from rest_framework.decorators import action
from django.conf import settings
from rest_framework.exceptions import ParseError
from rest_framework.response import Response
from openpyxl import load_workbook
from rest_framework.serializers import Serializer
from rest_framework.permissions import AllowAny
from apps.edu.services import make_img_x
# Create your views here.

class CertificateViewSet(CreateUpdateCustomMixin, ModelViewSet):
    perms_map = {'get': '*', 'post': 'certificate',
                 'put': 'certificate', 'delete': 'certificate'}
    queryset = Certificate.objects.all()
    serializer_class = CertificateSerializer
    search_fields = ['姓名', '证书编号', '所属单位']
    filterset_fields = ['是否内审员','是否授权签字人', '是否质量负责人', '是否最高管理者', '姓名', '证书编号', '所属单位', '单位名称']
    ordering = ['-create_time']

    def get_authenticators(self):
        if self.request.method == 'GET':
            return []
        return super().get_authenticators()
    
    def get_permissions(self):
        if self.request.method == 'GET':
            return [AllowAny()]
        return super().get_permissions()

    def retrieve(self, request, *args, **kwargs):
        regen_img = request.query_params.get('regen_img', False)
        instance = self.get_object()
        if not instance.证书地址 or regen_img:
            make_img_x(instance)
        serializer = self.get_serializer(instance)
        return Response(serializer.data)
    
    def make_data(self, data, sheet, i):
        data['证书编号'] = sheet['b'+str(i)].value
        data['所属单位'] = sheet['c'+str(i)].value
        data['单位名称'] = sheet['d'+str(i)].value
        data['姓名'] = sheet['e'+str(i)].value
        data['性别'] = sheet['f'+str(i)].value
        data['职务'] = sheet['g'+str(i)].value
        data['手机号'] = sheet['h'+str(i)].value
        data['是否内审员'] = True if sheet['i'+str(i)].value else False
        data['是否授权签字人'] = True if sheet['j'+str(i)].value else False
        data['是否质量负责人'] = True if sheet['k'+str(i)].value else False
        data['是否最高管理者'] = True if sheet['l'+str(i)].value else False
        data['是否需要集团证书'] = True if sheet['m'+str(i)].value else False
        data['是否需要北京标研培训合格'] = True if sheet['n'+str(i)].value else False
        return data

    @action(methods=['post'], detail=False, perms_map = {'post':'certificate'}, serializer_class=Serializer)
    def imp(self, request, *args, **kwargs):
        """导入表格

        导入表格
        """
        path = request.data.get('path', '')
        full_path = settings.BASE_DIR + path
        if not path.endswith('.xlsx'):
            raise ParseError('请提供xlsx格式文件')
        wb = load_workbook(full_path, data_only=True)
        sheet = wb.worksheets[0]
        i = 3
        while sheet['b'+str(i)].value:
            data = {}
            data = self.make_data(data, sheet, i)
            obj, created = Certificate.objects.update_or_create(defaults=data, 证书编号=data['证书编号'])
            i = i + 1
        return Response()
