# coding=utf-8

import time
import json
from multiprocessing import Pool, Manager

from django.core.management import BaseCommand

from api.models.face.user_record import ScanRecord


def deal_scan_record(start, per_num, end):

    if not end:
        max_obj = ScanRecord.objects.last()
        end = max_obj.id

    while True:
        start_time = time.time()
        if start > end:
            break

        scan_record_objs = ScanRecord.objects.filter(id__gt=start, id__lte=start + per_num, scan_type__in=[3, 4])
        if not scan_record_objs:
            continue

        for scan_record_obj in scan_record_objs:
            if not scan_record_obj.data:
                continue
            if scan_record_obj.scan_type == 3:
                scan_record_data = json.loads(scan_record_obj.data)
                extra = {
                    "face_desc": scan_record_data.get("face_desc"),
                    "user_portrait": scan_record_data.get("user_portrait"),
                    "classification": scan_record_data.get("classification"),
                    "classification_info": scan_record_data.get("classification_info")
                }
                ScanRecord.objects.filter(id=scan_record_obj.id).update(extra=extra)
            else:
                ScanRecord.objects.filter(id=scan_record_obj.id).update(detect=scan_record_obj.data)

        time.sleep(1)
        start += per_num
        print('time {} s {} id.'.format(time.time() - start_time, start))


class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('-start_id', type=int, action='store', default=0)
        parser.add_argument('-per_num', type=int, action='store', default=50)
        parser.add_argument('-end_id', type=int, action='store', default=0)

    def handle(self, *args, **options):
        """清洗api_scan_record数据"""

        print('------ starting -----')
        start_time = time.time()
        start_id = options.get('start_id')
        per_num = options.get('per_num')
        end_id = options.get('end_id')
        print("start at: ", start_time)

        deal_scan_record(start_id, per_num, end_id)

        end_time = time.time()
        print("end at: ", end_time)
        print('total use {} s.'.format(end_time - start_time))
        print('Done!')
