#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime
from django.conf import settings
from django.core.management import BaseCommand
from django.db.models import Count
from gm_types.gaia import SIGN_TYPE_V2

from api.models import SignRecordLogV2

log_path = '/tmp/'

sign_record_raw_log = log_path + "sign_record_raw.log"

raw_line = "{user_id}:{sign_count}\n"
raw_records = []


class Command(BaseCommand):
    """
    python manage.py sign_log_reset_v1
    记录所有有问题的补签记录
    """

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

        # 周末两天
        start = datetime.today().replace(day=1, hour=0, minute=0, second=0)
        end = datetime.today()

        sign_record = SignRecordLogV2.objects.using(settings.HERA_READ_DB).filter(
            created_time__lte=end, created_time__gte=start, sign_type=SIGN_TYPE_V2.ADD_SIGN,
        ).values('user_id').annotate(cnt=Count('user_id')).values_list('user_id', 'cnt')

        for user_id, sign_count in sign_record:
            if sign_count > 3:

                raw_records.append(raw_line.format(
                    user_id=user_id,
                    sign_count=sign_count,
                ))

        with open(sign_record_raw_log, 'a+') as f:
            f.writelines(raw_records)

        print('Done')
