# coding=utf-8

import xlwt
from openpyxl import Workbook

from hera.models import BackendModule, BackendPermission, BackendGroup

from django.core.management import BaseCommand

class Command(BaseCommand):
    """
    导出权限信息 12-16
    puthon manage.py export_permissions_info
    """

    def handle(self, *args, **options):

        excel = Workbook()
        excel_active = excel.get_active_sheet()
        excel_active.title = 'permissions_data'
        head = [u'权限', u'权限组', u'账号']

        for col in range(3):
            excel_active.cell(row=1, column=col + 1).value = head[col]
        backend_module_list = BackendModule.objects.all()
        index = 2
        for backend_module in backend_module_list:
            module_name = backend_module.title
            backend_permission_list = BackendPermission.objects.filter(module_id=backend_module.id)
            for backend_permission in backend_permission_list:
                permission_name = backend_permission.title
                backendgroups = list(
                    BackendGroup.objects.filter(permissions=backend_permission).values('title', 'members__username',
                                                                                       'members__last_name'))
                for backendgroup in backendgroups:
                    try:
                        backend_permission_name = '{}|{}'.format(module_name, permission_name)
                        group = backendgroup['title']
                        username = backendgroup['members__username'] if backendgroup['members__username'] else \
                        backendgroup['members__last_name']
                        excel_active.cell(row=index, column=1).value = backend_permission_name
                        excel_active.cell(row=index, column=2).value = group
                        excel_active.cell(row=index, column=3).value = username
                        index +=1
                    except Exception as e:
                        print e.message
                        continue
        print u'结束'
        excel.save(u'所有权限信息表.xls')

