#!/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, SignUserInfoV2

log_path = '/tmp/'

delete_log = log_path + "sign_record_delete.log"
invalid_user_id_log = log_path + "sign_invalid_user_ids.log"

raw_line_delete = "{user_id}:{sign_time}:{sign_type}:{created_time}:{updated_time}\n"
raw_line_user_ids = "{user_id}\n"
delete_records = []
invalid_user_records = []


class Command(BaseCommand):
    """
    python manage.py sign_log_reset_v2
    处理补签数据
    """

    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')

        # 当月第一天
        mount_start = datetime.today().replace(day=1, hour=0, minute=0, second=0)
        for user_id, sign_count in sign_record:
            if sign_count > 3:
                # 将补签次数更新为3
                SignUserInfoV2.objects.filter(user_id=user_id).update(
                    add_sign_number=3
                )
                # 将补签记录最新三条之前的 无效补签 删除
                invalid_user_sign_record = list(SignRecordLogV2.objects.using(settings.HERA_READ_DB).filter(
                    user_id=user_id, created_time__gte=mount_start, sign_type=SIGN_TYPE_V2.ADD_SIGN,
                ).order_by('created_time'))

                # 记录要被删除的日志
                invalid_ids = []
                for item in invalid_user_sign_record[: -3]:
                    delete_records.append(raw_line_delete.format(
                        user_id=item.user_id,
                        sign_time=item.sign_time,
                        sign_type=item.sign_type,
                        created_time=item.created_time,
                        updated_time=item.updated_time,
                    ))

                    # 记录无效补签的用户
                    invalid_user_records.append(raw_line_user_ids.format(user_id=user_id))

                    invalid_ids.append(item.id)

                # 删除
                SignRecordLogV2.objects.filter(id__in=invalid_ids).delete()

        with open(delete_log, 'a+') as f:
            f.writelines(delete_records)

        with open(invalid_user_id_log, 'a+') as f:
            f.writelines(invalid_user_records)

        print('Done')
