#! /usr/bin/env python
# -*- coding: utf-8 -*-

from openpyxl import Workbook, load_workbook
from api.models import Tag, TagRelation, ItemWiki
from django.core.management import BaseCommand
from gm_types.gaia import TAG_TYPE
from datetime import datetime


class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('param', nargs='+', type=str)

    '''
       1,导出execl命令 sudo python manage.py export_tag_wiki_data export,
       导出后目录下会有一个tag_wiki_data.xlsx文件即为导出文件
    '''

    def handle(self, *args, **options):
        for param in options['param']:
            if param == 'export':
                excel = HandleExcel('tag_wiki_data.xlsx')
                excel.export_file()


class HandleExcel:

    def __init__(self, file_name):
        self.file = file_name

    def save_log(self, log_file, content):
        with open(log_file, 'a+') as f:
            content = "%s--time:%s\n" % (content, datetime.now().strftime('%Y-%m-%d %H:%M:%S %f'))
            f.write(content)

    def export_file(self):
        tag_list = Tag.objects.filter(is_online=True).filter(tag_type=TAG_TYPE.ITEM_WIKI)
        self.save_log("info.log", "count is: %s " % str(len(tag_list)))
        excel = Workbook()
        excel_active = excel.get_active_sheet()
        excel_active.title = 'tag_wiki_data'
        head = [u'tag的所属一级分类ID',
                u'tag的所属一级分类名',
                u'tag的所属二级分类ID',
                u'tag的所属二级分类名',
                u'tag本身ID',
                u'tag本身的名字',
                u'tag本身所属类型',
                u'对应的wiki的id',
                u'对应的wiki的名字',
                ]
        for col in range(9):
            excel_active.cell(row=1, column=col + 1).value = head[col]
        record_count = 0
        for index1, tag in enumerate(tag_list):
            try:
                list_data = []
                try:
                    wiki = ItemWiki.objects.get(tag=tag)
                except ItemWiki.DoesNotExist, ItemWiki.MultipleObjectsReturned:
                    wiki = None
                wiki_id = wiki.id if wiki else ''
                wiki_name = wiki.item_name if wiki else ''
                seconed_type = TagRelation.objects.filter(child_id=tag.id)
                for second in seconed_type:
                    if second.parent.tag_type != TAG_TYPE.BODY_PART_SUB_ITEM:
                        self.save_log("error.log", 'tag_id :%s,parent_id:%s,error:二级分类不正确' %
                                      (str(tag.id), second.parent.id))
                        continue
                    first_type = TagRelation.objects.filter(child_id=second.parent.id)
                    for first in first_type:
                        if first.parent.tag_type != TAG_TYPE.BODY_PART:
                            self.save_log("error.log",
                                          'tag_id :%s,parent_id:%s,error:一级分类不正确' % (str(tag.id), first.parent.id))
                            continue
                        data = {}
                        data['first_type_id'] = first.parent.id
                        data['first_type_name'] = first.parent.name
                        data['seconed_type_id'] = second.parent.id
                        data['seconed_type_name'] = second.parent.name
                        data['id'] = tag.id
                        data['name'] = tag.name
                        data['tag_type'] = TAG_TYPE.getDesc(tag.tag_type)
                        data['wiki_id'] = wiki_id
                        data['wiki_name'] = wiki_name
                        list_data.append(data)
                for index, dt in enumerate(list_data):
                    excel_active.cell(row=record_count + index + 2, column=1).value = dt['first_type_id']
                    excel_active.cell(row=record_count + index + 2, column=2).value = dt['first_type_name']
                    excel_active.cell(row=record_count + index + 2, column=3).value = dt['seconed_type_id']
                    excel_active.cell(row=record_count + index + 2, column=4).value = dt['seconed_type_name']
                    excel_active.cell(row=record_count + index + 2, column=5).value = dt['id']
                    excel_active.cell(row=record_count + index + 2, column=6).value = dt['name']
                    excel_active.cell(row=record_count + index + 2, column=7).value = dt['tag_type']
                    excel_active.cell(row=record_count + index + 2, column=8).value = dt['wiki_id']
                    excel_active.cell(row=record_count + index + 2, column=9).value = dt['wiki_name']
                    info_log = 'import tag_id:%s' % str(tag.id)
                    self.save_log('info.log', info_log)
                record_count = len(list_data) + record_count
            except Exception, ex:
                self.save_log("error.log", 'tag_id :%s,error:%s' % (str(tag.id), str(ex)))
        excel.save(filename=self.file)
        complete = "------file:%s is command Complete------" % (self.file)
        self.save_log("info.log", complete)
        self.save_log("error.log", complete)
