# coding: utf-8
from __future__ import absolute_import, unicode_literals, print_function

import xlwt

from django.core.management import BaseCommand
from gm_types.gaia import TAG_TYPE

from api.models import Tag, SeoCategory, CategoryRelation


class Command(BaseCommand):
    all_category_info = {}

    def tag_to_seo_category(self):
        tags = Tag.objects.exclude(tag_type=TAG_TYPE.FREE)
        total_count = tags.count()
        print('total tags: %s' % total_count)
        for index, tag in enumerate(tags):
            print('%s/%s tag %s %s -> seo category' % (index + 1, total_count, tag.id, tag.name))
            tag_wikis = tag.tagwiki.all()
            if tag_wikis:
                wiki = tag_wikis.first().itemwiki
                if wiki:
                    wiki_id = wiki.id
                    wiki_info = '%s->%s' % (wiki.id, wiki.item_name)
            else:
                wiki_id = None
                wiki_info = None
            kwargs = {
                'tag_id': tag.id,
                'name': tag.name,
                'wiki_id': wiki_id,
                'category_type': tag.tag_type,
                'icon': tag.icon_url,
                'banner': tag.banner_url,
                'desc_md': tag.description,
            }
            sc, created = SeoCategory.objects.get_or_create(**kwargs)
            add_info = {
                'wiki': wiki_info,
                'category_type': TAG_TYPE.getDesc(tag.tag_type),
                'parent_category': [],
                'child_category': [],
                'show_diary': False,
            }
            kwargs.update(add_info)
            self.all_category_info[sc.id] = kwargs

    def create_seo_category_relation(self):
        print('creating category relations')

        def add_parent_info(parent, child):
            if parent.id in self.all_category_info:
                child_category = TAG_TYPE.getDesc(child.category_type)
                child_info = '-> %s:%s/%s \n' % (child.id, child.name, child_category)
                self.all_category_info[parent.id]['child_category'].append(child_info)
            else:
                pass

        def add_child_info(parent, child):
            if child.id in self.all_category_info:
                parent_category = TAG_TYPE.getDesc(parent.category_type)
                parent_info = '-> %s:%s/%s \n' % (parent.id, parent.name, parent_category)
                self.all_category_info[child.id]['parent_category'].append(parent_info)
            else:
                pass

        tags = Tag.objects.exclude(tag_type=TAG_TYPE.FREE)
        for tag in tags:
            child_tags = tag.child_tags()
            if not child_tags:
                continue
            try:
                seo_category = SeoCategory.objects.get(tag_id=tag.id)
            except Exception as e:
                print(e.message)
                continue
            for child_tag in child_tags:
                if child_tag.tag_type == TAG_TYPE.FREE:
                    continue
                try:
                    child_seo_category = SeoCategory.objects.get(tag_id=child_tag.id)
                except Exception as e:
                    print(e.message)
                    continue
                CategoryRelation.objects.get_or_create(parent_category=seo_category,
                                                       child_category=child_seo_category)
                add_parent_info(seo_category, child_seo_category)
                add_child_info(seo_category, child_seo_category)

    def export_seo_info(self):
        workbook = xlwt.Workbook(encoding='utf-8')
        sheet = workbook.add_sheet(u'Tag SEO分类')
        columns_name = [u'SEO词id', u'标签id', u'SEO词名称', u'关联百科+百科id', u'标签类型', u'图标', u'横幅',
                        u'显示日记本', u'描述', u'上级标签', u'下级标签']
        columns_key = ['tag_id', 'name', 'wiki', 'category_type', 'icon', 'banner', 'show_diary',
                       'desc_md', 'parent_category', 'child_category']
        for column, name in enumerate(columns_name):
            sheet.write(0, column, name)

        for line_num, category in enumerate(self.all_category_info, start=1):
            sheet.write(line_num, 0, category)
            for column_num, column_key in enumerate(columns_key, start=1):
                category_info = self.all_category_info[category]
                sheet.write(line_num, column_num, category_info[column_key])

        workbook.save('Tag与SEO对应关系及信息.xls')
        print(u'export finished')

    def handle(self, *args, **kwargs):
        self.tag_to_seo_category()
        self.create_seo_category_relation()
        self.export_seo_info()

