"""一次性写入客服后台菜单与权限映射。用法: python manage.py seed_kefu_menu"""
from django.core.management.base import BaseCommand

from jituan.models import KefuMenuPage
from jituan.services.kefu_menu_definitions import KEFU_MENU_ROW_DEFS


class Command(BaseCommand):
    help = '写入客服后台菜单页与权限映射（可重复执行，幂等更新）'

    def handle(self, *args, **options):
        created, updated = 0, 0
        for row in KEFU_MENU_ROW_DEFS:
            defaults = {
                'name': row['name'],
                'path': row.get('path', ''),
                'parent_id': row.get('parent_id', ''),
                'sort_order': row.get('sort_order', 0),
                'perm_codes': row.get('perm_codes', []),
                'require_super': row.get('require_super', False),
                'require_group_manage': row.get('require_group_manage', False),
            }
            existing = KefuMenuPage.query.filter(page_id=row['page_id']).first()
            if existing:
                for key, val in defaults.items():
                    setattr(existing, key, val)
                existing.save()
                updated += 1
            else:
                KefuMenuPage(page_id=row['page_id'], **defaults).save()
                created += 1
        self.stdout.write(self.style.SUCCESS(
            f'kefu_menu_page 种子完成：新增 {created}，更新 {updated}，共 {len(KEFU_MENU_ROW_DEFS)} 条'
        ))
        try:
            from django.core.management import call_command
            call_command('seed_gvsdsdk_permissions')
        except Exception as e:
            self.stdout.write(self.style.WARNING(f'seed_gvsdsdk_permissions 跳过: {e}'))
        try:
            from django.core.management import call_command
            call_command('seed_fund_freeze_perm')
        except Exception as e:
            self.stdout.write(self.style.WARNING(f'seed_fund_freeze_perm 跳过: {e}'))
        try:
            call_command('seed_role_agreement_perm')
        except Exception as e:
            self.stdout.write(self.style.WARNING(f'seed_role_agreement_perm 跳过: {e}'))
