#!/usr/bin/env python
# encoding=utf-8

from django.core.management import BaseCommand
from django.db import transaction
from api.models.diary import Diary, DiaryCheck
from api.models.topic import Problem
from api.models.person import Person
from api.models.types import DIARY_AUDIT_STATUS, DIARY_CONTENT_LEVEL
from datetime import datetime

class Command(BaseCommand):
    def handle(self, *args, **options):
        diary_audit = open('diary_audit.txt', 'a')
        error_diary = open('error_audit.txt', 'a')
        person = Person.objects.get(user__username='liyou')
        diarys = Diary.objects.filter(audit_status=DIARY_AUDIT_STATUS.UNAUDITED)
        for diary in diarys.iterator():
            try:
                with transaction.atomic():
                    topics = Problem.objects.filter(diary_id=diary.id,is_online=True)
                    if topics and topics.count()<3:
                        diary.audit_status=DIARY_AUDIT_STATUS.AUDITED
                        diary.content_level = DIARY_CONTENT_LEVEL.GENERAL
                        diary.audit_time = datetime.now()
                        diary.save()
                        diarycheck_data = {
                            'person': person,
                            'diary_id': diary.id,
                            'check_time': datetime.now(),
                            'content_level': DIARY_CONTENT_LEVEL.GENERAL,
                            'check_content': u'批量处理',
                        }
                        diarycheck = DiaryCheck.objects.create(**diarycheck_data)
                        print diary.id
                        diary_audit.write(u'%s,%s\n' % (diary.id, diarycheck.id))
            except Exception as e:
                print str(diary.id) + u':'+ e.message
                error_diary.write(str(diary.id) + u':'+ e.message)
                continue
        print u'DONE!'

