from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from .models import CMA
from .serializers import CMASerializer
from rest_framework.decorators import action
from django.conf import settings
from rest_framework import status
from rest_framework.response import Response
import zipfile
import rarfile
from openpyxl import Workbook, load_workbook
# Create your views here.
class CMAViewSet(ModelViewSet):
    """
    CMA检测能力：增删改查
    """
    perms_map = {'get': '*', 'post': 'cma_create',
                 'put': 'cma_update', 'delete': 'cma_delete'}
    queryset = CMA.objects.all()
    serializer_class = CMASerializer
    search_fields = ['bzbh', 'bzmc', 'sszx', 'xmmc']
    ordering_fields = ['xmxh']
    ordering = 'xmxh'

    @action(methods=['post'], detail=False, url_path='import', url_name='cma_import', perms_map = {'post':'cma_import'})
    def cma_import(self, request, pk=None):
        """
        导入能力
        """
        filepath = request.data['path']
        fullpath = settings.BASE_DIR + filepath
        import os
        if fullpath.endswith('.rar'):
            rar = rarfile.RarFile(fullpath)
            fulldir = fullpath.replace('.rar','')
            os.mkdir(fulldir)
            os.chdir(fulldir)
            rar.extractall()
            rar.close()
            CMA.objects.all().delete()
            for root, dirs, files in os.walk(fulldir):
                for f in files:
                    import_cma(f, os.path.join(root,f))
        return Response(status = status.HTTP_200_OK)


def import_cma(filename, path):
    wb = load_workbook(path)
    sheet = wb.worksheets[0]
    datalist = []
    sszx = filename.replace('.xlsx','').replace('副本14检验检测能力申请表-','')
    i = 4
    while sheet['b'+str(i)].value:
        data = {}
        data['dlxh'] = sheet['a'+str(i)].value
        data['dlmc'] = sheet['b'+str(i)].value
        data['lbxh'] = sheet['c'+str(i)].value
        data['lbmc'] = sheet['d'+str(i)].value
        data['xmxh'] = sheet['e'+str(i)].value
        data['xmmc'] = sheet['f'+str(i)].value
        data['bzmc'] = sheet['g'+str(i)].value
        data['bzbh'] = sheet['h'+str(i)].value
        data['xzfw'] = sheet['i'+str(i)].value
        data['bz'] = sheet['j'+str(i)].value
        data['sszx'] = sszx
        print(data)
        datalist.append(CMA(**data))
        i = i + 1
    CMA.objects.bulk_create(datalist)