# coding=utf-8
import os
import datetime

from django.core.management import BaseCommand
from django.conf import settings

from api.models import Diary
from search.utils.diary import filter_diary
from search.utils.diary import DIARY_ORDER_TYPE


class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('size')
        parser.add_argument('type')

    def handle(self, *args, **options):
        filters = {}
        size = int(options['size'])
        if size > 100:
            last_updated = []
            index = []
            for i in range(size / 100):
                _index = 100 * i
                ld = filter_diary(_index, size, filters=filters, sort_type=DIARY_ORDER_TYPE.LAST_UPDATE_TIME)['diary_ids']
                id = filter_diary(_index, size, filters=filters, sort_type=DIARY_ORDER_TYPE.INDEX)['diary_ids']
                last_updated += ld
                index += id
        else:
            last_updated = filter_diary(0, size, filters=filters, sort_type=DIARY_ORDER_TYPE.LAST_UPDATE_TIME)['diary_ids']
            index = filter_diary(0, size, filters=filters, sort_type=DIARY_ORDER_TYPE.INDEX)['diary_ids']

        file_dir = settings.LOG_DIR + 'index_diary/'
        if not os.path.exists(file_dir):
            os.mkdir(file_dir)
        file_name = file_dir + 'score_detail.log'
        now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        last_updated_diary_detail = self.generate_diary_detail(last_updated)
        index_diary_detail = self.generate_diary_detail(index)
        with open(file_name, 'w') as f:
            f.write(u'{}\n'.format(now).encode('utf-8'))

            type = options['type']
            if type == 'all' or type == 'update':
                f.write(u'根据最后更新日记的排序\n'.encode('utf-8'))
                self.write_file(f, last_updated_diary_detail)
            if type == 'all' or type == 'index':
                f.write(u'根据首页的排序\n'.encode('utf-8'))
                self.write_file(f, index_diary_detail)
            f.close()
        print u'文件已保存至{}'.format(file_name)

    def generate_diary_detail(self, diary_ids):
        diaries = [Diary.objects.get(pk=i) for i in diary_ids]
        detail = []
        for d in diaries:
            try:
                username = d.user.last_name
            except:
                username = u'无'
            try:
                service_name = d.service.name
            except:
                service_name = u'无'
            info = (d.id, d.get_index_rank(), username, service_name)
            detail.append(info)
        return detail

    def write_file(self, fd, values):
        log_template = u'日记本id: {}, 热度分: {}, 内容质量分: {}, 医生抽成分: {}, 用户名: {}, 美购名: {}\n'
        for value in values:
            id = value[0]
            heat_score, audit_score, choucheng_score = value[1]
            username, service_name = value[2], value[3]
            log = log_template.format(id, heat_score, audit_score, choucheng_score, username, service_name)
            fd.write(log.encode('utf-8'))
