from django.core.management import BaseCommand
from django.conf import settings
from django.db import transaction

from common.utils.models import BaseConnection
from common.accounts.models import (Users, Accounts, Enterprise,
                                    UserEnterprise, Perms)
from common.utils.str_utils import make_uuid
from common.utils.perms_conf import model_perms, CONFIG

base_db = BaseConnection()


class Command(BaseCommand):
    help = '初始化数据库'

    def add_arguments(self, parser):
        parser.add_argument('username', help="指定username字段")
        parser.add_argument('password', help="指定password字段")

    def create_enterprise(self, name):
        admin_ent = Enterprise.objects.filter(is_admin=True)
        if admin_ent:
            self.stdout.write("管理员企业已存在")
            return admin_ent.first()
        ent = Enterprise.objects.create(enterprise_id=make_uuid(),
                                        name=name,
                                        is_admin=True)
        self.stdout.write("管理员企业创建成功")
        return ent

    def create_admin_user(self, name, password):
        account = Accounts.objects.filter(username=name).first()
        if account:
            self.stdout.write("管理员账号已存在")
            has_user = Users.objects.filter(account=account)
            if has_user:
                self.stdout.write("管理员用户已存在")
                return has_user.first()
            else:
                self.stdout.write("未找到管理员用户，将重新分配用户")
        else:
            account = Accounts.objects.create(username=name,
                                              is_active=True,
                                              certification_status=True,
                                              account_type="manager")
            account.set_password(password)
            account.save()
            self.stdout.write("管理员账号创建成功")
        user = Users.objects.create(
            account=account,
            nickname=name,
        )
        self.stdout.write("管理员用户创建成功")
        return user

    def link_account_enterprise(self, user_id, enterprise_id):
        has_user_ent = UserEnterprise.objects.filter(
            user_id=user_id, enterprise_id=enterprise_id)
        if has_user_ent:
            self.stdout.write("管理员用户已关联到管理员企业")
        else:
            UserEnterprise.objects.create(user_id=user_id,
                                          enterprise_id=enterprise_id)
            self.stdout.write("管理员用户与管理员企业成功关联")

    @transaction.atomic()
    def init_perms(self):
        perms = model_perms(CONFIG)
        perms_list = []
        has_perms = Perms.objects.all()
        for i in range(len(perms)):
            perms[i]["id"] = i + 1
            perms_list.append(Perms(**perms[i]))
        if has_perms.count() == 0:
            Perms.objects.bulk_create(perms_list)
            self.stdout.write("成功初始化权限表")
        else:
            # has_perms.delete()
            base_db.query("truncate table perms")
            Perms.objects.bulk_create(perms_list)
            self.stdout.write("成功初始化权限表")

    def handle(self, *args, **options):
        username = options.get('username', settings.USERNAME)
        password = options.get("password", settings.PASSWORD)
        enterprise = self.create_enterprise(settings.ENTERPRISE_NAME)
        user = self.create_admin_user(username, password)
        self.link_account_enterprise(user.id, enterprise.enterprise_id)
        self.init_perms()
